How can I make `bquote` replace the greek letter stored in a variable with the symbol?

纵饮孤独 提交于 2019-12-11 15:22:10

问题


I want to label the axis on a plot dynamically. The labels come from a data frame and contain greek letters as well as super/sub scription.

In a static case, where I would know the letters of my labels, bquote would work well. But in the case, where the label-string comes from a variable, bquote fails.

This demonstrates what I want to achieve:

a <- "alpha"
b <- "beta"
ggplot(data.frame(x=c(1), y=c(1)), aes(x, y)) + 
  geom_point() +
  labs(x = bquote(.(a)[.(b)])) + ## will output the greek letters by "name"
  labs(y = bquote(alpha[beta]))  ## the greek letter-names are replaces by the symbols


回答1:


Turn the a and b variable into symbols with rlang::sym.

library("tidyverse")

a <- "alpha"
b <- "beta"

ggplot(data.frame(x = c(1), y = c(1)), aes(x, y)) +
  geom_point() +
  labs(x = bquote(.(sym(a))[.(sym(b))])) +
  labs(y = bquote(alpha[beta]))

Created on 2019-11-04 by the reprex package (v0.3.0)



来源:https://stackoverflow.com/questions/58685422/how-can-i-make-bquote-replace-the-greek-letter-stored-in-a-variable-with-the-s

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