Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bring figure legend to front?

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

like image 975
logi Avatar asked Oct 15 '15 14:10

logi


1 Answers

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

like image 199
jrjc Avatar answered Oct 21 '22 23:10

jrjc