【问题标题】:Apply a ggplot-function per group with dplyr and set title per group使用 dplyr 为每组应用一个 ggplot 函数并为每组设置标题
【发布时间】:2015-05-16 02:10:09
【问题描述】:

我想在数据框中为每个组创建一个单独的图,并将该组包含在标题中。

使用 iris 数据集,我可以在 base R 和 ggplot 中做到这一点

plots1 <- lapply(split(iris, iris$Species), 
  function(x) 
    ggplot(x, aes(x=Petal.Width, y=Petal.Length)) +
      geom_point() +
      ggtitle(x$Species[1]))

是否有使用 dplyr 的等价物?

这里尝试使用构面而不是标题。

p <- ggplot(data=iris, aes(x=Petal.Width, y=Petal.Length)) + geom_point()
plots2 = iris %>% group_by(Species) %>% do(plots = p %+% . + facet_wrap(~Species))

我使用 %+% 将 p 中的数据集替换为每次调用的子集。

或(工作但复杂)与 ggtitle

plots3 = iris %>%
  group_by(Species) %>%
  do(
    plots = ggplot(data=.) +
      geom_point(aes(x=Petal.Width, y=Petal.Length)) +
      ggtitle(. %>% select(Species) %>% mutate(Species=as.character(Species)) %>% head(1) %>% as.character()))

问题是我似乎无法以非常简单的方式使用 ggtitle 设置每个组的标题。

谢谢!

【问题讨论】:

    标签: r split ggplot2 dplyr


    【解决方案1】:

    使用.$Species将物种数据拉入ggtitle

    iris %>% group_by(Species) %>% do(plots=ggplot(data=.) +
             aes(x=Petal.Width, y=Petal.Length) + geom_point() + ggtitle(unique(.$Species)))
    

    【讨论】:

    • 我倾向于通过一个自定义函数来解决这个问题,我使用species[1] 来指定标题。但是,如果您的实际情节如此简单,那肯定有效。 IE——我的工作流程通常是plot.cust &lt;- function(...); iris %&gt;% group_by(Species) %&gt;% plot.cust(...)
    • 非常简单的解决方案,我没有想到!谢谢!
    • @MatthewPlourde 我想是这样,但它看起来比.$Species[1] 更清晰。
    • 你也可以使用类似dplyr的first(.$Species)
    • 实际上只使用 ggtitle(.$Species) 似乎可行,但我不知道为什么,我还没有检查任何建议的速度。再次感谢!
    【解决方案2】:
    library(dplyr, warn.conflicts = FALSE)
    library(ggplot2)
    
    plots3 <- iris %>%
      group_by(Species) %>%
      group_map(~ ggplot(.) + aes(x=Petal.Width, y=Petal.Length) + geom_point() + ggtitle(.y[[1]]))
    
    length(plots3)
    #> [1] 3
    # for example, the second plot :
    plots3[[2]]
    

    reprex package (v2.0.1) 于 2021 年 11 月 19 日创建

    【讨论】:

    • 有兴趣了解 group_map,虽然我发现这不适用于 dplyr 0.8.3,plots3 返回 3 个 1x1 小标题。对于最后一行,我认为应该是 plots3[[2]]$plots.如果有人想在管道中保存这些地块,你认为这是可能的吗?或者更好地循环遍历 plots3[[n]]$plots ?干杯!
    • ggtitle 中的 .y 是什么?我猜它包含有关不同组的信息? y 这个名字是从哪里来的,我该如何访问它?
    • .y 是一个小标题,每个分组变量只有一行和一列,请参阅文档。所以这里我取第一列也是唯一一列的内容,也就是名字。
    • 此解决方案需要更新。
    • 标题发生变化,但所有数据都存在于所有图中。
    【解决方案3】:

    这是另一个使用rowwise的选项:

    plots2 = iris %>% 
        group_by(Species) %>% 
        do(plots = p %+% .) %>% 
        rowwise() %>%
        do(x=.$plots + ggtitle(.$Species))
    

    【讨论】:

      猜你喜欢
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      相关资源
      最近更新 更多