I'm trying to create a function that plots an image based on a given data and label the image according to an input variable (which currently I have as a string). I would like to make the labels friendly to math expressions, but I'm running into trouble with that.
I tried to use functions like expression
, parse
or bquote
and the best I managed was to:
- make only symbols from
plotmath
work - get partial proper math formatting (see example for sub- and superscripts - I couldn't put the subscript for the 1 without printing parenthesis as well, but I didn't research much on that)
library(ggplot2)
myFunc <- function(givenData,myString){
myplot <- ggplot(givenData, aes(x = x, y = y)) +
geom_point() +
labs(title = bquote("My plot for" ~ .(parse(text = myString)[[1]])), x = "", y = "")
print(myplot)
}
df <- data.frame(
x = c(1, 2, 3, 4, 5),
y = c(2, 3, 4, 5, 6)
)
myFunc(df,myString = "text >= (1^2)[3]")
myFunc(df,myString = "`text with spaces`")
myFunc(df,myString = "`testing text \u2192`")
(With those functions I also tried to change myString
into a function output instead of a string, but I didn't get anywhere with that.)
I also tried to use simple unicode instead, which achieves:
- all unicode symbols appear
- however I lose the math formatting capability
library(ggplot2)
mysecFunc <- function(givenData,myString){
myplot <- ggplot(givenData, aes(x = x, y = y)) +
geom_point() +
labs(title = paste("My plot for", myString), x = "", y = "")
print(myplot)
}
df <- data.frame(
x = c(1, 2, 3, 4, 5),
y = c(2, 3, 4, 5, 6)
)
mysecFunc(df,myString = "text >= 1^2[3]")
mysecFunc(df,myString = "text with spaces")
mysecFunc(df,myString = "testing text \u2192")
How can I pass the myString
argument in such a way that math expressions are properly treated? I want to
0. have a prefix text inside my function (the "My plot for"
in the mwes)
- be able to use any unicode character, not only those from
plotmath
1.optional be able to use latex expressions would be even better - be able to do math formatting like sub- and superscripts
If relevant, I'm writing this all in R chunks inside a quarto document in RStudio for windows. I didn't do any testing regarding the rendering, but I would also like to: 3. have the resulting plot label be rendered correctly (for example, in html output)
I guess I can go around 3 by saving the plots as an image, but it would be nice to not have to do so. I use ggplot2
because in my actual use the function will be producing a heatmap rather than a simple plot.
All questions related to labeling that I could find did not translate well to the function case with an inbuilt prefix. Related but unsolved question: ggplot2 custom facet labeller with math notation