使用ggdraw叠加图像后ggsave导出边距被压缩,如何设置边距
原因说明
ggdraw() 默认会将输入的ggplot对象拉伸铺满整个画布,会覆盖原图原本设置的边距参数,因此导出后会出现边距丢失的问题。
可行解决方案
方法1:提前调整原图边距
在调用ggdraw()前先给底图p设置plot.margin参数,自定义上下左右边距:
# 四个参数顺序为 上、右、下、左,可自行调整数值适配需求 library(ggplot2) p <- p + theme(plot.margin = unit(c(1, 3, 1, 3), "cm")) p1 <- cowplot::ggdraw(p) + cowplot::draw_plot(legend, x = .18, y = .25, width = 0.5, height = .5) ggsave(plot = p1, filename = "outputs/tree_test.png", width = 45, height = 30, units = "cm", dpi = 300)
方法2:手动控制底图绘制范围
不在ggdraw()中直接传入底图,而是通过draw_plot()单独放置底图,自行控制底图的绘制范围预留边距:
p1 <- cowplot::ggdraw() + # x为底图左侧起始位置,width小于1时左右会自动留出空白边距 cowplot::draw_plot(p, x = 0.05, y = 0, width = 0.9, height = 1) + cowplot::draw_plot(legend, x = .18, y = .25, width = 0.5, height = .5) ggsave(plot = p1, filename = "outputs/tree_test.png", width = 45, height = 30, units = "cm", dpi = 300)
方法3:给最终叠加后的图片追加边距
完成图层叠加后,直接给最终的p1对象设置边距:
p1 <- cowplot::ggdraw(p) + cowplot::draw_plot(legend, x = .18, y = .25, width = 0.5, height = .5) # 追加边距设置 p1 <- p1 + theme(plot.margin = unit(c(1, 3, 1, 3), "cm")) ggsave(plot = p1, filename = "outputs/tree_test.png", width = 45, height = 30, units = "cm", dpi = 300)
内容的提问来源于stack exchange,提问作者Anh
相关产品推荐
相关产品推荐

