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

如何在Matplotlib子图中仅调整第二个子图的尺寸?

如何单独调整Matplotlib中第二个子图的尺寸(保持宽度一致、并列排布)

Matplotlib默认的子图布局会均分画布空间,要实现左右并列、宽度一致,仅第二个子图高度(长度)更大的效果,推荐以下两种方法:

方法1:使用GridSpec(灵活可控,推荐)

GridSpec是Matplotlib中用于精准控制子图布局的工具,可直接设置子图的尺寸比例。

适配面向对象写法(fig, ax)

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

x1 = np.array([0, 1, 2, 3])
y1 = np.array([3, 8, 1, 10])
x2 = np.array([0, 1, 2, 3])
y2 = np.array([10, 20, 30, 40])

# 创建画布,设置整体尺寸
fig = plt.figure(figsize=(7, 5))
# 定义1行2列的布局,设置子图高度比例(此处第二个子图高度为第一个的2倍,可自行调整)
gs = GridSpec(1, 2, height_ratios=[1, 2])

# 基于GridSpec创建子图
ax1 = fig.add_subplot(gs[0])
ax1.plot(x1, y1)

ax2 = fig.add_subplot(gs[1])
ax2.plot(x2, y2)

plt.tight_layout()  # 自动调整布局,避免元素重叠
plt.show()

适配plt.subplot传统写法

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

x1 = np.array([0, 1, 2, 3])
y1 = np.array([3, 8, 1, 10])
x2 = np.array([0, 1, 2, 3])
y2 = np.array([10, 20, 30, 40])

plt.figure(figsize=(7,5))
# 定义布局比例
gs = GridSpec(1, 2, height_ratios=[1, 2])

# 通过GridSpec索引创建子图
plt.subplot(gs[0])
plt.plot(x1, y1)

plt.subplot(gs[1])
plt.plot(x2, y2)

plt.tight_layout()
plt.show()

方法2:直接修改子图位置参数(快速临时调整)

如果不需要复杂布局,可直接获取子图的位置对象,手动修改高度属性:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.array([0, 1, 2, 3])
y1 = np.array([3, 8, 1, 10])
x2 = np.array([0, 1, 2, 3])
y2 = np.array([10, 20, 30, 40])

# 初始化默认布局
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(7,5))
ax1.plot(x1, y1)
ax2.plot(x2, y2)

# 获取第二个子图的当前位置信息
pos = ax2.get_position()
# 修改高度:将高度扩大为原来的1.5倍,同时调整底部位置保证子图垂直居中
ax2.set_position([pos.x0, pos.y0 - (pos.height * 0.25), pos.width, pos.height * 1.5])

plt.show()

补充说明

如果你的“长度”指的是水平宽度(而非垂直高度),只需将GridSpec中的height_ratios替换为width_ratios即可,例如gs = GridSpec(1, 2, width_ratios=[1, 2]),这样第二个子图宽度会更大,同时保持高度一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:45:43