How to bring the figure legend to the front?

I have a series of subtitles where everyone has a legend that I want to be outside of every subtitle overlapping a neighboring subtitle. The problem is that the legend is “on top” of its own plot, but lower than the neighboring plot. The legend does not accept zorder as an argument, so I'm not sure how to solve the problem. This is the code I 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

+4
source share
1 answer

The legend does not accept an argument zorder, but the object axesdoes:

You may try:

ax2.set_zorder(-1)

So, it ax2goes for ax1.

Alternatively, you can move ax1forward:

ax1.set_zorder(1)

ax1, (ax1) .

+3

Source: https://habr.com/ru/post/1611799/


All Articles