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

如何在R Markdown中调整2×2布局图形的高度

2×2布局下延长图形高度的解决办法

以下几种方式可以让你的2×2布局里每个图形的高度更长:

1. 调整图形输出设备的宽高比

直接在生成图形文件时指定更大的高度、更小的宽度,提升整体画布的高度占比,每个子图的高度自然更长。示例代码:

# 生成png格式图形,设置宽6英寸、高8英寸,分辨率300dpi
png("output_plots.png", width=6, height=8, units="in", res=300)
attach(mtcars)
par(mfrow=c(2,2))
plot(wt,mpg, main="Scatterplot of wt vs. mpg")
plot(wt,disp, main="Scatterplot of wt vs disp")
hist(wt, main="Histogram of wt")
boxplot(wt, main="Boxplot of wt")
dev.off() # 关闭图形设备

如果是在RStudio绘图窗口操作,直接拖动窗口边缘拉长高度也能达到同样效果。

2. 缩小图形边距,释放绘图空间

默认的图形边距(上下左右空白区域)占用了不少空间,通过par()的mar参数缩小边距,能让绘图区域的高度更充足。示例代码:

attach(mtcars)
# mar参数顺序为:下、左、上、右的边距(单位是文本行数),按需调整数值
par(mfrow=c(2,2), mar=c(4,4,2,1))
plot(wt,mpg, main="Scatterplot of wt vs. mpg")
plot(wt,disp, main="Scatterplot of wt vs disp")
hist(wt, main="Histogram of wt")
boxplot(wt, main="Boxplot of wt")

这里调小了上边和右边的边距,把更多空间留给绘图区域,视觉上图形高度会更长。

3. 用layout函数自定义布局高度比例

layout()比mfrow更灵活,能直接指定每行的高度占比,让两行的高度相对于宽度更大。示例代码:

attach(mtcars)
# 定义2行2列的布局,heights设置每行高度比例(数值越大占比越高)
layout(matrix(c(1,2,3,4), nrow=2, byrow=TRUE), heights=c(1.5,1.5))
plot(wt,mpg, main="Scatterplot of wt vs. mpg")
plot(wt,disp, main="Scatterplot of wt vs disp")
hist(wt, main="Histogram of wt")
boxplot(wt, main="Boxplot of wt")

可以根据需求调整heights的数值,比如改成c(2,2),高度占比会进一步提升。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:35:16