Let\'s assume we have the following data frame
data <- data.frame(time=1:10, y1=runif(10), y2=runif(10), y3=runif(10))
and we want to create
This is old now but in case anyone else comes across it, I had a very similar problem that was driving me crazy. The solution I found was to pass aes_q()
to geom_line()
using the as.name()
option. You can find details on aes_q()
here. Below is the way I would solve this problem, though the same principle should work in a loop. Note that I add multiple variables with geom_line()
as a list here, which generalizes better (including to one variable).
varnames <- c("y1", "y2", "y3")
add_lines <- lapply(varnames, function(i) geom_line(aes_q(y = as.name(i), colour = i)))
p <- ggplot(data, aes(x = time))
p <- p + add_lines
plot(p)
Hope that helps!