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

如何自定义Matplotlib子图占比?调整ax4与ax3宽度比例

自定义Matplotlib子图横向占比布局

当前实现代码

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


def format_axes(fig):
    for i, ax in enumerate(fig.axes):
        ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
        ax.tick_params(labelbottom=False, labelleft=False)

fig = plt.figure(constrained_layout=True)

gs = GridSpec(2, 2, figure=fig)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, 1])
ax4 = fig.add_subplot(gs[1, 0])

fig.suptitle("GridSpec")
format_axes(fig)

plt.show()

当前布局说明

当前是2行2列的均分网格布局,四个子图各占均等空间:第一行横向排列ax1、ax2,第二行横向排列ax4、ax3。

需求描述

保持ax1和ax2的布局不变,让第二行的ax4向ax3方向扩展部分空间,ax3占据剩余空间,且支持自定义两者的空间占比。

修改后的实现方案

通过给GridSpec设置width_ratios参数即可实现自定义列宽度占比,具体代码如下:

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


def format_axes(fig):
    for i, ax in enumerate(fig.axes):
        ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
        ax.tick_params(labelbottom=False, labelleft=False)

fig = plt.figure(constrained_layout=True)

# width_ratios定义两列的相对宽度,示例中ax4(第一列):ax3(第二列)=3:2,可按需修改数值
gs = GridSpec(2, 2, figure=fig, width_ratios=[3, 2])
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, 1])
ax4 = fig.add_subplot(gs[1, 0])

fig.suptitle("自定义占比的GridSpec布局")
format_axes(fig)

plt.show()

关键说明

  • width_ratios的两个数值对应网格两列的相对宽度比例,比如改成[2,1]就是ax4占2份空间,ax3占1份空间,可根据需求自由调整。
  • 第一行的ax1和ax2会自动继承该宽度比例,保持与下方子图的列对齐,满足布局不变的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:24:36