[英]For loop to create multiple ggplots
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.我有一个数据集,其中包含变量周、社会经济地位(从 1 到 5)以及每周和每个社会经济地位的独特家庭数量。
Now, I want to create 5 ggplots, one plot for each socioeconomic status.现在,我想为每个社会经济地位创建 5 个 ggplots,一个 plot。 Each plot should show the development of the number of unique households for one socioeconomic status over several weeks.每个 plot 应显示几周内针对一种社会经济地位的独特家庭数量的发展。
I thought about using a for loop but so far I couldn't find a solution that works.我考虑过使用 for 循环,但到目前为止我找不到有效的解决方案。 Would be great if someone could help me.如果有人可以帮助我,那就太好了。
Let's say your data is df
and you have columns week
, ses
, and nhh
.假设您的数据是df
并且您有列week
、 ses
和nhh
。 If you just want to visualize the plot by ses, you can use facet_wrap()
, like this:如果您只想通过 ses 可视化 plot,可以使用facet_wrap()
,如下所示:
ggplot(df, aes(week, nhh)) +
geom_point() +
facet_wrap(~ses)
If you would like a dataframe of plots, you can do this:如果你想要一个 dataframe 的地块,你可以这样做:
plots <- df %>%
group_by(ses) %>%
summarize(plot = list(ggplot(NULL, aes(week, nhh)) + geom_point()))
Output: 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如果您想要 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.