-2

I want to draw only one legend into my figure with subplots of different numbers (from one to five depending of results). The legend should be always drawn above the first plot1. Is there a way to explicit tell matplotlib to use the first plot to draw the legend and not the last2?

I tried to calculate the positions manually in case there is more than one plot but it is not very precise and not a nice solution.

Edit: To explain a bit more. I know how to draw only one legend for many subplots (as you can see in image 2) but I want to know how to fix the legend to the first plot which was drawn and not to the last. I tried to calculate the positions depending of the plot numbers but it is not precise and sometimes looks ugly (legend comes into plot). I want to know whether I can tell matplotlib to fix the legend always to subplot1.

import matplotlib.pyplot as plt
import matplotlib.lines as mlines
plt.figure(1, figsize=(12, 10))
nrows = 5
ncols = 1
plot_number = 1
for i in range(3):
    plot = plt.subplot(nrows, ncols, plot_number)
    plot_number += 1

p3 = mlines.Line2D([], [], color='r')
p4 = mlines.Line2D([], [], color='b')
plt.legend([p3, p4], ['one', 'two'],loc=4, ncol=4,     mode="", borderaxespad=.5, frameon=True,
        bbox_to_anchor=(0., 1.02, 1., .102))
plt.show()

enter image description here enter image description here

honeymoon
  • 2,400
  • 5
  • 34
  • 43
  • it's usually better to show example code, even if it is trivial in your eyes. For us it's much easier to build on existing code, than writing code for you from the scratch. – cel Dec 18 '15 at 08:57
  • Sorry I forgot to add my code. I know the link you referred but I want to know how to say directly to matplotlib to fix the legend to plot one. I don't have a fixed number of plots and therefore a fixed position. That's the problem. – honeymoon Dec 18 '15 at 09:16

1 Answers1

3

Everything becomes simpler if you use the object-oriented interface here. Then you can call legend on a specific subplot's axes. We can simplify your code a little using plt.subplots:

import matplotlib.pyplot as plt
import matplotlib.lines as mlines

nrows = 5
ncols = 1
fig, axes = plt.subplots(nrows,ncols,figsize=(12,10))

p3 = mlines.Line2D([], [], color='r')
p4 = mlines.Line2D([], [], color='b')

# axes[0] is the first subplot
axes[0].legend([p3, p4], ['one', 'two'],loc=4, ncol=4,     mode="", borderaxespad=.5, frameon=True,
        bbox_to_anchor=(0., 1.02, 1., .102))
plt.show()
tmdavison
  • 64,360
  • 12
  • 187
  • 165