geom_sf绘图存PDF时页面留白过多问题求助
解决PDF保存sf地图时空白过多的问题
核心原因
pdf()函数默认使用A4竖版页面(宽8.3英寸、高11.7英寸),而世界地图这类宽幅图形和默认尺寸适配性差,再加上ggplot默认的绘图边距,就会出现大量空白。ggsave()会自动根据图形比例调整参数,所以空白量可控。
具体解决方法
方法1:调整PDF页面尺寸+压缩绘图边距
直接在pdf()里设置匹配地图比例的宽高,同时去掉ggplot的多余边距:
library(tidyverse) library(terra) library(rnaturalearth) # 获取世界矢量数据 world <- ne_countries(returnclass = "sf") # 打开PDF设备,设置宽高为宽屏比例 pdf("world_map_fit.pdf", width = 14, height = 7) # 绘制地图,压缩边距,去掉不必要的坐标轴元素 ggplot(world) + geom_sf() + theme( plot.margin = margin(0, 0, 0, 0, unit = "cm"), # 完全去掉绘图边距 axis.text = element_blank(), # 隐藏坐标轴文字 axis.ticks = element_blank(), # 隐藏刻度 axis.title = element_blank() # 隐藏坐标轴标题 ) # 关闭PDF设备 dev.off()
方法2:多图组合时用patchwork控制布局
如果需要和其他绘图一起保存,用patchwork包统一控制整体边距和布局:
library(patchwork) # 准备地图和其他绘图 map_plot <- ggplot(world) + geom_sf() + theme(plot.margin = margin(0, 0, 0, 0, "cm")) other_plot <- ggplot(mtcars) + geom_point(aes(x = mpg, y = hp)) # 组合图形,设置整体边距 combined <- map_plot / other_plot & theme(plot.margin = margin(0.5, 0.5, 0.5, 0.5, "cm")) # 保存到PDF,设置合适的宽高 pdf("combined_plots.pdf", width = 12, height = 10) print(combined) dev.off()
方法3:直接用ggsave批量保存到同一PDF
如果只是要把多个图存到同一个PDF,也可以用ggsave()的onefile=TRUE参数,利用它的自动适配逻辑:
# 打开PDF文件,onefile=TRUE表示所有图存到同一文件 ggsave("multi_plots.pdf", onefile = TRUE) # 依次绘制所有图 print(map_plot) print(other_plot) # 关闭设备 dev.off()
内容的提问来源于stack exchange,提问作者Gmichael
相关产品推荐
相关产品推荐

