You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何减少RMarkdown中plot_grid生成图表的上下多余空白区域?

解决方案

上下多余空白主要来自代码块参数、单图边距、组合图边距三个层面,按以下步骤调整即可:

1. 调整knitr代码块参数

在原有代码块头部补充fig.align='center'、fig.margin=F,同时根据图片比例设置合适的fig.height,避免Rmarkdown自动分配过高的绘图区域:

{r, echo=F, cache=T, fig.cap=fig_cap("ch7__peaches.example__fig.cap"), out.width="100%", fig.height=2.5, fig.align='center', fig.margin=F}

fig.height的数值可以根据你图片的实际横纵比调整,三张都是横图的话设2-3之间即可。

2. 消除单张图片的上下边距

draw_image默认会在图片周围预留少量边距,可以通过指定scale参数让图片占满整个绘图区域,同时给每个ggdraw对象加上空白边距配置:

peach1 <- ggdraw() + 
  draw_image("./resources/images/peach1-photo-grey.png", scale = 1) +
  theme(plot.margin = margin(0,0,0,0))
peach2 <- ggdraw() + 
  draw_image("./resources/images/peach2-photo-grey.png", scale = 1) +
  theme(plot.margin = margin(0,0,0,0))
peach3 <- ggdraw() + 
  draw_image("./resources/images/peach3-photo-grey.png", scale = 1) +
  theme(plot.margin = margin(0,0,0,0))

3. 调整plot_grid的边距与填充

在plot_grid中添加vpadding = unit(0, "pt")消除垂直方向的默认填充,同时在最终的theme设置里把组合图的边距设为0:

plot_grid(NULL, peach1, NULL, peach2, NULL, peach3, NULL, 
          ncol = 7, 
          rel_widths = c(0.3, 1, 0.3, 1, 0.3, 1, 0.3),
          vpadding = unit(0, "pt")) + 
    theme(panel.border = element_rect(colour = "black", fill = NA, size = 1), 
          legend.title = element_blank(),
          plot.margin = margin(1,1,1,1, unit = "pt"))

这里留1pt边距是避免外层边框被裁切,不需要可以直接设为0。

如果调整完还有少量空白,可检查原始png图片是否本身自带透明/白色的上下边距,若有可以在draw_image中加clip = "on"参数,或者提前批量裁剪图片。

内容的提问来源于stack exchange,提问作者adajam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 09:15:03