0

I would like to successively add lines to a ggplot object. But I can't get the following supposedly simple code to work:

The data frame contains time series which I want to plot for periods 0 to 20.

p <- ggplot(data=dfp, aes(x=seq(0,20,1), y=dfp) )

for (i in 1:7) {
  p <- p + geom_line(aes(y=dfp[i]))
}

p  
shadow
  • 21,823
  • 4
  • 63
  • 77
hannes
  • 31
  • 1
  • 1
  • 3
    A `dput(dfp)` would help. The error or errant output you're getting plus expected output would help. And, if there's no `dfp` column in the `dfp` data frame, this won't work at all. – hrbrmstr Jan 09 '15 at 01:46
  • 2
    Just `melt` your data. – Gregor Thomas Jan 09 '15 at 02:02
  • Provide a sample data so that we can help you !!! – Koundy Jan 09 '15 at 04:00
  • http://stackoverflow.com/questions/15987367/how-to-add-layers-in-ggplot-using-a-for-loop – CMichael Jan 09 '15 at 06:43
  • +++1 for Gregor. If you hit a bit of a block trying to do something in ggplot2, the chances are your data needs tidying. Use reshape2::melt or tidyr::gather and then its a ggplot one-liner and you get a nice legend if you want it too. I'll give an answer if you give sample data and if there isn't a previous answer anywhere else (which there probably is). – Spacedman Jan 09 '15 at 09:22
  • Thank you guys a lot! My bad, it wasnt really the code for ggplot2, it was a problem with the content of the data frame (got the data manipulations wrong, so all ts had same values^^) – hannes Jan 10 '15 at 02:13

2 Answers2

5

Easiest way is to use aes_string instead of aes.

# load necessary package
require(ggplot2)
# create sample data
dfp <- data.frame(matrix(rnorm(147), nrow=21))
# original plot (removed unnecessary call to y)
p <- ggplot(data=dfp, aes(x=seq(0,20,1)))
# loop
for (i in 1:7) {
  # use aes_string with names of the data.frame
  p <- p + geom_line(aes_string(y = names(dfp)[i]))
}
# print the result
print(p)
shadow
  • 21,823
  • 4
  • 63
  • 77
2

Using the same dfp from shadow's answer:

library(tidyr)
library(dplyr)

and then:

dfp %>% gather() %>% group_by(key) %>% 
        mutate(x=1:n()) %>%
        ggplot(aes(x=x, y=value,group=key)) + geom_line()

ggplot from tidy data

add colour=key to the aes() call if you also want a legend. Try running parts of the pipe to see what gather and the other bits do.

Spacedman
  • 92,590
  • 12
  • 140
  • 224