R/ggplot2:评估表达式内的对象 [英] R / ggplot2: Evaluate object inside expression

查看:77
本文介绍了R/ggplot2:评估表达式内的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例代码:

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

我希望图例显示为R² = 0.72.
我知道我可以使用unicode符号来表示²,但总的来说,我认为必须有一种方法可以将数学表达式和存储在对象中的计算值结合起来.

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.

我曾尝试使用evalpaste的各种组合,但似乎我一直遇到相同的问题.

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

编辑#1:
我尝试根据对此答案使用bquote 像这样:

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 ==.

编辑#2:
即使下面的答案有效,对于更复杂的表达式,似乎也很不方便,例如:

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.

推荐答案

结果显示bquote内容已关闭.
可行(尽管感觉……不是最理想的):

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

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

也在工作:

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

显然需要~来将元素粘贴"在一起,而不实际地paste()粘贴它们吗?而as.expressionexpression做不到的.我不确定到底是怎么回事,但是works,它行得通:

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:

非常感谢,彼得·达尔加德

这篇关于R/ggplot2:评估表达式内的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆