How to enclose arbitrarily many subplots in matplotlib?

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

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

      

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

+3


source to share


2 answers


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, since 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

+2


source


At first there is no difference between multiple lists or one long list, so combine all the lists into one

biglist = list1 + list2 + list3

      

Then you can determine the number of subfences needed for 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 other axles, unscrew the spikes

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

      

0


source







All Articles