matplotlib:当绘制许多子图时,图中出现空白区域

Woj*_*zak 3 python matplotlib

我正在使用matplotlib绘制几十个子图.在图的底部,在最后一行图和图例之间,出现一个空白区域.当我添加更多的子图时,空白区域会变大.知道如何摆脱这个空旷的空间吗?

这是工作代码:

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')
Run Code Online (Sandbox Code Playgroud)

您还可以在此处查看示例结果.谢谢!

Rut*_*ies 5

您可以使用bottom关键字for subplots_adjust来设置相对于图形绘制子图的点.

例如:

fig.subplots_adjust(wspace=0.5, hspace=0.5, bottom=0)
Run Code Online (Sandbox Code Playgroud)

然后,图例将接近"最低"子图.以下是生成图像底部的裁剪:

在此输入图像描述

此外bottom,还有left,righttop关键字.