编写函数自动化ggplot2中的重复绘图任务
自动化生成ACF绘图的函数实现
可以通过两种方式实现批量绘图,生成的绘图对象会被存放在一个列表里,方便后续用ggarrange拼接:
方法一:用purrr包的map函数(简洁高效)
先确保安装并加载ggplot2和purrr包:
install.packages(c("ggplot2", "purrr")) library(ggplot2) library(purrr)
直接用map遍历列表中的每个dataframe,批量生成绘图:
# 生成的绘图对象会存入plot_list列表 plot_list <- map(list1, function(df) { ggplot(data = df, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_segment(mapping = aes(xend = lag, yend = 0)) })
plot_list[[1]]对应原代码中的b,plot_list[[2]]对应c,以此类推。
方法二:自定义函数+循环(直观易懂)
先定义一个生成单张ACF图的函数:
library(ggplot2) create_acf_plot <- function(df) { ggplot(data = df, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_segment(mapping = aes(xend = lag, yend = 0)) }
再用循环遍历列表,生成并存储所有绘图:
plot_list <- list() for (i in seq_along(list1)) { plot_list[[i]] <- create_acf_plot(list1[[i]]) }
后续用ggarrange拼接绘图
拿到plot_list后,直接传入ggarrange即可(需加载ggpubr包):
install.packages("ggpubr") library(ggpubr) # 示例:按2行2列排列拼接所有图 ggarrange(plotlist = plot_list, nrow = 2, ncol = 2)
内容的提问来源于stack exchange,提问作者lola
相关产品推荐
相关产品推荐

