【发布时间】:2021-10-04 12:17:30
【问题描述】:
总结:我想使用Matplotlib.tight_layout()自动优化包含任意数量子图形的图形布局,2D numpy.array。
示例: 这是一个示例(可以从http://www.filedropper.com/fmap 访问数据)。我想绘制一个 CNN 层的特征图(后来我想让它自动化,所以代码可以从任何模型中绘制任何层的特征图)。这里我只展示一层的代码进行演示:
fmap.shape # (1, 64, 64, 128)
square1 = int(round(math.sqrt(fmap.shape[-1])/8)*8) # 8
square2 = int(fmap.shape[-1]/square1) # 16
ix = 1
for _ in range(square1):
for _ in range(square2):
# specify subplot and turn of axis
ax = plt.subplot(square1, square2, ix)
ax.set_xticks([])
ax.set_yticks([])
# plot filter channel in grayscale
plt.imshow(fmap[0, :, :, ix-1], cmap='gray')
ix += 1
# show the figure
plt.tight_layout()
plt.show()
情节如下图所示: subfigures和margin之间的空间是相当随机的,从不同层的feature map可以看出(subplot的数量不同):
【问题讨论】:
-
我建议查看matplotlib: Tight Layout guide &
matplotlib.pyplot.tight_layout。尝试使用rect参数。预计填充取决于子图的数量和图形大小,并且会因配置而异。 -
感谢您的建议。我一直在玩这些参数。但是没有通用的方法可以使它们起作用。如果您对如何选择这些参数有更多经验,请提供帮助。我试过的东西包括,h_adjust、w_adjust、rect、fig_size等
-
还需要注意的是,您使用的是
imshow,默认为aspect='equal',当x 和y 尺寸相等时,始终显示方形图像。如果你真的想要紧凑的布局,你要么需要设置合适的图形宽度和高度,要么使用imshow(..., aspect='auo')(拉伸图像以适应所需的布局)。
标签: python matplotlib plot layout data-visualization