How to plot multiple graphs on ggplots with lapply

library(ggplot2)
x<-c(1,2,3,4,5)
a<-c(3,8,4,7,6)
b<-c(2,9,4,8,5)

df1 <- data.frame(x, a, b)

x<-c(1,2,3,4,5)
a<-c(6,5,9,4,1)
b<-c(9,5,8,6,2)

df2 <- data.frame(x, a, b)

df.lst <- list(df1, df2)

plotdata <- function(x) {
  ggplot(data = x, aes(x=x, y=a, color="blue")) + 
    geom_point() +
    geom_line()
}

lapply(df.lst, plotdata)

      

I have a list of dataframes and I am trying to plot the same columns on the same ggplot. I tried with the code above, but it seems to only return one plot.

There should be 2 ggplots. one with data in column "a" and the other with data in column "b" plotted from both data frames in the list.

I've looked through a lot of examples and it seems like it should work.

+3


source to share


2 answers


If you want them to be on the same plot, it's simple:

ggplot(data = df1, aes(x=x, y=a), color="blue") + 
  geom_point() +
  geom_line() +
  geom_line(data = df2, aes(x=x, y=a), color="red") +
  geom_point(data = df2, aes(x=x, y=a), color="red")

      

Edit: if you have multiple of them, you are probably better off combining them with a large dataset while keeping the source df for aesthetic use. Example:



df.lst <- list(df1, df2)

# put an identifier so that you know which table the data came from after rbind
for(i in 1:length(df.lst)){
  df.lst[[i]]$df_num <- i
}
big_df <- do.call(rbind,df.lst) # you could also use `rbindlist` from `data.table`

# now use the identifier for the coloring in your plot
ggplot(data = big_df, aes(x=x, y=a, color=as.factor(df_num))) + 
    geom_point() +
    geom_line() + scale_color_discrete(name="which df did I come from?")
    #if you wanted to specify the colors for each df, see ?scale_color_manual instead

      

enter image description here

+3


source


They are both built. If you are using RStudio, click the back arrow to switch between graphs. If you want to see them together, follow these steps:

library(gridExtra)
do.call(grid.arrange,lapply(df.lst, plotdata))

      



enter image description here

+3


source







All Articles