NPMitchell
NPMitchell

Reputation: 313

matplotlib: Make legend appear above other subplots

I want to make a legend that can overlay all subplots in a figure. If I set its framealpha=1.0 then it covers stuff on its subplot, but I need it to lie "on top of" the data in other subplots too. Note that I need have the red lines to pass BEHIND the legend; by 'above' I'm talking about the z dimension, not its y position.

Here is an example:

import matplotlib.pyplot as plt
import numpy as np

x1 = np.random.rand(25)
y1 = np.random.rand(25)
x2 = np.random.rand(25)
y2 = np.random.rand(25)

f, axes = plt.subplots(1,2)
axes[0].plot(x1,y1,'b-',label='data 1 blah blah blah this is a wide legend that should sit top of BOTH subplots')
axes[1].plot(x2,y2,'r-')
axes[0].axis('off')
axes[1].axis('off')

leg = axes[0].legend(bbox_to_anchor=(0.5, .8), loc=2, fontsize=8, frameon=True, framealpha = 1.0)
rect = leg.get_frame()
rect.set_facecolor([0.9,0.9,0.9])
leg.set_zorder(100)
plt.show()

enter image description here

THANKS!

Upvotes: 4

Views: 4642

Answers (1)

albertoql
albertoql

Reputation: 518

In general, zorder changes the order in which different artists are drawn (see, for example, the related demo from matplotlib).

The problem raised by the OP of not having the legend overlaid on top of all of the subplots derives from the fact that zorder is set for the legend, which is a children of the subplot in axes[0]. So, changing that value affects the order only within axes[0]. Using the function get_zorder (e.g., axes[0].get_zorder()) allows to check the zorder for the different subplots, and it is possible to see that axes[0] and axes[1] have the same zorder. This causes the legend not to be on the foreground of the right subplot.

In order to solve the problem, as axes[0] is the plot with the legend, its zorder should be set to a higher value (e.g., axes[0].set_zorder(100)). This results in the correct display of the legend, as shown in the following figure. Note that drawing in different orders the artists in the figure can be generalized; one useful function of figure is get_children() that returns all the artists in the figure, and thus allowing to iterate over all of them . Resulting image with legend correctly on the foreground.

Upvotes: 6

Related Questions