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

Matplotlib示例代码报错__init__() got an unexpected keyword argument 'layout'求助

解决Matplotlib __init__() got an unexpected keyword argument 'layout' 报错问题

运行Matplotlib官方提供的示例代码(未做任何修改)时,在最新版Jupyter Notebook中出现报错:__init__() got an unexpected keyword argument 'layout',此前该代码可正常运行,解决方案如下:

示例代码

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(layout="constrained")

gs = GridSpec(3, 3, figure=fig)
ax1 = fig.add_subplot(gs[0, :])
# identical to ax1 = plt.subplot(gs.new_subplotspec((0, 0), colspan=3))
ax2 = fig.add_subplot(gs[1, :-1])
ax3 = fig.add_subplot(gs[1:, -1])
ax4 = fig.add_subplot(gs[-1, 0])
ax5 = fig.add_subplot(gs[-1, -2])

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

plt.show()

解决方案

  • 检查Matplotlib版本:layout参数是Matplotlib 3.4.0及以上版本新增的参数,若你的环境中Matplotlib版本低于此,就会触发该报错。在Jupyter Notebook中执行以下命令查看当前版本:
    !pip show matplotlib
    
  • 升级Matplotlib:若版本过低,执行以下命令升级到最新稳定版,即可支持layout参数:
    !pip install --upgrade matplotlib
    
  • 兼容旧版本的替代写法:若无法升级版本,可将代码中的fig = plt.figure(layout="constrained")替换为旧版本支持的约束布局写法:
    # 写法1:使用tight_layout(兼容更早版本)
    fig = plt.figure()
    plt.tight_layout()
    
    # 写法2:使用constrained_layout参数(Matplotlib 3.2.0+支持)
    fig = plt.figure(constrained_layout=True)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 06:22:16