1

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. If I move the legend a bit up it changes the format of the subplots such that it doesn't overlap another plot. So my question would be: how to replace the legend without affecting the general make up of the subplots/how to allow overlapping?

I have tried both with loc and bbox_to_anchor but both reformat the subplots (i.e. changes axes) Used syntax: ax[1,1].legend(["line1",..,"lineN"],loc=(0.5,0.5) and the same but loc replaced with bbob_to_anchor

EDIT: I have just found this answer but it doesn't work for me I think because I'm not defining the labels inside the plot call. What I tried based on that answer was:

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

But that gives me an empty legend. Just a little small square

EDIT2: A bit more clarification to my exact situation:

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
C. Binair
  • 419
  • 4
  • 14

2 Answers2

0

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

Jay Patel
  • 1,374
  • 1
  • 8
  • 17
  • True but in my case `y` actually represent three lines. So I'm not sure what `l1`, `l2`, etc. represents in that case – C. Binair Mar 12 '21 at 14:58
  • You can also just enable the legend for the plot where you want them and then just adjust legend. If you can post what you’re expecting then i could help you better. – Jay Patel Mar 12 '21 at 15:45
  • I found already some thing that works for my case see my answer below. But thanks for your help anyway. – C. Binair Mar 12 '21 at 16:02
-1

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.

C. Binair
  • 419
  • 4
  • 14