Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot2 using variable expressions in legend name

Tags:

r

ggplot2

I am trying to plot a series of time series with ggplot2 that sometimes have greek names. As the plot uses dynamic names (i.e. the names of the variables are stored within another variable) I am having troubles to get it to work.

Here is an example:

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

Do you have any idea of how I can evaluate the variable nam to be displayed as the name of the legend as in option 2? Thank you very much!

like image 570
David Avatar asked Dec 24 '22 16:12

David


1 Answers

Using this code

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

This gives me the plot you probably wanna see. No eval in name = eval(name) and no blockquotes in the assignment nam <- expression(alpha[i])

enter image description here

like image 94
symbolrush Avatar answered Dec 28 '22 06:12

symbolrush