r - 设置 ggplot 标题以反射(reflect) dplyr 分组

标签 r ggplot2 dplyr

我在 dplyr 中生成了一个分组数据框,其中每个组反射(reflect)了因子变量水平的独特组合。我想使用类似于 this 的代码绘制不同的组邮政。但是,我不知道如何在图的标题中包含两个(或更多)变量,这很麻烦,因为我有一堆不同的组合。

虚假数据和绘图代码:

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

我需要每个图的标题来反射(reflect)“地点”和“物种”。有什么想法吗?

最佳答案

使用 split() %>% purrr::map2() 而不是 group_by() %>% do(),如下所示:

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

关于r - 设置 ggplot 标题以反射(reflect) dplyr 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47661847/

相关文章:

r - 基于 2 个其他列查找一列的平均值 RStudio

r - install.packages ("methods") R 3.0.1 失败

r - 当值首先超过阈值然后保持高于阈值时获取行

r - 根据条件对多列进行变异,每一列都有不同的设置

r - 使用dplyr中的mutate_each将所有数字变量转换为因数

r - 如何在R中的圆形图上更改轴标签方向

r - 控制光栅图图例标签以在 r 中显示指定的中断值

r - 使用 ggplot2 的 Github 版本运行 ggrepel 时,zero_range() 出现错误

r - ggplot2,如何在 geom_text 中跳过 NA

r - 使用 ggplot2 绘制误差线时抑制一些交叉线