首页 > 解决方案 > 在 Matplotlib 中定义 GridSpec 的宽度/高度

问题描述

我有一个简单的情节来比较一些图像,如下所示:

fig = plt.figure(constrained_layout=True,figsize=(15,15))
gs = GridSpec(3,2, figure=fig)
axes = []

ax = fig.add_subplot(gs[0, 0])
ax.imshow(square, cmap='gray')
ax.set_title('Original')
axes.append(ax)

ax = fig.add_subplot(gs[0, 1])
im1 = ax.imshow(scaled_square_sobel, cmap='gray')
ax.set_title('Sobel')
axes.append(ax)

ax = fig.add_subplot(gs[1, 0])
im2 = ax.imshow(scaled_square_sobel_x, cmap='gray')
ax.set_title('Sobel X')
axes.append(ax)

ax = fig.add_subplot(gs[1, 1])
ax.imshow(scaled_square_sobel_y, cmap='gray')
ax.set_title('Sobel Y')
axes.append(ax)

ax = fig.add_subplot(gs[2,0:2])
fig.colorbar(im2, cax=ax, orientation='horizontal')
plt.suptitle('Comparacao Sobel');

看起来像这样

奇怪的彩条

正如您所看到的,颜色条采用了整个绘图的高度,而不是一个漂亮而优雅的小高度。如何“强制” GridSpec 具有预定义的高度。

当然,我可以创建一个 (30,20) 网格规范并将每个图定义为更大的切片,但恕我直言,这也不优雅,似乎我正在使用 HTML 表格。

有什么想法可以改进上面的代码吗?

标签: pythonmatplotlib

解决方案


无需为颜色条制作网格规范:

fig, axs = plt.subplots(constrained_layout=True,figsize=(15,15))

# other axes...

ax = axs[1, 1]
im2 = ax.imshow(np.random.rand(10,10), cmap='gray')
ax.set_title('Sobel Y')

fig.colorbar(im2, ax=axs, orientation='horizontal')

推荐阅读