8

I try to plot multiple lines in single plot as follow:

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) produces single line only.

What I expect to see is similar to:

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 ggplot2 way to do this?

wush978
  • 3,114
  • 2
  • 19
  • 23

2 Answers2

11

Instead of ruuning a loop, you should do this the ggplot2 way. ggplot2 wants the data in the long-format (you can convert it with reshape2::melt()). Then split the lines via a 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

EDi
  • 13,160
  • 2
  • 48
  • 57
  • How would be the best way of setting up different colours of each line with this? For example the first line being red, the next being blue, etc... I could then put it into a legend. – James Ashwood Jul 12 '22 at 10:57
7

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

like 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

This outputs:

enter image description here

Harpal
  • 12,057
  • 18
  • 61
  • 74