rggplot2lapplyggtitle

How attach names of a list within ggtitle into a map function


I would have the follwing example

plot_list2 = split(mtcars, mtcars$cyl) %>% 
              map(function(q) ggplot(q, aes(x= mpg)) + 
                 geom_histogram(aes(y=..density..), 
                 color="darkblue", fill="lightblue")+ 
                 geom_density(alpha=.2, fill="#FF6666") + 
                 theme_classic()+ 
                 ggtitle(sprintf('Distribution for', names(q))))

My aim is to use a unique code so that in the ggtitle I can attach each names for the list on top generated with split. What should I change here?

Thanks


Solution

  • I will do like this:

    library(dplyr)
    library(purrr)
    plot_list2 = split(mtcars, mtcars$cyl) %>%
      map(function(q) ggplot(q, aes(x= mpg)) + 
            geom_histogram(aes(y=..density..), 
                           color="darkblue", fill="lightblue")+ 
            geom_density(alpha=.2, fill="#FF6666") + 
            theme_classic()+
              labs(title = paste0("distribution for cyl ",unique(q$cyl))))
    

    because cyl is unique in each element of the list created with split you can use the values of cly to plot the title. Here I used labs instead of GGtitle but should be the same. Furthermore you do not need necessarily purrr::map. The base::lapply here works the same. Remember to explicit the library you use in the example code (i.e. library(dyplr) and library(purrr)