0

Here is reproducible dataframe:

example_df <- data.frame(rnorm1 = rnorm(100), 
                       rnorm2 = rnorm(100), 
                       rnorm3 = rnorm(100), 
                       id = (1:100))

I'd like to plot it in this manner:

plot(example_df[,1], type = 'l')
for(i in 2:3) {
  lines(example_df[,i], col = i)
}

Base plot

But base plot is not convenient for further additions so I want to use ggplot. However, why is it not possible to use the same loop approach?

g1 <- ggplot(example_df, aes(seq(length(example_df[,1]))))
for(i in 1:3) {
  g1 <- g1 + geom_line(aes(y=example_df[,i], colour=colnames(example_df)[i]))
}
g1

This only saves the last line:

ggplot2 example 1

Now, I can obviously do the same without the loop and it will obviously be incovenient for more than 3 lines:

g2 <- ggplot(example_df, aes(seq(length(example_df[,1])))) 
g2 <- g2 + geom_line(aes(y=example_df[,1], colour=colnames(example_df)[1]))
g2 <- g2 + geom_line(aes(y=example_df[,2], colour=colnames(example_df)[2]))
g2 <- g2 + geom_line(aes(y=example_df[,3], colour=colnames(example_df)[3]))
g2

ggplot2 example 1

I can also melt the df and get the desired plot:

example_df_melt <- melt(example_df, id.vars = 'id', variable.name = 'variable')
g3 <- ggplot(example_df_melt, aes(id,value)) + geom_line(aes(colour = variable))
g3

enter image description here

But is there any reason for it to not produce the same result in a loop?

Required packages:

require(ggplot2)
require(reshape2)
aurora
  • 77
  • 1
  • 5
  • https://stackoverflow.com/questions/32698616/ggplot2-adding-lines-in-a-loop-and-retaining-colour-mappings has some good info – e.matt Feb 10 '20 at 19:02

1 Answers1

0

ggplot is not intended to be used in this way. If you restructure your data slightly, you can avoid using a loop altogether:

example_df <- data.frame(y = c(rnorm(100), rnorm(100), rnorm(100)),
                         group = rep(c("rnorm1", "rnorm2", "rnorm3"), each = 100),
                         id = rep((1:100), 3))

ggplot(example_df, aes(y=y, x=id, colour=group))+
  geom_line()
Jordan Hackett
  • 689
  • 3
  • 11