Let's say I have a plot like this
library(ggplot2)
ggplot(mtcars, aes(x=wt)) + ylab("") +
geom_line(aes(y=mpg, color="one")) +
geom_line(aes(y=qsec, color="two")) +
scale_color_manual(name="Val", values=c(one="#105B63",two="#BD4932"))
where I am plotting two lines and specifying a color group for each. Now let's say I want to specify the variables names dynamically as character values which means I'll need to use aes_string().
If I try
v1<-"mpg"
v2<-"qsec"
ggplot(mtcars, aes(x=wt)) + ylab("") +
geom_line(aes_string(y=v1, color="one")) +
geom_line(aes_string(y=v2, color="two")) +
scale_color_manual(name="Val", values=c(one="#105B63",two="#BD4932"))
I get the error
Error in eval(expr, envir, enclos) : object 'one' not found
because now aes_string()
is trying to parse the color value when I just want a literal character value. And if I try
ggplot(mtcars, aes(x=wt)) + ylab("") +
geom_line(aes_string(y=v1), aes(color="one")) +
geom_line(aes_string(y=v2), aes(color="two")) +
scale_color_manual(name="Val", values=c(one="#105B63",two="#BD4932"))
I get
Error: ggplot2 doesn't know how to deal with data of class uneval
presumably because the layer doesn't know how to handle two aesthetic directives.
How can I combine aes()
and aes_string()
aesthetics or how can I specify literal character values for aes_string()
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…