Name multiple plots with lapply(ggplot + ggtitle) with nested list name accordingly

Viewed 420

My question is similar to this question but the difference is that my nested data frames in the list are named. How can I make multiple ggplots from a list of dataframes and have them on one pdf page?

The code below applied the same title to all my plots (I added ggtitle to the original one).
All the four graphs were named v1, which is the first column name in each df. I expected plots to be named df1,df2,..., or perhaps [[1]], [[2]],...

df1 <- data.frame(v1=c(1:5), v2=c(2:6))
df2 <- data.frame(v1=c(10:50), v2=c(20:60))
df3 <- data.frame(v1=c(100:500), v2=c(200:600))
df4 <- data.frame(v1=c(1000:5000), v2=c(2000:6000))
df.list <- list(df1, df2, df3, df4)

lapply(df.list, function(d) ggplot(data = d, aes(x=v1, y=v2)) + ggtitle(names(d)) + geom_point() )

How do I change my code? Thank you!

1 Answers

Try this also:

library(ggplot2)
#Names
names(df.list) <- paste0('df',1:4)
#Code
lapply(seq_along(df.list), function(i) {
  ggplot(df.list[[i]], aes(x=v1, y=v2)) + 
    geom_point()+ 
    ggtitle(names(df.list)[i]) })

Output:

enter image description here

enter image description here

enter image description here

enter image description here

And as @markus cited, you will need names in your list.

Related