ggplot: aes vs aes_string, or how to programmatically specify column names?

前端 未结 3 1313
别那么骄傲
别那么骄傲 2021-02-15 01:29

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

3条回答
  •  野的像风
    2021-02-15 02:20

    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!

提交回复
热议问题