循环创建多个ggplots

发布于 2025-02-12 09:44:55 字数 184 浏览 1 评论 0原文

我有一个数据集,该数据集具有变量周,社会经济状况(从1-5起)以及每周和每个社会经济地位的独特家庭数量。

现在,我想创建5个GGPLOTS,这是每个社会经济地位的一个图。每个情节都应显示几周来一个社会经济地位的独特家庭数量的发展。

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

I have a data set that has the variables week, socioeconomic status (from 1-5) and number of unique households for each week and each socioeconomic status.

Now, I want to create 5 ggplots, one plot for each socioeconomic status. Each plot should show the development of the number of unique households for one socioeconomic status over several weeks.

I thought about using a for loop but so far I couldn't find a solution that works. Would be great if someone could help me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

诗笺 2025-02-19 09:44:55

假设您的数据是df,并且您有列Weeksesnhh。如果您只想通过SES可视化绘图,则可以使用facet_wrap(),如:

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

如果您想要绘图的数据框架,则可以执行此操作:

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

输出:

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

如果您想要一个列表情节对象,您可以做到这一点

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

Let's say your data is df and you have columns week, ses, and nhh. If you just want to visualize the plot by ses, you can use facet_wrap(), like this:

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

If you would like a dataframe of plots, you can do this:

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>  

If you would like a list of plot objects, you can do this

plots <- lapply(unique(df$ses), \(s) ggplot(df %>% filter(ses == s), aes(week,nhh)) + geom_point())
names(plots = unique(df$ses))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文