2

To feed to a function that creates a ggplot, I want to build up an axis title (for facets). The fixed part of the title always contains a superscript and the variable part sometimes contains a superscript. In the example below, the fixed part is “x-axes, R^2’s for “.

n.form = 2   

I could make x.labs.clunky by hand, using help from How do I pass a string of symbols for bquote to evaluate in ggplot? for a simpler question with no fixed component of the label.

x.labs.clunky <- c(expression("x-axes,"~R^2*s~'for'~Monthly),
   expression("x-axes,"~R^2*s~'for'~m^2))
ggplot() + geom_point(aes(x = 1, y = 1)) + 
   labs(x = x.labs.clunky[n.form])

But is there a better way, in which the fixed part is typed only once?

I tried to apply Use expression with a variable r. It prints correctly through 'for' but is blank after that.

x.labs.short <- data.frame(x = c("Monthly", "m^2"), stringsAsFactors = F)
ggplot() + geom_point(aes(x = 1, y = 1)) + 
   labs(x = bquote("x-axes,"~R^2~"for:"~.(x.labs.short$x[n.form])))          

Next print the literal x.labs.long.1 or x.labs.long.2

x.labs.long.1 <- paste0("x-axes,~R^2*s~’for’", x.labs.short$x)
ggplot() + geom_point(aes(x = 1, y = 1)) + 
   labs(x = eval(x.labs.long.1[n.form])) 

x.labs.long.2 <- paste0("bquote(x-axes,~R^2*s~’for’", x.labs.short$x, ")")
ggplot() + geom_point(aes(x = 1, y = 1)) + 
   labs(x = eval(x.labs.long.2[n.form])) 

The following fail to evaluate x.labs.long.1

x.labs.long.3 <- expression(x.labs.long.1)  
x.labs.long.3 <- expression(enquo(x.labs.long.1)) 

Finally, this one keeps everything after bquote as literal.

x.labs.long.4 <- bquote(paste0("x-axes,~R^2*s~’for’", .(x.labs.short$x)))

Thank you.

InColorado
  • 308
  • 2
  • 12

0 Answers0