R ggplot2在图例名称中使用变量表达式

时间:2015-07-31 09:35:17

标签: r ggplot2

我试图用ggplot2绘制一系列时间序列,有时会有希腊名字。由于绘图使用动态名称(即变量的名称存储在另一个变量中),因此无法使其工作。

以下是一个例子:

# create some data
df <- data.frame(time = rep(1:10, 3), 
                 variable = rep(letters[1:3], each = 10), 
                 val = rnorm(30))

# create a variable for the group name
nam <- expression("alpha[i]")

library(ggplot2)
# plot the data as a line
ggplot(df, aes(x = time, y = val, color = variable)) + 
   geom_line() + 
   # Option 1: Does not work
   scale_color_discrete(name = eval(nam)) 
   # Option 2: works but has no variable input
   # scale_color_discrete(name = expression(alpha[i])) 

您是否知道如何评估变量nam作为选项2中的图例名称显示? 非常感谢你!

2 个答案:

答案 0 :(得分:5)

使用此代码

# create some data
df <- data.frame(time = rep(1:10, 3), 
                 variable = rep(letters[1:3], each = 10), 
                 val = rnorm(30))

# create a variable for the group name
nam <- expression(alpha[i])

library(ggplot2)
# plot the data as a line
ggplot(df, aes(x = time, y = val, color = variable)) + 
  geom_line() + 
  # Option 1: Does not work
  scale_color_discrete(name = nam) 
# Option 2: works but has no variable input
#  scale_color_discrete(name = expression(alpha[i]))

这给了我你可能想看到的情节。 eval中没有name = eval(name),作业nam <- expression(alpha[i])

中没有块引用

enter image description here

答案 1 :(得分:3)

可能会有效:

nam <- "alpha[i]"
...
scale_color_discrete(name = eval(parse(text= nam)))