Use for loop to plot multiple lines in one chart with ggplot2

I am trying to build several lines in one graph as follows:

y <- matrix(rnorm(100), 10, 10) m <- qplot(NULL) for(i in 1:10) { m <- m + geom_line(aes(x = 1:10, y = y[,i])) } plot(m) 

However, it seems that qplot will parse m during plot(m) , where i is 10 , so plot(m) only creates one line.

What I expect to see is like:

 plot(1,1,type='n', ylim=range(y), xlim=c(1,10)) for(i in 1:10) { lines(1:10, y[,i]) } 

which should contain 10 different lines.

Is there any way ggplot2 do this?

+4
source share
2 answers

Instead of chopping a loop, you should do it in the ggplot2 way. ggplot2 wants data in a long format (you can convert it with reshape2 :: melt ()). Then split the rows by column (here Var2).

 y <- matrix(rnorm(100), 10, 10) require(reshape2) y_m <- melt(y) require(ggplot2) ggplot() + geom_line(data = y_m, aes(x = Var1, y = value, group = Var2)) 

enter image description here

+9
source

The proposed EDi is the best way. If you still want to use a for loop, you need to use a for loop to generate a data frame.

as below:

 # make the data > df <- NULL > for(i in 1:10){ + temp_df <- data.frame(x=1:10, y=y[,i], col=rep(i:i, each=10)) + df <- rbind(df,temp_df)} > ggplot(df,aes(x=x,y=y,group=col,colour=factor(col))) + geom_line() # plot data 

It is output:

enter image description here

+5
source

All Articles