how to add layers in ggplot using a for-loop

后端 未结 3 1421
我在风中等你
我在风中等你 2020-11-29 08:20

I would like to plot each column of a dataframe to a separate layer in ggplot2. Building the plot layer by layer works well:

df<-data.frame(x1=c(1:5),y1=c         


        
3条回答
  •  死守一世寂寞
    2020-11-29 09:12

    I tried the melt method on a large messy dataset and wished for a faster, cleaner method. This for loop uses eval() to build the desired plot.

    fields <- names(df_normal) # index, var1, var2, var3, ...
    
    p <- ggplot( aes(x=index), data = df_normal)
    for (i in 2:length(fields)) { 
      loop_input = paste("geom_smooth(aes(y=",fields[i],",color='",fields[i],"'))", sep="")
      p <- p + eval(parse(text=loop_input))  
    }
    p <- p + guides( color = guide_legend(title = "",) )
    p
    

    This ran a lot faster then a large melted dataset when I tested.

    I also tried the for loop with aes_string(y=fields[i], color=fields[i]) method, but couldn't get the colors to be differentiated.

提交回复
热议问题