2

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?

www
  • 38,575
  • 12
  • 48
  • 84
laroof
  • 23
  • 2

2 Answers2

4

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) )

enter image description here

Nate
  • 10,361
  • 3
  • 33
  • 40
  • Thanks kindly Nate, that works. I'm still trying to wrap my head around map2. It's not as intuitive to me as the dplyr functions I'm familiar with, but that may be a function of me being more researcher than programmer. Cheers. – laroof Dec 06 '17 at 00:30
  • `map2` is very similar to `mapply`, in that it is designed to iterate over two list objects in pairs (so list1[1] is paired with list2[1]). In the `map2` here we are going over the split list being passed in via pipe (subsequently referred to as `.`) and the names of that same split list as the second list, `.y`. [Jenny Bryan's purrr turotial](https://jennybc.github.io/purrr-tutorial/) is a great place to start learning `purrr`. – Nate Dec 06 '17 at 00:51
1

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=" - ")))

enter image description here

M--
  • 25,431
  • 8
  • 61
  • 93