R/ggplot2:计算表达式内的对象

R/ggplot2:计算表达式内的对象,r,ggplot2,plotmath,R,Ggplot2,Plotmath,示例代码: 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)))

示例代码:

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)))

rsq结果是
bquote
的事情已经结束了。
这是可行的(尽管感觉……不太理想):

还工作:

 scale_color_discrete(labels = as.expression(bquote(R^2 == .(rsq))))
显然,
~
需要将元素“粘贴”在一起,而不是实际粘贴它们?而
as.expression
做了
expression
做不到的事情。我不确定到底发生了什么,但唉,它起作用了:


非常感谢

我注意到,从ggplot2软件包的3.3.2版开始,
scale\u color\u discrete()
scale\u color\u manual()
现在都直接接受
bquote()
标签。这一变化可能更广泛地应用于其他
scale\uu
函数,但我还没有进行更广泛的测试

然而,像
geom_线(aes(color=bquote(…)))
geom_线(aes(color=as.expression(bquote(…))))
这样的简单方法仍然被拒绝,因为它们具有无效的美学效果

data = data.frame(x = seq(0, 5, length.out = 50))
data$exp1 = 1 - exp(-data$x)
data$exp0.5 = 1 - exp(-0.5 * data$x)
ggplot(data, aes(x = x)) + geom_line(aes(y = exp1, color = "exp1")) + 
  geom_line(aes(y = exp0.5, color = "exp0.5")) +
  scale_color_manual(labels = c(bquote(1 - e^-x), bquote(1 - e^"-0.5x")), values = c("blue", "green")) + # or scale_color_discrete(labels = c(bquote(1 - e^-x), bquote(1 - e^"-0.5x")))
  labs(y = "y") + theme(legend.position = c(0.8, 0.15))

data = data.frame(x = seq(0, 5, length.out = 50))
data$exp1 = 1 - exp(-data$x)
data$exp0.5 = 1 - exp(-0.5 * data$x)
ggplot(data, aes(x = x)) + geom_line(aes(y = exp1, color = "exp1")) + 
  geom_line(aes(y = exp0.5, color = "exp0.5")) +
  scale_color_manual(labels = c(bquote(1 - e^-x), bquote(1 - e^"-0.5x")), values = c("blue", "green")) + # or scale_color_discrete(labels = c(bquote(1 - e^-x), bquote(1 - e^"-0.5x")))
  labs(y = "y") + theme(legend.position = c(0.8, 0.15))