使用 dplyr 为每组应用 ggplot 函数并为每组设置标题 [英] Apply a ggplot-function per group with dplyr and set title per group
本文介绍了使用 dplyr 为每组应用 ggplot 函数并为每组设置标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在数据框中为每个组创建一个单独的图,并将该组包含在标题中.
I would like to create one separate plot per group in a data frame and include the group in the title.
使用 iris 数据集,我可以在基础 R 和 ggplot 中做到这一点
With the iris dataset I can in base R and ggplot do this
plots1 <- lapply(split(iris, iris$Species),
function(x)
ggplot(x, aes(x=Petal.Width, y=Petal.Length)) +
geom_point() +
ggtitle(x$Species[1]))
是否有使用 dplyr 的等价物?
Is there an equivalent using dplyr?
这是使用构面而不是标题的尝试.
Here's an attempt using facets instead of title.
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 中的数据集替换为每次调用的子集.
where I use %+% to replace the dataset in p with the subset for each call.
或(工作但复杂)与 ggtitle
or (working but complex) with 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 设置每个组的标题.
The problem is that I can't seem to set the title per group with ggtitle in a very simple way.
谢谢!
推荐答案
使用.$Species
将物种数据拉入ggtitle
:
iris %>% group_by(Species) %>% do(plots=ggplot(data=.) +
aes(x=Petal.Width, y=Petal.Length) + geom_point() + ggtitle(unique(.$Species)))
这篇关于使用 dplyr 为每组应用 ggplot 函数并为每组设置标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文