我想在数据框中为每个组创建一个单独的图,并将该组包含在标题中。
使用 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)))
关于r - 使用 dplyr 为每组应用 ggplot 函数并为每组设置标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29034863/