Alternatives to combination to paste and parse functions using ggplot2

I'm trying to construct a general function to generate some graphics. So I have to create an axis label that combines an expression and a string. I've tried:

i <- 2
measure <- c(expression((kg/m^2)), "(%)")
variable <- c("BMI", "Cintilografia 1h")
data <- data.frame(x = 0, y = 0)
gp <- ggplot(data, aes(x = x, y = y)) +
  geom_point() +
  labs(y = parse(text = paste(variable[i], measure[i])))

It works for i = 1, but for i = 2.

I discovered parse function has some problems with special characters. I would prefer that the user-function does not to worry about these features. Then, I'm looking for a more general solution.

Does anyone have any idea? Thanks in advance

Upvotes: 1

Views: 580

Answers (1)

MrFlick
MrFlick

Reputation: 206167

Trying to paste and parse isn't a great idea when working with labels where you want to use ?plotmath markup. It's better to work with expressions. The bquote() function makes it somewhat easier to pop in values into expressions. This should work for you

i<-1
g1<-ggplot(data, aes(x = x, y = y)) +
  geom_point() +
  labs(y = bquote(.(variable[i])~.(measure[[i]])))
i<-2
g2<-ggplot(data, aes(x = x, y = y)) +
  geom_point() +
  labs(y = bquote(.(variable[i])~.(measure[[i]])))

gridExtra::grid.arrange(g1,g2, ncol=2)

Also note that when using bquote() on the measure object, since it's an expression, you want to extract the sub-expressions with [[ ]] rather than [ ] because the latter always wraps the result in an expression() and plotmath doesn't like nested expressions -- you want proper call objects.

enter image description here

Upvotes: 2

Related Questions