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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.