我在 dplyr 中生成了一个分组数据框,其中每个组反射(reflect)了因子变量水平的独特组合。我想使用类似于 this 的代码绘制不同的组邮政。但是,我不知道如何在图的标题中包含两个(或更多)变量,这很麻烦,因为我有一堆不同的组合。
虚假数据和绘图代码:
library(dplyr)
library(ggplot2)
spiris<-iris
spiris$site<-as.factor(rep(c("A","B","C")))
spiris$year<-as.factor(rep(2012:2016))
spiris$treatment<-as.factor(rep(1:2))
g<-spiris %>%
group_by(site, Species) %>%
do(plots=ggplot(data=.) +
aes(x=Petal.Width)+geom_histogram()+
facet_grid(treatment~year))
##Need code for title here
g[[3]] ##view plots
我需要每个图的标题来反射(reflect)“地点”和“物种”。有什么想法吗?
最佳答案
使用 split() %>% purrr::map2()
而不是 group_by() %>% do()
,如下所示:
spiris %>%
split(list(.$site, .$Species)) %>%
purrr::map2(.y = names(.),
~ ggplot(data=., aes(x=Petal.Width)) +
geom_histogram()+
facet_grid(treatment~year) +
labs(title = .y) )
关于r - 设置 ggplot 标题以反射(reflect) dplyr 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47661847/