使用 dplyr 为每个组应用 ggplot-function 并为每个组设置标题

Apply a ggplot-function per group with dplyr and set title per group

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

使用 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 为每个组设置标题。

谢谢!

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

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

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

plots2 = iris %>% 
    group_by(Species) %>% 
    do(plots = p %+% .) %>% 
    rowwise() %>%
    do(x=.$plots + ggtitle(.$Species))
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 创建