使用 ggplot 和 for 循环在同一页上绘制多个图
Plotting multiple plots on the same page using ggplot and for loop
我调用了几个数据帧并将其放在列表中,如下所示:
plots_list <- list(data_1, data_2, data_3, data_4, data_5)
我定义了一个函数,它从每个数据帧中获取数据并绘制残差:
residual_plots <- function(data) {
ggplot(data, aes(x = x, y = y)) +
geom_point(
aes(color = col1,
shape = col2),
na.rm = T,
size = 1.2
) +
geom_hline(
yintercept = 0,
colour = "dimgray",
linetype = "solid",
size = 0.25
) +
geom_abline(
intercept = 0,
slope = 0.1,
colour = "dimgray",
linetype = "dashed",
size = 0.25
) +
geom_abline(
intercept = 0,
slope = -0.1,
colour = "dimgray",
linetype = "dashed",
size = 0.25
)
}
因为我有多个数据框,所以我想使用 for 循环来快速完成工作。这是我使用的代码:
res_plot_list <- vector("list", length = length(plots_list))
for (i in (plots_list)) {
res_plot_list[[i]] <- residual_plots(i)
}
ml <- marrangeGrob(res_plot_list, nrow = 2, ncol = 3)
ml
我尝试了多种变体,试图将所有图表放在同一页上,但我总是遇到某种形式的死胡同。截至目前,当我使用此代码时,我将 运行 保留为以下错误:
Error in `[[<-`(`*tmp*`, i, value = residual_plots(i)) :
invalid subscript type 'list'
对于如何最好地解决此问题的任何帮助,我将不胜感激,因为我找不到合适的问题。谢谢!
for
循环中的 i
是数据集,因此 res_plot_list[[i]]
失败。尝试-
for (i in seq_along(plots_list)) {
res_plot_list[[i]] <- residual_plots(plots_list[[i]])
}
或者为什么不直接使用 lapply
-
res_plot_list <- lapply(plots_list, residual_plots)
我调用了几个数据帧并将其放在列表中,如下所示:
plots_list <- list(data_1, data_2, data_3, data_4, data_5)
我定义了一个函数,它从每个数据帧中获取数据并绘制残差:
residual_plots <- function(data) {
ggplot(data, aes(x = x, y = y)) +
geom_point(
aes(color = col1,
shape = col2),
na.rm = T,
size = 1.2
) +
geom_hline(
yintercept = 0,
colour = "dimgray",
linetype = "solid",
size = 0.25
) +
geom_abline(
intercept = 0,
slope = 0.1,
colour = "dimgray",
linetype = "dashed",
size = 0.25
) +
geom_abline(
intercept = 0,
slope = -0.1,
colour = "dimgray",
linetype = "dashed",
size = 0.25
)
}
因为我有多个数据框,所以我想使用 for 循环来快速完成工作。这是我使用的代码:
res_plot_list <- vector("list", length = length(plots_list))
for (i in (plots_list)) {
res_plot_list[[i]] <- residual_plots(i)
}
ml <- marrangeGrob(res_plot_list, nrow = 2, ncol = 3)
ml
我尝试了多种变体,试图将所有图表放在同一页上,但我总是遇到某种形式的死胡同。截至目前,当我使用此代码时,我将 运行 保留为以下错误:
Error in `[[<-`(`*tmp*`, i, value = residual_plots(i)) :
invalid subscript type 'list'
对于如何最好地解决此问题的任何帮助,我将不胜感激,因为我找不到合适的问题。谢谢!
for
循环中的 i
是数据集,因此 res_plot_list[[i]]
失败。尝试-
for (i in seq_along(plots_list)) {
res_plot_list[[i]] <- residual_plots(plots_list[[i]])
}
或者为什么不直接使用 lapply
-
res_plot_list <- lapply(plots_list, residual_plots)