4

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.

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

the list comprehension solution is the one i've been looking for, actually quite a bit faster than other suggestions in similar questions
but how to use the list then as a figure?
You get the different subplots from their list indexes. Thus axs[0] will reference the first subplot.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.