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

MatplotlibDeprecationWarning(Gridspec使用)求助:如何正确创建Axes?

Fixing MatplotlibDeprecationWarning in Your Gridspec Function

First, let's unpack the warning you're hitting—it's telling you that you're trying to add axes to the exact same gridspec positions multiple times, and Matplotlib's behavior for this scenario is changing soon:

MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.

Looking at your code, the root issue is the redundant for dataset in range(2) loop. You only have 2 rows in your graphs_gs grid, but this loop makes you attempt to add each of those two subplots twice—hence the warning about duplicate axes arguments.

Solution 1: Remove the Redundant Loop (Best Practice)

The dataset loop doesn't serve a purpose here (your grid only has space for 2 metric plots total). Ditching it will eliminate the warning entirely and make your code more intentional:

import matplotlib.pyplot as plt

def get_gridspec(): 
    fig10 = plt.figure(constrained_layout=True)
    gs0 = fig10.add_gridspec(1, 2)
    
    # Set up subgrids
    loss_gs = gs0[0].subgridspec(1, 1)
    graphs_gs = gs0[1].subgridspec(2, 1)
    
    # Add loss plot axis
    loss_ax = fig10.add_subplot(loss_gs[0])
    
    # Add metric plot axes (no redundant dataset loop)
    metric_axes = []
    for irow_metric in range(2):
        ax = fig10.add_subplot(graphs_gs[irow_metric, 0])
        metric_axes.append(ax)
    
    # Return explicit list of axes (more reliable than fig.axes)
    return [loss_ax] + metric_axes

This way, you only create each axis once, and you get direct references to each Axes object instead of relying on fig10.axes (which can be unpredictable if the figure ever has extra axes added later).

Solution 2: Add Unique Labels (If You Need Repeated Calls)

If for some specific reason you do need to call add_subplot() on the same position multiple times (this is rare, but possible), you can pass a unique label parameter to each call to suppress the warning and align with future Matplotlib behavior:

def get_gridspec(): 
    fig10 = plt.figure(constrained_layout=True)
    gs0 = fig10.add_gridspec(1, 2)
    loss_gs = gs0[0].subgridspec(1, 1)
    graphs_gs = gs0[1].subgridspec(2, 1)
    
    fig10.add_subplot(loss_gs[0], label="loss_plot")
    
    for dataset in range(2):
        for irow_metric in range(2):
            for jrow_metric in range(1):
                # Create a unique label for each axes instance
                unique_label = f"dataset_{dataset}_metric_{irow_metric}"
                fig10.add_subplot(graphs_gs[irow_metric, jrow_metric], label=unique_label)
    
    return fig10.axes

Again, this is only useful if you have a specific need to re-add axes to the same spot. In your original code, the dataset loop looks like an accidental redundancy, so Solution 1 is the correct fix.

Bonus: Cleaner Gridspec Usage

For even more concise code, you can create axes directly from the gridspec using subplots() instead of manual add_subplot() calls:

def get_gridspec(): 
    fig10 = plt.figure(constrained_layout=True)
    gs0 = fig10.add_gridspec(1, 2)
    
    # Create loss axis in one line
    loss_ax = gs0[0].subplots()
    
    # Create 2x1 metric axes grid
    metric_axes = gs0[1].subplots(nrows=2, ncols=1)
    
    # Return flat list of axes
    return [loss_ax] + metric_axes.flatten().tolist()

This method cuts down on loop boilerplate and makes your grid structure immediately clear.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 18:17:42