Question

I am plotting a few dozen of subplots with matplotlib. At the bottom of the figure, between the last row of plots and the legend, an empty area appears. The empty area grows larger when I add more subplots. Any idea how to get rid of this empty space?

Here's the working code:

import textwrap
import matplotlib.pyplot as plt
from collections import OrderedDict

rlen = 31 # number of plots
figsize = (11, 3) # matrix of subplots
fig = plt.figure(figsize=(figsize[1]*4, figsize[0]*4))

plots = []
for f_ind in range(rlen):
   plots.append(fig.add_subplot(figsize[0], figsize[1], f_ind))

fig.subplots_adjust(wspace=0.5, hspace=0.5)

for ax in plots:
   atitle = 'Aaa bbb ccc ' * 10
   ax.set_title('\n'.join(textwrap.wrap(atitle, 45)), fontsize=10)
   ax.plot(range(10), range(10), 'o', color='red', label='LABEL_1')
   revlist = list(reversed(range(10)))
   ax.plot(revlist, range(10), 'o', color='blue', label='LABEL_2')
   ax.set_xlabel('Train set size', fontsize=9)
   ax.set_ylabel('Accuracy (%)', fontsize=9)

handles, labels = plt.gca().get_legend_handles_labels()
by_label = OrderedDict(zip(labels, handles))
lgd = fig.legend(by_label.values(), by_label.keys(), loc='lower center', ncol=4)
fig.savefig('ZZZ.png', dpi=fig.dpi, bbox_extra_artists=(lgd,), bbox_inches='tight')

You can also view the example result here. Thanks!

Was it helpful?

Solution

You can use the bottom keyword for subplots_adjust to set the point to which the subplots should be drawn with respect to the figure.

So for example:

fig.subplots_adjust(wspace=0.5, hspace=0.5, bottom=0)

The legend will then be close to the 'lowest' subplots. Here is a crop from the bottom of the resulting image:

enter image description here

Besides bottom, there are also left, right and top keywords.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top