如何在没有要更改的地块的情况下重新定位 matplotlib 图例

How to reposition matplotlib legend without plots to change

我有一个包含 6 个数据非常相似的子图的图。我只想要一个图例,我想将它放置在两个子图重叠的位置,但 matplotlib 似乎阻止了这一点。如果我将图例向上移动一点,它会改变子图的格式,这样它就不会与另一个图重叠。所以我的问题是:如何在不影响 subplots/how 的一般组成的情况下替换图例以允许重叠?

我已经尝试过 locbbox_to_anchor 但都重新格式化了子图(即改变轴) 使用的语法:ax[1,1].legend(["line1",..,"lineN"],loc=(0.5,0.5) 和相同但 loc 替换为 bbob_to_anchor

编辑: 我刚刚找到 this 答案,但我认为它对我不起作用,因为我没有在绘图调用中定义标签。我根据该答案尝试的是:

handles,labels = ax[1,1].get_legend_handles_labels()
    fig.legend(handles, ["line0",..,"lineN"], loc=(0.5,0.5))

但这给了我一个空洞的传说。就是一个小方块

EDIT2:进一步说明我的具体情况:

f, ax = plt.subplots(3,2,  figsize=(10,8), sharex=True, sharey=True)
x = np.linspace(0,100,100)
y = np.random.rand(100,3)
ax[0,0].plot(x,y)
ax[0,1].plot(x,y)
ax[1,0].plot(x,y)
ax[1,1].plot(x,y)
ax[2,0].plot(x,y)
ax[2,1].plot(x,y)
//One single legend for the three lines represented in y. It should overlap part of subplot 0,1 and 1,1

好的,我根据 this 的回答自己找到了解决方案,但略有不同。 有效的是:

handles = ax[0,0].get_lines()
labels = ["line0",...,"lineN"] #obviously expand this and do not use ...
fig.legend(handles, labels, loc=(0.5,0.5)

所以技巧是使用 get_lines 而不是 get_legend_handles_labels 如果你没有在你的绘图调用中定义标签。

你也可以试试这个:

f, (ax1, ax2, ax3) = plt.subplots(3,  figsize=(10,8), sharex=True, sharey=True)
l1,=ax1.plot(x,y, color='r', label='Blue stars')
l2,=ax2.plot(x,y, color='g')
l3,=ax3.plot(x,y, color='b')
ax1.set_title('Title')
plt.legend([l1, l2, l3],["label 1", "label 2", "label 3"], loc='center left', bbox_to_anchor=(1, 3.2))
plt.show()