使用facet_wrap生成多图后如何实现每页1张并导出为PDF
R语言ggplot分面图逐页输出PDF解决方案
方案1:分组循环生成单图(灵活度最高)
无需保留原有facet_wrap逻辑时优先选择,可自定义每张图的样式:
library(ggplot2) library(dplyr) # 初始化PDF输出设备 pdf("国别人口趋势_单页单图.pdf", onefile = TRUE) # 遍历所有国家逐张绘图 for (current_country in unique(df$country)) { # 过滤当前国家的数据集 single_country_data <- filter(df, country == current_country) # 绘制单国趋势图 single_plot <- ggplot(single_country_data, aes(x = age)) + geom_line(aes(y = pop), colour = "red") + geom_line(aes(y = cn), colour = "blue") + scale_y_continuous(labels = scales::comma) + labs( title = paste("国家:", current_country), x = "年龄", y = "人口数量" ) # 将当前图输出到PDF新一页 print(single_plot) } # 关闭PDF设备,完成文件写入 dev.off()
方案2:保留facet_wrap原有样式
如果需要保留分面自带的标签栏,可基于原有代码调整为循环输出:
library(ggplot2) library(dplyr) pdf("国别人口趋势_facet样式单页单图.pdf", onefile = TRUE) for (current_country in unique(df$country)) { plot <- ggplot(data = filter(df, country == current_country), aes(x=age,group = country))+ geom_line(aes(y=pop),colour="red")+ geom_line(aes(y=cn),colour="blue")+ facet_wrap(~country) + scale_y_continuous(labels = scales::comma)+ xlab("age") + ylab("population") print(plot) } dev.off()
注意事项
- 运行前需确保已经加载
ggplot2、dplyr依赖包 - PDF文件默认生成在当前工作目录下,可通过
getwd()查看当前工作目录路径
内容的提问来源于stack exchange,提问作者mehmo
相关产品推荐
相关产品推荐

