繁体   English   中英

For循环创建多个ggplots

[英]For loop to create multiple ggplots

我有一个数据集,其中包含变量周、社会经济地位(从 1 到 5)以及每周和每个社会经济地位的独特家庭数量。

现在,我想为每个社会经济地位创建 5 个 ggplots,一个 plot。 每个 plot 应显示几周内针对一种社会经济地位的独特家庭数量的发展。

我考虑过使用 for 循环,但到目前为止我找不到有效的解决方案。 如果有人可以帮助我,那就太好了。

假设您的数据是df并且您有列weeksesnhh 如果您只想通过 ses 可视化 plot,可以使用facet_wrap() ,如下所示:

ggplot(df, aes(week, nhh)) + 
  geom_point() + 
  facet_wrap(~ses)

如果你想要一个 dataframe 的地块,你可以这样做:

plots <- df %>% 
  group_by(ses) %>%
  summarize(plot = list(ggplot(NULL, aes(week, nhh)) + geom_point()))

Output:

# A tibble: 5 x 2
    ses plot  
  <int> <list>
1     1 <gg>  
2     2 <gg>  
3     3 <gg>  
4     4 <gg>  
5     5 <gg>  

如果您想要 plot 对象的列表,您可以这样做

plots <- lapply(unique(df$ses), \(s) ggplot(df %>% filter(ses == s), aes(week,nhh)) + geom_point())
names(plots = unique(df$ses))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM