Search code examples
rggplot2plotmath

R / ggplot2: Evaluate object inside expression


Example code:

rsq <- round(cor(mtcars$disp, mtcars$mpg)^2, 2) # rsq = 0.72

ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point() +
  geom_smooth(method = lm, aes(color = "Linear")) +
  scale_color_discrete(labels = expression(paste("R"^2, " = ", rsq)))

I would like the legend to be displayed as R² = 0.72.
I know I can just use the unicode symbol for ² to get the superscript, but in general I think there has to be a way to combine math expressions and calculated values stored in objects.

I have tried to play around with eval and various combinations of paste, but it seems I keep running into the same problem.

Edit #1:
I tried using bquote according to this answer like this:

scale_color_discrete(labels = bquote(R^2 == .(rsq)))

Turns out that only renders the legend as ==.

Edit #2:
Even though the answer below works, it seems… very inconvenient for more complex expressions, like this:

I'm still hoping for a simpler solution.


Solution

  • Turns out the bquote thing was close.
    This works (although it feels… suboptimal):

      scale_color_discrete(labels = as.expression(bquote(R^2~"="~.(rsq))))
    

    Also working:

     scale_color_discrete(labels = as.expression(bquote(R^2 == .(rsq))))
    

    Apparently the ~ are required to "paste" the elements together, without actually paste()ing them? And as.expression does what expression couldn't. I'm not sure what exactly is going on, but alas, it works:

    Thanks a lot, Peter Dalgaard!