【问题标题】:Set ggplot title to reflect dplyr grouping设置 ggplot 标题以反映 dplyr 分组
【发布时间】:2018-05-19 14:23:48
【问题描述】:

我在 dplyr 中生成了一个分组数据框,其中每个组都反映了因子变量级别的独特组合。我想使用类似于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

我需要每个地块的标题来反映“地点”和“物种”。有什么想法吗?

【问题讨论】:

    标签: r ggplot2 dplyr


    【解决方案1】:

    像这样使用split() %&gt;% purrr::map2() 而不是group_by() %&gt;% 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) )
    

    【讨论】:

    • 感谢 Nate,这行得通。我仍在尝试围绕 map2 进行思考。对我来说,它不像我熟悉的 dplyr 函数那么直观,但这可能是因为我更像是研究人员而不是程序员。干杯。
    • map2mapply 非常相似,因为它被设计成成对地遍历两个列表对象(因此 list1[1] 与 list2[1] 配对)。在map2 中,我们将检查通过管道传入的拆分列表(随后称为.)以及与第二个列表.y 相同的拆分列表的名称。 Jenny Bryan's purrr turotial 是开始学习 purrr 的好地方。
    【解决方案2】:

    你只需要用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=" - ")))
    

    【讨论】:

      猜你喜欢
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      相关资源
      最近更新 更多