Python并排显示两个包含多个子图的图形

时间:2020-02-04 09:10:00

标签: python-3.x matplotlib

如标题中所述,使用matplotlib.pyplot时可以将两个数字合而为一吗?

使用此代码,我将生成如下图像:

def plot_output_image(label, clothes):
plt.clf()
fig = plt.figure(figsize=(5, 2))
columns = 5
rows = 2

for i in range(1, columns * rows + 1):
    filename = similar_images['class'].iloc[i - 1] + '/' + str(similar_images['id'].iloc[i - 1]) + '.jpg'
    img = load_img((files.small_images_classes_directory / filename).absolute().as_posix())
    img = img_to_array(img) / 255
    fig.add_subplot(rows, columns, i)
    plt.axis('off')
    plt.imshow(img)

plt.savefig((files.ROOT / 'similarity-output' / label / ('out_' + clothes)).absolute().as_posix())
plt.close()

similar trousers

我如何并排放置第二个图形,以使输出变成这样? similar trousers + template

1 个答案:

答案 0 :(得分:2)

对于复杂的布局,可以使用GridSpecsubplot2grid()生成可以跨越几行/列的子图。有关更多信息,请参见this tutorial

例如,使用gridspec可以做到:

from matplotlib import gridspec
gs00 = gridspec.GridSpec(1,2, width_ratios=[1,2])
gs01 = gridspec.GridSpecFromSubplotSpec(2,5, subplot_spec=gs00[0,1])
fig = plt.figure(figsize=(8,3))
left_ax = fig.add_subplot(gs00[0,0])
small_axs = [fig.add_subplot(gs01[i,j]) for i in range(2) for j in range(5)]

enter image description here