I want to move the legend of a figure with several subfigures to the upper center relative to the entire figure. I tried to pass a legend object created with fig.legend
to fig.savefig
using bbox_extra_artist
, as described here. However unlike described the legend gets cut-off:
This is the code that I used:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig, axes = plt.subplots(nrows=5, ncols=3, sharex=True, sharey=False)
legendLines = []
for rI, rA in enumerate(axes):
for cI, ax in enumerate(rA):
line, = ax.plot(x, np.sin(x), label='Sine')
legendLines.append(line)
line, = ax.plot(x, np.cos(x), label='Cosine')
legendLines.append(line)
line, = ax.plot(x, np.arctan(x), label='Inverse tan')
legendLines.append(line)
if cI == 0:
ax.set_ylabel('foo')
if rI == len(axes) -1:
ax.set_xlabel('bar')
if rI == 0:
ax.set_title('baz')
legend = fig.legend(legendLines[:3], ['Sine', 'Cosine', 'Inverse Tan'], 'upper center', frameon=False, ncol=3, borderaxespad=-0.7)
outFile = 'test.pdf'
fig.set_size_inches(8,7)
fig.tight_layout()
fig.savefig(outFile, bbox_extra_artists=[legend], bbox_inches='tight')
plt.close()
I'm looking for a technique that let me define the legend location relative to the entire figure not just a subfigure.
Update:
If I replace
legend = fig.legend(legendLines[:3], ['Sine', 'Cosine', 'Inverse Tan'], 'upper center', frameon=False, ncol=3, borderaxespad=-0.7)
with
legend = fig.legend(legendLines[:3], ['Sine', 'Cosine', 'Inverse Tan'], loc='lower center', frameon=False, ncol=3, bbox_to_anchor=(.5, 0.965))
the result is the same: plot area is not increased and legend gets shifted off the plot.
(System: matplotlib-1.2.0-py2.7-macosx-10.8-intel)