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

使用ggarrange排布4个非ggplot绘图时出现重叠问题求助

问题原因与解决方案

你遇到的问题核心是 ggarrange(来自ggpubr包)是为ggplot2对象设计的,而recordPlot()保存的是base R绘图的记录,直接调用print()会在当前绘图设备上直接绘制,而非生成ggarrange能识别的对象。四个print()调用会在同一位置叠加,最终只显示最后一个绘图。

以下是几种可行的解决方法:

方法1:将base绘图转换为ggplot兼容对象(推荐)

使用gridGraphics和ggplotify包,把base R绘图转换为ggplot/grid对象,这样就能正常用ggarrange排列:

# 安装所需包(首次使用)
install.packages(c("ggpubr", "gridGraphics", "ggplotify"))

# 生成并转换绘图
plot(1:10)
p1 <- as.ggplot(function() replayPlot(recordPlot()))
dev.off()

plot(1:10)
p2 <- as.ggplot(function() replayPlot(recordPlot()))
dev.off()

plot(1:10)
p3 <- as.ggplot(function() replayPlot(recordPlot()))
dev.off()

plot(1:10)
p4 <- as.ggplot(function() replayPlot(recordPlot()))
dev.off()

# 用ggarrange排列
pdf("test.pdf", width = 20, height = 10)
ggarrange(plotlist = list(p1, p2, p3, p4), ncol = 2, nrow = 2, align = "hv")
dev.off()

方法2:直接用base R原生排版

既然都是base R绘图,直接用par(mfrow)或layout来布局,更简单高效:

pdf("test.pdf", width = 20, height = 10)
par(mfrow = c(2, 2)) # 设置2行2列布局
replayPlot(p1)
replayPlot(p2)
replayPlot(p3)
replayPlot(p4)
dev.off()

如果需要调整边距,这里用par(mar)才会生效,比如:

par(mfrow = c(2, 2), mar = c(3, 3, 2, 1)) # 调整上下左右边距(默认是c(5,4,4,2)+0.1)

方法3:用cowplot包的plot_grid(类似ggarrange)

同样需要先转换为ggplot对象,再用plot_grid排列:

install.packages("cowplot")
library(cowplot)

# 转换步骤同方法1,得到p1-p4后:
pdf("test.pdf", width = 20, height = 10)
plot_grid(p1, p2, p3, p4, ncol = 2, nrow = 2, align = "hv")
dev.off()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 23:42:41