r - how to add layers in ggplot using a for-loop -


i plot each column of dataframe separate layer in ggplot2. building plot layer layer works well:

df<-data.frame(x1=c(1:5),y1=c(2.0,5.4,7.1,4.6,5.0),y2=c(0.4,9.4,2.9,5.4,1.1),y3=c(2.4,6.6,8.1,5.6,6.3))  ggplot(data=df,aes(df[,1]))+geom_line(aes(y=df[,2]))+geom_line(aes(y=df[,3])) 

is there way plot available columns @ ones using single function?

i tried way not work:

    plotalllayers<-function(df){     p<-ggplot(data=df,aes(df[,1]))     for(i in seq(2:ncol(df))){          p<-p+geom_line(aes(y=df[,i]))         }         return(p)     }  plotalllayers(df) 

one approach reshape data frame wide format long format using function melt() library reshape2. in new data frame have x1 values, variable determine column data came, , value contains original y values.

now can plot data 1 ggplot() , geom_line() call , use variable have example separate color each line.

 library(reshape2)  df.long<-melt(df,id.vars="x1")  head(df.long)   x1 variable value 1  1       y1   2.0 2  2       y1   5.4 3  3       y1   7.1 4  4       y1   4.6 5  5       y1   5.0 6  1       y2   0.4  ggplot(df.long,aes(x1,value,color=variable))+geom_line() 

enter image description here

if want use for() loop (not best way) should use names(df)[-1] instead of seq(). make vector of column names (except first column). inside geom_line() use aes_string(y=i) select column name.

plotalllayers<-function(df){   p<-ggplot(data=df,aes(df[,1]))   for(i in names(df)[-1]){      p<-p+geom_line(aes_string(y=i))   }   return(p) }  plotalllayers(df) 

enter image description here


Comments

Popular posts from this blog

c++ - How to modify context menu of internet explorer using IDocHostUIHandler::ShowContextMenu? -

c# - Getting "Internal .Net Framework Data Provider error 30" error when column has NULL value -

android - Spacing between the stars of a rating bar? -