Set ggplot title to reflect dplyr grouping

2020-03-30 02:57发布

问题:

I've got a grouped dataframe generated in dplyr where each group reflects a unique combination of factor variable levels. I'd like to plot the different groups using code similar to this post. However, I can't figure out how to include two (or more) variables in the title of my plots, which is a hassle since I've got a bunch of different combinations.

Fake data and plotting code:

library(dplyr)
library(ggplot2)

spiris<-iris
spiris$site<-as.factor(rep(c("A","B","C")))
spiris$year<-as.factor(rep(2012:2016))  
spiris$treatment<-as.factor(rep(1:2))

g<-spiris %>% 
  group_by(site, Species) %>% 
  do(plots=ggplot(data=.) +
       aes(x=Petal.Width)+geom_histogram()+
       facet_grid(treatment~year))
       ##Need code for title here
g[[3]] ##view plots

I need the title of each plot to reflect both "site" and "Species". Any ideas?

回答1:

Use split() %>% purrr::map2() instead of group_by() %>% do() like this:

spiris %>% 
    split(list(.$site, .$Species)) %>%
    purrr::map2(.y = names(.),
         ~ ggplot(data=., aes(x=Petal.Width)) +
           geom_histogram()+
           facet_grid(treatment~year) +
           labs(title = .y) )



回答2:

You just need to set the title with ggtitle():

g <- spiris %>% group_by(site, Species) %>% do(plots = ggplot(data = .) + 
    aes(x = Petal.Width) + geom_histogram() + facet_grid(treatment ~ 
    year) + ggtitle(paste(.$Species,.$site,sep=" - ")))



标签: r ggplot2 dplyr