Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to plot multiple plots on ggplots with lapply

Tags:

r

ggplot2

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 data frames and i am trying to plot the same columns on the same ggplot. I tried with the code above but it seems to return only one plot.

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

i've looked at many examples and it seems that this should work.

like image 334
CPL Avatar asked Jan 09 '23 01:01

CPL


1 Answers

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

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 several of these, you are probably better off combining them into a big data set while keeping the df of origin for use in the aesthetic. 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

like image 175
C8H10N4O2 Avatar answered Jan 15 '23 02:01

C8H10N4O2