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.

1

1 Answer 1

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)
})
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, thank you! The mapply function somehow did not work at first but with the purrr package everything worked smoothly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.