Search code examples
rdataframeggplot2facet-wrapline-plot

How to line plot columns from multiple data frame in R?


Thought it would be easy but am running out of ideas here. I have three data.frame that I would like to plot in a single figure such that plot-A would contain line plots using data of column A from all the data.frame i.e., DF1,DF2,DF3, plot-B should contain line plots using data of column B from all data.frame and likewise for C. In the past I use facet_wrap, however, I have no idea how to go about this. here is my simple code which does not produce any plot but will give an idea what I want. A ggplot option would be great.

library(gridExtra)

DF1 = data.frame(Month = 1:12, A = runif(12, 1,10), B = runif(12,5,10), C = runif(12, 3,9))
DF2 = data.frame(Month = 1:12, A = runif(12, 4,13), B = runif(12,6,14), C = runif(12, 3,12))
DF3 = data.frame(Month = 1:12, A = runif(12, 2,15), B = runif(12,1,9), C = runif(12, 3,15))

G1 = plot(DF1$Month, y=DF1$A, "l")
lines(DF2$A, col = "red")
lines(DF3$A, col = "blue")

G2 = plot(DF1$Month, y=DF1$B, "l")
lines(DF2$B, col = "red")
lines(DF3$B, col = "blue")

G3 = plot(DF1$Month, y=DF1$C, "l")
lines(DF2$C, col = "red")
lines(DF3$C, col = "blue")

grid.arrange(G1,G2,G3, ncol = 3)

Note: in my example, I have three columns in each data.frame, however, I would like to apply the code over data.frame that have a large number of columns- not just three. so automating the process would help.


Solution

  • Like this

    The only manual step is giving each data.frame an identifying column (possibly automate using this? Add column containing data frame name to a list of data frames)

    Then you combine them all into one dataframe and gather the columns so that the data.frame is in long form. You can then use with facet_grid/facet_wrap as you mentioned

    DF1 = data.frame(Month = 1:12, A = runif(12, 1,10), B = runif(12,5,10), C = runif(12, 3,9))
    DF2 = data.frame(Month = 1:12, A = runif(12, 4,13), B = runif(12,6,14), C = runif(12, 3,12))
    DF3 = data.frame(Month = 1:12, A = runif(12, 2,15), B = runif(12,1,9), C = runif(12, 3,15))
    
    
    DF1$df <- "1"
    DF2$df <- "2"
    DF3$df <- "3"
    
    library(tidyr)
    library(ggplot2)
    AllDf <- rbind(DF1,DF2,DF3)
    
    AllDf_l <- AllDf %>% gather(Var,Value, A:C)
    
    ggplot(AllDf_l, aes(x = Month, y = Value, colour = df))+geom_line()+
      facet_grid(Var~.)