10

I have a series of subplots where each one has a legend I want to be outside each subplot overlapping the neighboring subplot. The problem is that the legend is 'on top' of its own plot but below the neighboring plot. Legend does not take zorder as an argument so I am not sure how to solve the problem. This is the code I have used:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row')
f.subplots_adjust(hspace=0.15,wspace=0.1)

for i,j in enumerate([ax1,ax2,ax3,ax4],start=1):
    j.set_title(r'%s'%i)

ax1.plot(x, y,label='curve')
ax2.scatter(x, y)
ax3.scatter(x, 2 * y ** 2 - 1, color='r')
ax4.plot(x, 2 * y ** 2 - 1, color='r')

bbox=(1.3, 1.)
ax1.legend(loc=1,bbox_to_anchor=bbox)
plt.savefig('example.png')

enter image description here

Leb
  • 15,483
  • 10
  • 56
  • 75
logi
  • 101
  • 1
  • 4
  • if using **twinx**: see [Data being plotted over legend when using twinx](https://stackoverflow.com/q/29010078/10197418) – FObersteiner Aug 25 '23 at 09:31

1 Answers1

6

Legend does not take a zorder argument, but axes object does:

You can try:

ax2.set_zorder(-1)

So ax2 goes behind ax1.

Alternatively, you can bring the ax1 forward:

ax1.set_zorder(1)

and as your legend is an object of ax1, it will bring the legend (of ax1) on top of the second plot.

HTH

jrjc
  • 21,103
  • 9
  • 64
  • 78