1

I'm trying to get a dataframe name to use it as title in ggplot

#create dataframes
N1 <- N2 <- N3 <- N4 <- data.frame(matrix(1:12, 3, 4))

#list dataframes
mylist = list(N1, N2, N3, N4)

#rename dataframes in list
names(mylist) = c("N1", "N2", "N3", "N4")



#plot each ggplot using one data frame

myggplots =  lapply(mylist, function(x){
  require(ggplot2)
  a = ggplot(x, aes(x=X1, y = X2)) +
  geom_point() +
  ggtitle(paste0(x))
  a
})

If I access myggplots[[1]] , the title is not the name of the dataframe (N1 in this case). However, each plot object is named correctly after the dataframe that was used to create it

I tried many codes, without success. It is important to create a list of ggplots!

1 Answer 1

2

As it is a named list, we can use imap where the .y returns the name of the list element and .x the value of the element

library(ggplot2)
library(purrr)
out <- imap(mylist, ~ 
         ggplot(.x, aes(x = X1, y = X2)) + 
              geom_point() + 
              ggtitle(.y)
          )

With lapply, an option is to either loop over the sequence of list or the names and then extract the list element with [[

out <- lapply(names(mylist), function(nm)
            ggplot(mylist[[nm]], aes(x = X1, y = X2)) + 
               geom_point() + 
               ggtitle(nm)
      )

Or use Map

out <- Map(function(x, y) 
               ggplot(x, aes(x = X1, y = X2)) + 
                  geom_point() + 
                  ggtitle(y), 
                   mylist, names(mylist))
Sign up to request clarification or add additional context in comments.

2 Comments

These do work very well! Thank you for the very fast response. The only detail is that by using map or lapply I lose the naming of the list!
@GabrielG. When you extract the list element with [[, it extracts only the list element. Yes, lapply or Map, loops over the list and you don't have access to the outer names

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.