首页 > 解决方案 > 如何重新定位matplotlib图例而不改变地块

问题描述

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

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

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

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

标签: pythonmatplotliblegend

解决方案


你也可以试试这个:

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

在此处输入图像描述


推荐阅读