0

I am trying to create plots with ggplot for 20 data frames ("df1" - "df20") that are contained in a list called "list1". The list looks like this:

list1 <- list(df1, df2, ..., df20)

Each data frame has two columns z and y that I want to plot against each other:

df1
z  y
1  6
2  9
3  7

I have created the following code which also works but it does not provide the plots with the respective titles from df1 to df20:

lapply(list1, function(x) 
  ggplot(data = list1$x) + 
    geom_line(mapping = aes(x = x$z, 
                          y = x$y)))

I have tried putting all names in a vector and including this vector in the code like this:

titlenames <- c(df1, df2, ..., df20)

+ ggtitle(titlenames) 

but this only provides the first name for all plot.

Would appreciate any help with this as I am still quite new to R.

Soph2010
  • 563
  • 3
  • 13
  • Not related to the title specifically, but [don't put `$` inside your `aes`](https://stackoverflow.com/questions/32543340/issue-when-passing-variable-with-dollar-sign-notation-to-aes-in-combinatio) – camille May 08 '19 at 15:08

1 Answers1

2

You could try using mapply (similar to lapply but takes the function first, and can iterate through more than one equal-length list/vector) with the list of data and the vector of names:

mapply(function(df, titlename) {
    ggplot(data = df) + 
        geom_line(mapping = aes(x = z, y = y)) +
        ggtitle(titlename)
}, list1, titlenames)

I find that because the format of mapply differs from lapply, it is hard to remember. The package purrr provides what I think is a cleaner alternative:

purrr::map2(list1, titlenames, function(df, titlename) {
    ggplot(data = df) + 
        geom_line(mapping = aes(x = z, y = y)) +
        ggtitle(titlename)
})
C. Braun
  • 5,061
  • 19
  • 47
  • Awesome, thank you! The mapply function somehow did not work at first but with the purrr package everything worked smoothly. – Soph2010 May 08 '19 at 15:52