如何将bquote与ggplot2 geom_label结合使用? [英] How to use bquote in combination with ggplot2 geom_label?

查看:179
本文介绍了如何将bquote与ggplot2 geom_label结合使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读以下文章: https://trinkerrstuff.wordpress.com/2018/03/15/2246/

I've read the following article: https://trinkerrstuff.wordpress.com/2018/03/15/2246/

现在,我正在尝试在情节中将建议的方法与bquote一起使用.但是我无法使它正常工作.我有以下代码

Now I'm trying to use the suggested approach with bquote in my plot. However I can't get it to work. I have the following code

x <- seq(0, 2*pi, 0.01)
y <- sin(x)
y_median <- median(y)
ggplot(mapping = aes(x = x, y = y)) + 
  geom_line() + 
  geom_label(aes(label = bquote("median" ~ y==~.y_median), x = 1, y = y_median))

我收到以下错误:

Error in as.data.frame.default(x[[i]], optional = TRUE) : 
  cannot coerce class ‘"formula"’ to a data.frame

我在做什么错了?

推荐答案

ggplot不喜欢使用geom_textgeom_label层中标签的表达式.它喜欢使用字符串.因此,您可以这样做

ggplot doesn't like to work with expressions for labels in geom_text or geom_label layers. It likes to work with strings. So instead you can do

ggplot(mapping = aes(x = x, y = y)) + 
  geom_line() + 
  annotate("text", label = deparse(bquote("median" ~ y==~.(y_median))), x = 1, y = y_median, parse=TRUE)

我们使用deparse()将其转换为字符串,然后使用parse=TRUE使ggplot将其解析回表达式.另外我在这里只使用了annotate(),因为您根本没有将这个值映射到您的数据.

We use deparse() to turn it into a string, then use parse=TRUE to have ggplot parse it back into an expression. Also I just used annotate() here since you aren't really mapping this value to your data at all.

这篇关于如何将bquote与ggplot2 geom_label结合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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