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!
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With