Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use for loop to plot multiple lines in single plot with ggplot2

Tags:

r

ggplot2

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?

like image 233
wush978 Avatar asked Feb 05 '13 10:02

wush978


People also ask

How to plot multiple lines on same graph in r ggplot?

In this method to create a ggplot with multiple lines, the user needs to first install and import the reshape2 package in the R console and call the melt() function with the required parameters to format the given data to long data form and then use the ggplot() function to plot the ggplot of the formatted data.

How do you plot more than one variable in r?

You can create a scatter plot in R with multiple variables, known as pairwise scatter plot or scatterplot matrix, with the pairs function. In addition, in case your dataset contains a factor variable, you can specify the variable in the col argument as follows to plot the groups with different color.

How do I add a line to my plot in R?

The R function abline() can be used to add vertical, horizontal or regression lines to a graph. A simplified format of the abline() function is : abline(a=NULL, b=NULL, h=NULL, v=NULL, ...)


2 Answers

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

like image 114
EDi Avatar answered Jan 04 '23 19:01

EDi


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

like image 37
Harpal Avatar answered Jan 04 '23 21:01

Harpal