我正在尝试创建一个函数,它将生成一个单独的图,将type = " plot“和type = "Strata”的两个线性回归进行比较。对于BCR #和LC类型的每个唯一组合,必须进行线性模型的这种比较。例如(LC = UC和BCR = 30,LC = UC和BCR = 29,LC = UC和BCR = 28...once已经为每个唯一的BCR比较了LC "UC“,然后循环应该移动到下一个LC类型并将其与所有BCR #进行比较)。下面是我的数据框:
> head(Plot_BCR)
# A tibble: 6 x 5
Year BCR LC Area type
<dbl> <int> <chr> <dbl> <chr>
1 2001 30 UC 0 Plot
2 2001 30 OW 0 Plot
3 2001 30 D1 0.0126 Plot
4 2001 30 D2 0 Plot
5 2001 30 D3 0 Plot
6 2001 30 D4 0 Plot
> unique(Plot_BCR$LC)
[1] "UC" "OW" "D1" "D2" "D3" "D4" "BL" "DF" "EF" "MF" "SS" "H" "HP" "CC" "WW" "EW"
> unique(Plot_BCR$BCR)
[1] 30 29 28 14 13 100 27 31我已经创建了以下函数和嵌套循环来创建每个唯一的组合,但是我的输出只为每种LC类型生成了一个图形,而且只为最后一个BCR # (#31)生成了一个图形。
comparison.graph <- function(Plot_BCR, na.rm=TRUE, ...){
BCR <- unique(Plot_BCR$BCR)
LC <- unique(Plot_BCR$LC)
for (i in seq_along(LC)){
for (j in seq_along(BCR))
plot <-
ggplot(subset(Plot_BCR, Plot_long$LC == LC[i] & BCR == BCR[j]), aes(x = Year, y = Area, group=type))+
geom_smooth(method="lm", formula=y~x)+
ggtitle(paste(LC[i], BCR[j], sep="-"))
print(plot)
}
}
comparison.graph(Plot_BCR)对我的函数的任何帮助都会让它为LC和BCR #的每一个组合创建一个图,我将非常感激。
发布于 2021-05-18 09:36:58
您可以使用split + lapply方法生成绘图列表。
library(ggplot2)
comparison.graph <- function(Plot_BCR, na.rm=TRUE, ...){
lapply(split(Plot_BCR, list(Plot_BCR$LC,Plot_BCR$BCR)), function(data) {
ggplot(data, aes(x = Year, y = Area, group=type)) +
geom_smooth(method="lm", formula=y~x)+
ggtitle(paste(data$LC[1], data$BCR[1], sep="-"))
})
}
list_plots <- comparison.graph(Plot_BCR)我们将数据split到数据帧列表中,其中每个数据帧是LC和BCR的唯一值的组合,并绘制每个数据帧的数据。可以通过[[ (即list_plots[[1]]、list_plots[[2]]等)访问各个绘图。
https://stackoverflow.com/questions/67578555
复制相似问题