megashigger
megashigger

Reputation: 9043

How to plot arbitrarily many subplots in matplotlib?

I usually do this when I want to make 2 plots:

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

What if I have multiple lists of images and want to run the same function on each list so that every image in that list is plotted? Each list has a different number of images.

Upvotes: 4

Views: 1358

Answers (2)

JohanL
JohanL

Reputation: 6891

What about:

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

or even shorter, as list comprehension:

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

*) edit: Added list comprehension solution

Upvotes: 4

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

First there is no difference between having several lists or one long list, so merge all lists into one

biglist = list1 + list2 + list3

Then you can determine the number of subplots needed from the length of the list. In the simplest case make a square grid,

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

Fill the grid with your images,

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

For the rest of the axes turn the spines off

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

Upvotes: 1

Related Questions