gpt4 book ai didi

r - 设置 ggplot 标题以反射(reflect) dplyr 分组

转载 作者:行者123 更新时间:2023-12-02 20:34:08 24 4
gpt4 key购买 nike

我在 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) )

enter image description here

关于r - 设置 ggplot 标题以反射(reflect) dplyr 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47661847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com