Skip to content Skip to sidebar Skip to footer

How To Reposition Matplotlib Legend Without Plots To Change

I have a plot with 6 subplots with very similar data. I only want one legend and I would like to place it such that it overlaps two subplots, but it seems matplotlib prevents this.

Solution 1:

You can also try something this:

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

enter image description here

Solution 2:

Oke I found the solution myself based on this answer but slightly different. What worked is:

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)

So the trick is to use get_lines instead of get_legend_handles_labels if you haven't define labels in your plot calls.

Post a Comment for "How To Reposition Matplotlib Legend Without Plots To Change"