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

如何在Jupyter Lab中控制R语言绘图的图形纵横比?

R语言在Jupyter Lab中多图布局比例异常问题

问题场景

在Jupyter Lab中运行以下R代码绘制多幅图形:

par(mfrow=c(1,3))

plot(t, loc.t)  # x和y为随机值
plot(t, scale.t)
plot(t, shape.t)

生成的图形显示为一行三幅过于细长的图:
一行三幅细长布局图

已尝试的无效操作

  • 调整行列图形比例的设置在Jupyter Lab中未生效
  • 设置asp=100仅改变y轴范围,图形纵横比无变化:
    asp=100后的图形
  • 使用par(mfrow=c(3,3))能得到类似布局,但存在大量空白:
    3行3列带空白的图形

需求

在Jupyter Lab中直接显示比例合适的一行三幅图(无需保存)


解决方法

1. 直接设置Jupyter图形输出尺寸

在代码开头添加图形尺寸配置,指定整体宽度和高度:

options(repr.plot.width=12, repr.plot.height=4) # 可根据需求调整数值
par(mfrow=c(1,3))

plot(t, loc.t)
plot(t, scale.t)
plot(t, shape.t)

通过repr.plot.width和repr.plot.height控制输出图形的整体大小,让子图比例更协调。

2. 缩小绘图边距

用par()的mar参数减少子图的边距占用,扩大绘图区域:

par(mfrow=c(1,3), mar=c(3,3,2,1)) # mar参数顺序:下、左、上、右,单位为行
plot(t, loc.t)
plot(t, scale.t)
plot(t, shape.t)

可根据实际显示效果微调mar的数值,边距越小,子图可利用空间越大。

3. 改用ggplot2的facet布局

如果允许换用ggplot2绘图,布局控制更灵活稳定:

library(ggplot2)
library(tidyr)

# 将宽格式数据转为长格式
df <- data.frame(t = t, loc = loc.t, scale = scale.t, shape = shape.t)
df_long <- pivot_longer(df, cols = -t, names_to = "variable", values_to = "value")

# 绘制一行三幅图
ggplot(df_long, aes(x = t, y = value)) +
  geom_point() + # 数据是连续型的话也可以用geom_line()
  facet_wrap(~variable, nrow = 1) +
  theme_bw() +
  theme(panel.spacing = unit(0.5, "cm")) # 调整子图之间的间距

ggplot2的facet布局会自动适配子图比例,在Jupyter Lab中显示效果更理想。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 22:13:15