使用Gridspec的MatplotlibDeprecationWarning

时间:2020-08-09 14:29:05

标签: python matplotlib

我有一个函数可以返回使用子图和gridspecs创建的图形上的轴。它引发了MatplotlibDeprecationWarning,我想了解我应该怎么做。有人可以帮忙吗?

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])

    for dataset in range(2):
        for irow_metric in range(2):
            for jrow_metric in range(1):
                fig10.add_subplot(graphs_gs[irow_metric, jrow_metric])
    return fig10.axes

提高:

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.

fig10.add_subplot(graphs_gs [irow_metric,jrow_metric])

enter image description here

1 个答案:

答案 0 :(得分:1)

是的,这有点尴尬。我们正在研究一个“子图”或“子面板”的隐喻,这种隐喻不会那么令人讨厌(https://github.com/matplotlib/matplotlib/issues/17375

OTOH,自最近的matplotlib起,在subplots个对象(https://matplotlib.org/api/_as_gen/matplotlib.gridspec.GridSpecBase.html#matplotlib.gridspec.GridSpecBase.subplots)上有一个gridspec方法,它将在与gridspec关联的图形上创建子图:

import matplotlib.pyplot as plt

fig10 = plt.figure(constrained_layout=True)
gs0 = fig10.add_gridspec(1, 2)
loss_axs = gs0[0].subgridspec(1, 1).subplots()
graphs_axs = gs0[1].subgridspec(2, 1).subplots()

不推荐使用警告是因为您的外循环-您“创建”了两次轴,因此不推荐使用。