How to use bquote in combination with ggplot2 geom_label?

你。 提交于 2019-12-05 17:43:52

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)

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.

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

Key points:

1.) I fixed the missing parentheses in "median" ~ y==~.(y_median). This is discussed in ?bquote help page:

‘bquote’ quotes its argument except that terms wrapped in ‘.()’ are evaluated in the specified ‘where’ environment.

2.) Put the bquote inside a list, because aes expects a vector or a list.

3.) Tell geom_label to parse the expression by the setting the corresponding parameter to TRUE.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!