pcu
pcu

Reputation: 1214

Put legend on a place of a subplot

I would like to put a legend on a place of a central subplot (and remove it). I wrote this code:

import matplotlib.pylab as plt
import numpy as np

f, ax = plt.subplots(3,3)
x = np.linspace(0, 2. * np.pi, 1000)
y = np.sin(x)

for axis in ax.ravel():
    axis.plot(x, y)
    legend = axis.legend(loc='center')

plt.show()

I do not know how to hide a central plot. And why legend is not appear?

example plot

This link did not help http://matplotlib.org/1.3.0/examples/pylab_examples/legend_demo.html

Upvotes: 4

Views: 1909

Answers (1)

kiliantics
kiliantics

Reputation: 1188

There are several problems with your code. In your for loop, you are attempting to plot a legend on each axis (the loc="center" refers to the axis, not the figure), yet you have not given a plot label to represent in your legend.

You need to choose the central axis in your loop and only display a legend for this axis. This iteration of the loop should have no plot call either, if you don't want a line there. You can do this with a set of conditionals like I have done in the following code:

import matplotlib.pylab as plt
import numpy as np

f, ax = plt.subplots(3,3)
x = np.linspace(0, 2. * np.pi, 1000)
y = np.sin(x)

handles, labels = (0, 0)

for i, axis in enumerate(ax.ravel()):

    if i == 4:
        axis.set_axis_off()
        legend = axis.legend(handles, labels, loc='center')
    else:
        axis.plot(x, y, label="sin(x)")

    if i == 3:
        handles, labels = axis.get_legend_handles_labels()

plt.show()

This gives me the following image:

enter image description here

Upvotes: 5

Related Questions