对每个组应用一个ggplot函数,并使用dplyr设置每个组的标题 [英] Apply a ggplot-function per group with dplyr and set title per group
本文介绍了对每个组应用一个ggplot函数,并使用dplyr设置每个组的标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在数据框中为每个组创建一个单独的图,并将该组包含在标题中。
I would like to create one separate plot per group in a data frame and include the group in the title.
使用虹膜数据集,我可以在基本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.
谢谢!
推荐答案
使用 $物种
拉物种数据进入 ggtitle
:
iris %>% group_by(Species) %>% do(plots=ggplot(data=.) +
aes(x=Petal.Width, y=Petal.Length) + geom_point() + ggtitle(unique(.$Species)))
这篇关于对每个组应用一个ggplot函数,并使用dplyr设置每个组的标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文