byt*_*ght 24 split r ggplot2 dplyr
我想在数据框中为每个组创建一个单独的绘图,并在标题中包含该组.
使用虹膜数据集,我可以在基础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]))
Run Code Online (Sandbox Code Playgroud)
是否有使用dplyr的等价物?
这是尝试使用facet而不是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))
Run Code Online (Sandbox Code Playgroud)
其中我使用%+%将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()))
Run Code Online (Sandbox Code Playgroud)

问题是我似乎无法以非常简单的方式使用ggtitle为每个组设置标题.
谢谢!
Jam*_*mes 42
使用.$Species该种数据拉入ggtitle:
iris %>% group_by(Species) %>% do(plots=ggplot(data=.) +
aes(x=Petal.Width, y=Petal.Length) + geom_point() + ggtitle(unique(.$Species)))
Run Code Online (Sandbox Code Playgroud)
从dplyr 0.8.0我们可以使用group_map:
library(dplyr, warn.conflicts = FALSE, quietly = TRUE)
#> Warning: le package 'dplyr' a été compilé avec la version R 3.5.2
library(ggplot2)
plots3 <- iris %>%
group_by(Species) %>%
group_map(~tibble(plots=list(
ggplot(.) + aes(x=Petal.Width, y=Petal.Length) + geom_point() + ggtitle(.y[[1]]))))
plots3
#> # A tibble: 3 x 2
#> # Groups: Species [3]
#> Species plots
#> <fct> <list>
#> 1 setosa <S3: gg>
#> 2 versicolor <S3: gg>
#> 3 virginica <S3: gg>
plots3$plots[[2]]
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.2.0)于 2019 年 2 月 18 日创建。
| 归档时间: |
|
| 查看次数: |
10809 次 |
| 最近记录: |