Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib: empty area appears on the figure when plotting many subplots

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!

like image 888
Wojciech Walczak Avatar asked Jun 06 '26 18:06

Wojciech Walczak


1 Answers

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.

like image 59
Rutger Kassies Avatar answered Jun 08 '26 10:06

Rutger Kassies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!