使用matplotlib子图时,减少行之间的差距?

时间:2017-05-10 13:08:02

标签: python matplotlib

我的子图结果 subplot

我的代码

fig,ax = plt.subplots(rows,cols, figsize = [24,24])
plt.subplots_adjust(hspace=0, wspace=0)

for i in range(cols):
    step = 6
    ind = i*step
    ax[0,i].imshow(a[ind,:,:],cmap='gray')
    ax[0,i].axis('off')

    ax[1,i].imshow(b[ind,:,:],cmap='gray')
    ax[1,i].axis('off')

    ax[2,i].imshow(c[ind,:,:],cmap='gray')
    ax[2,i].axis('off')

然而,似乎plt.subplots_adjust(hspace = 0,wspace = 0)根本不起作用。我注意到它强迫数字具有相同的x和y大小,你能帮我纠正一下吗?

3 个答案:

答案 0 :(得分:2)

您已使用class A { enum B { C = 0, D }; template <A::B value = A::C> int fun(); }; template<A::B value> int A::fun<A::B::C>() { return 1; } template<A::B value> int A::fun<A::B::D>() { return fun<B>() + 1; } 将其设为方形图像。然后figsize=[24,24]会使每个subplots_adjust坚持相邻的ax[i,j]。但ax.imshow()并未填写每个ax。在上面的示例中,如果图像的垂直尺寸较大,则会填充分配给该轴的区域,但会扭曲图像。如果您想尝试一下,请使用命令ax[0,i].imshow(a[ind,:,:],cmap='gray', aspect='auto')aspect='auto'部分将拉伸图像以填充轴。 如果您希望图像宽高比不会失真,则必须相应地修改figsize

答案 1 :(得分:1)

您可以缩小垂直方向的数字大小,例如

fig,ax = plt.subplots(rows,cols, figsize = [24,12])

或者您可以保持方形图的大小,但在子图周围放置更多的边距

plt.subplots_adjust(bottom=0.3, top=0.7, hspace=0)

答案 2 :(得分:1)

figsize中的比率应与plt.subplot(rows, cols, figsize)中的行和列的比率相同。例如,如果row为2,cols为4,则比率为1/2,因此figsize为(15,7.5)(相同比率)会很好。

以下代码为例。

fig, ax = plt.subplots(2, 4, figsize=(15, 7.5))
for i in range(2):
    for j in range(4):
        img = cv2.cvtColor(cv2.imread(os.path.join('../input/deepfake486326facescleaned', train_df.loc[i*2+j, 'name_path'])), cv2.COLOR_BGR2RGB)
        ax[i][j].imshow(img)
        ax[i][j].set_title(train_df.loc[i*2+j, 'label'])

enter image description here

相关问题