设置ggplot标题以反映dplyr分组 [英] Set ggplot title to reflect dplyr grouping

查看:103
本文介绍了设置ggplot标题以反映dplyr分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在dplyr中生成了一个分组数据框,其中每个组都反映了因子变量水平的唯一组合。我想使用类似于


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?

解决方案

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

这篇关于设置ggplot标题以反映dplyr分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆