python Matplotlib tight_layout()永远无法正常工作

2024-09-29 00:14:54 发布

您现在位置:Python中文网/ 问答频道 /正文

摘要:我想使用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()

该图如图所示: enter image description here 子图形和边距之间的空间非常随机,这可以从不同图层的特征图中看出(子图的数量不同):

enter image description hereenter image description here


Tags: in图形示例数量绘制plt特征ax
1条回答
网友
1楼 · 发布于 2024-09-29 00:14:54

可以使用^{}设置地物布局参数

基本代码

import matplotlib.pyplot as plt

N = 5

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

plt.show()

enter image description here

完整代码

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()

enter image description here


为了避免多次尝试设置lefttop等的值,我建议您绘制一个图形,按下配置子图按钮:

enter image description here

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

相关问题 更多 >