R / ggplot2: evaluate an object inside an expression

Code example:

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 appear as R² = 0.72.
I know that I can simply use the Unicode character for ² to get a superscript, but overall I think there should be a way to combine mathematical expressions and calculated values ​​stored in objects.

I tried to play with evaland various combinations paste, but it seems that I am constantly facing the same problem.

Edit # 1:
I tried using bquotein accordance with for this answer as follows:

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

It turns out that only the legend is displayed as ==.

№2:
, , ... , :

.

+4
1

bquote. ( ... ):

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

:

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

-, ~ "" , paste() ? as.expression , expression . , , , , :

, Peter Dalgaard!

+4

All Articles