[英]python Matplotlib tight_layout() never work well
Summary: I want to use Matplotlib.tight_layout()
to automatically optimize the layout of figures that contains any number of subfigures with 2D numpy.array
.总结:我想使用Matplotlib.tight_layout()
自动优化包含任意数量子图的图形布局,其中包含 2D numpy.array
。
Example: Here is an example (the data can be accessed from http://www.filedropper.com/fmap ).示例:这是一个示例(数据可以从http://www.filedropper.com/fmap 访问)。 I want to plot the feature map of an CNN layer (later I want to make this automatic, so the code can plot feature maps of any layer from any model).我想绘制 CNN 层的特征图(后来我想让它自动进行,因此代码可以绘制任何模型中任何层的特征图)。 Here I only show the code for one layer for demonstration:这里我只展示一层的代码进行演示:
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()
The plot is shown as:该图显示为: The space between subfigures and the margin are quite random, as can be seen from feature maps of different layers (the number of subplot differs):子图和边距之间的空间是相当随机的,从不同层的特征图可以看出(子图的数量不同):
You can set figure layout parameters with subplots_adjust
.您可以使用subplots_adjust
设置图形布局参数。
Basic code:基本代码:
import matplotlib.pyplot as plt
N = 5
fig, ax = plt.subplots(N, N)
plt.show()
Whole code:全码:
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()
To avoid making too many attempts to set the values of left
, top
, etc..., I suggest you to plot a figure, press the Configure subplots button:为避免多次尝试设置left
、 top
等的值,我建议您绘制一个图形,按Configure subplots按钮:
and manually change the values of those six parameters, until you find a configuration that satisfies you.并手动更改这六个参数的值,直到找到满意的配置。 At this point, you can set those six values directly via code using subplots_adjust
.此时,您可以使用subplots_adjust
通过代码直接设置这六个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.