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

如何在R中保留原图比例组合ggplot绘图与图片生成Figure panel?

问题:组合ggplot绘图与外部图片时保留原始比例

想要构建多面板Figure(包含ggplot生成的图表与外部图片),当前使用magick+ggpubr将图片转为ggplot对象后,用patchwork或cowplot组合时,外部图片会被拉伸变形,无法维持原始宽高比。

当前实现代码:

# 导入图片并转为ggplot对象
p1 <- magick::image_read(here(path_data, "image.png")) 
p1 <- ggplot()+ggpubr::background_image(p1)

# 使用patchwork组合面板
p1+p2+p3+p4+p5+p6+plot_annotation(tag_levels = 'a')+plot_layout(ncol=3) 

# 使用cowplot组合面板
cowplot::plot_grid(p1, p2, p3, p4, p5, p6, ncol=3, labels = "auto")

解决方案

核心问题是ggpubr::background_image会强制图片填充整个ggplot面板空间,导致比例失真。以下是两种可靠的解决思路:

方法1:用annotation_custom+rasterGrob保留图片比例

将图片转为grob对象后,通过annotation_custom添加到ggplot中,避免强制填充,再结合图片的原始宽高比调整面板布局。

library(magick)
library(grid)
library(patchwork)

# 读取图片并获取原始宽高比
img <- image_read(here(path_data, "image.png"))
img_ratio <- image_info(img)$width / image_info(img)$height

# 将图片转为grob并添加到空ggplot中(无轴、无背景)
p1 <- ggplot() +
  annotation_custom(
    rasterGrob(img, interpolate = TRUE),
    xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf
  ) +
  theme_void()

# 使用patchwork组合,为p1指定匹配的宽高比
(p1 + plot_layout(widths = img_ratio) + p2 + p3) /
  (p4 + p5 + p6) +
  plot_annotation(tag_levels = 'a')

方法2:用cowplot结合相对尺寸调整

同样先获取图片宽高比,在plot_grid中通过rel_widths或rel_heights参数为图片所在面板设置匹配的相对尺寸。

library(magick)
library(grid)
library(cowplot)

# 读取图片并获取宽高比
img <- image_read(here(path_data, "image.png"))
img_ratio <- image_info(img)$width / image_info(img)$height

# 构建带图片的ggplot对象
p1 <- ggplot() +
  annotation_custom(rasterGrob(img, interpolate = TRUE),
                    xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf) +
  theme_void()

# 组合面板时,为图片所在列设置相对宽度
plot_grid(
  p1, p2, p3,
  p4, p5, p6,
  ncol = 3,
  labels = "auto",
  rel_widths = c(img_ratio, 1, 1) # p1列宽度按比例,其余列保持默认
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:40:20