% ggplot(aes(x = x, y = y)) + ge-6ren">
gpt4 book ai didi

R – 为列中的每个字符串组复制/自动化散点图

转载 作者:行者123 更新时间:2023-12-05 03:31:57 25 4
gpt4 key购买 nike

我有一个像这样的数据框(170 个观察值和 3 列):

site_names <- c("WS1", "WS1", "WS2", "WS2", "WS3", "WS3")
x <- c(.15, .20, .17, .16, .20, .22)
y <- c(.026, .031, .045, .087, .09, .033)

df <- data.frame(site_names, x, y)

我有一个简单的 ggplot 公式,我可以为每个 site_name 运行,并相应地绘制 x 和 y:

df %>% 
filter(site_names == "") %>%
ggplot(aes(x = x, y = y)) +
geom_point() +
labs(x = "Discharge", y = "Stage")

我想要的是自动化这些图并通过 site_name 生成 26 个单独的图并将它们全部保存为 PDF

这是我尝试过的:

scatter_expl = function(x, y) {
ggplot(df, aes(x = x, y = y) ) +
geom_point() +
theme_bw() +
labs(x = "Discharge", y = "Stage")
}

plots = map(df, ~scatter_expl())

plots

但这贯穿整个数据框,返回一个列表并在同一图上生成所有散点:/image/gVBhf.png !如何按站点分组并返回单个图表?

最佳答案

我们可能需要group_by

library(dplyr)
library(ggplot2)
library(gridExtra)
out <- df %>%
group_by(site_names) %>%
summarise(plot = list(ggplot(cur_data(), aes(x = x, y = y)) +
geom_point() +
labs(x = "Discharge", y = "Stage")+
ggtitle(sprintf('Plot for %s', cur_group()$site_names))))

-输出

> out
# A tibble: 3 × 2
site_names plot
<chr> <list>
1 WS1 <gg>
2 WS2 <gg>
3 WS3 <gg>

-将输出保存为pdf

ggsave(file.path(getwd(), "plot.pdf"), 
marrangeGrob(out$plot, nrow = 1, ncol = 1), device = "pdf")

数据

df <- structure(list(site_names = c("WS1", "WS1", "WS2", "WS2", "WS3", 
"WS3"), x = c(0.15, 0.2, 0.17, 0.16, 0.2, 0.22), y = c(0.026,
0.031, 0.045, 0.087, 0.09, 0.033)), class = "data.frame", row.names = c(NA,
-6L))

关于R – 为列中的每个字符串组复制/自动化散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70550405/

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