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)
}
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:
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
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
But is there any reason for it to not produce the same result in a loop?
Required packages:
require(ggplot2)
require(reshape2)