【问题标题】:python Matplotlib tight_layout() never work wellpython Matplotlib tight_layout() 永远无法正常工作
【发布时间】: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


【解决方案1】:

您可以使用subplots_adjust设置图形布局参数。

基本代码

import matplotlib.pyplot as plt

N = 5

fig, ax = plt.subplots(N, N)

plt.show()

完整代码

import matplotlib.pyplot as plt

N = 5

fig, ax = plt.subplots(N, N)

plt.subplots_adjust(left = 0.1, top = 0.9, right = 0.9, bottom = 0.1, hspace = 0.5, wspace = 0.5)

plt.show()


为避免过多尝试设置left、top等的值,建议您绘制一个图形,按配置子图按钮: p>

并手动更改这六个参数的值,直到找到满意的配置。此时,您可以使用subplots_adjust 直接通过代码设置这六个值。

【讨论】:

  • 您好 Andrea,感谢您提供解决方案。这只能部分解决我的问题,因为我有很多数字要绘制并且真的需要它是全自动的。您的回答是一个不错的解决方法,但仍需要反复试验。
猜你喜欢
  • 1970-01-01
  • 2019-12-02
  • 2018-11-11
  • 2021-07-09
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多