You need to enable JavaScript to run this app. matplotlib多子图场景下如何正确设置figsize自定义画布尺寸
优惠活动
大模型
产品
解决方案
定价
更多

matplotlib多子图场景下如何正确设置figsize自定义画布尺寸

画布尺寸不生效的核心原因

你之前尝试添加plt.figure(figsize=(10,10))设置尺寸完全没用,本质是这个独立生成的画布根本没有参与最终绘图流程:
调用plt.subplots()的时候,matplotlib会自动初始化一个全新的Figure实例,接管当前pyplot的活动画布指针,把你之前单独创建的空图挤到后台。你看到的<Figure size 720x720 with 0 Axes>打印输出,就是那个被闲置的空画布——上面连坐标轴都没有,当然不可能影响最终的成图尺寸。

正确的尺寸配置实现

完全不需要单独调用plt.figure(),plt.subplots()本身就原生支持figsize入参,直接把尺寸参数传进去即可。你还可以把尺寸设置做成原函数的可选入参,不用每次修改函数内部逻辑:

def plot_figures(figures, nrows=1, ncols=1, figsize=(10, 10)):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary
    ncols : number of columns of subplots wanted in the display
    nrows : number of rows of subplots wanted in the figure
    figsize: 自定义画布尺寸,单位为英寸,格式为(宽度, 高度)
    """
    # 直接在subplots接口中传入figsize参数,生效范围完全匹配最终绘图的画布
    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows, figsize=figsize)
    for ind, title in enumerate(figures):
        axeslist.ravel()[ind].imshow(figures[title], cmap=plt.gray())
        axeslist.ravel()[ind].set_title(title)
        axeslist.ravel()[ind].set_axis_off()
    plt.tight_layout()

import matplotlib.pyplot as plt
import numpy as np

# 生成测试图像字典
number_of_im = 6
figures = {'im' + str(i): np.random.randn(100, 100) for i in range(number_of_im)}

# 调用时直接传入自定义尺寸即可生成对应大小的2行3列子图布局
plot_figures(figures, 2, 3, figsize=(12, 8))
关键注意点
  • 不要在调用plt.subplots()之前单独写plt.figure(figsize=...),这段代码生成的画布会被后续subplots的新建画布操作完全覆盖,属于无效操作
  • figsize的单位是英寸,搭配matplotlib默认的72dpi换算逻辑,传入的数值会直接对应最终画布的物理尺寸

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.22 07:06:07