如何在matplotlib中任意绘制多个子图?

时间:2017-05-02 05:43:22

标签: python matplotlib

当我想制作2个地块时,我通常会这样做:

f, (ax1, ax2) = plt.subplots(1, 2)

如果我有多个图像列表并希望在每个列表上运行相同的功能,以便绘制该列表中的每个图像,该怎么办?每个列表具有不同数量的图像。

2 个答案:

答案 0 :(得分:2)

怎么样:

num_subplots = len(listoffigs)
axs = []
for i in range(num_subplots):
    axs.append(plt.subplot(num_subplots, 1, i+1))

甚至更短,作为列表理解:

num_subplots = len(listoffigs)
axs = [plt.subplot(num_subplots, 1, i+1) for i in range(num_subplots)]

*)编辑:添加了列表理解解决方案

答案 1 :(得分:0)

首先,拥有多个列表或一个长列表没有区别,因此将所有列表合并为一个

biglist = list1 + list2 + list3

然后,您可以从列表的长度确定所需的子图的数量。在最简单的情况下,制作一个方格,

n = int(np.ceil(np.sqrt(len(biglist))))
fig, axes = plt.subplots(n,n)

使用图像填充网格

for i, image in enumerate(biglist):
    axes.flatten()[i].imshow(image)

对于其余的轴,请关闭脊椎

while i < n*n:
    axes.flatten()[i].axis("off")
    i += 1