【问题标题】:将 fig.legend 与 matplotlib 中的子图相结合
【发布时间】:2023-03-24 02:20:01
【问题描述】:

免责声明:我知道在这个简单的示例中使用子图无关紧要,后者仅用于说明我的问题:我希望能够将fig.legend()fig.subfigures1 一起使用。


我目前正在发现 matplotlib 的新 subfigure 模块。我注意到当主图包含子图时,使用fig.legend() 创建的图例不会显示:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1, 10, 10)
y1 = x
y2 = -x

fig = plt.figure(constrained_layout=True)
subfigs = fig.subfigures(nrows=2, ncols=1)

for subfig in subfigs:
    axarr = subfig.subplots(1, 2)
    for ax in axarr.flatten():
        l1, = ax.plot(x, y1, label='line1')
        l2, = ax.plot(x, y2, label='line2')
            #
        ax.legend()
    # subfig.legend(handles=[l1, l2], loc='upper center', ncol=2)
fig.legend(handles=[l1, l2], loc='upper center', ncol=2)
plt.savefig('subfigures_figlegend.png', dpi=200)

请注意该人物图例是如何缺失的。为了比较,请注意仅使用 plt.subplots 时会显示:

fig, axarr = plt.subplots(2, 2, constrained_layout=True)
for ax in axarr.flatten():
    l1, = ax.plot(x, y1, label='line1')
    l2, = ax.plot(x, y2, label='line2')
    #
    ax.legend()
fig.legend(handles=[l1, l2], loc='upper center', ncol=2)
plt.savefig('subplots_figlegend.png', dpi=200)

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

    当我运行你的代码时,图例就在那里,但它在情节的后面并略高于情节,然后在调用plt.savefig() 时被切断。我能够让它与plt.savefig()bbox_inches='tight' 参数一起工作,并使用以下内容来移动图例。

    fig.legend(handles=[l1, l2], bbox_to_anchor=(0.7, 1.1), ncol=2)
    

    【讨论】:

    • 很好,我会就此发出错误报告,我很确定这不是预期的行为。不过,请注意MatplotlibDeprecationWarning: savefig() got unexpected keyword argument "box _inches" which is no longer supported as of 3.3 and will become an error two minor releases later
    • 我还没有想出解决这个 zorder 问题的方法,之后用 l.set_zorder(1000) 更改图例 zorder 不会改变任何东西
    • @Liris box_inches 是一个错字。应该是 bbox_inches
    • 我在fig.legend(handles=[l1, l2], bbox_to_anchor=(0.7, 1.1), ncol=2) 中看不到任何bbox_inches='tight' 参数。不要评论错别字:编辑您的帖子。
    • 它不在 fig.legend 中,它被传递给 savefig 的调用。为了清楚起见,我编辑了帖子。
    猜你喜欢
    • 2019-12-20
    • 2017-11-21
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    相关资源
    最近更新 更多