0

Given a list of images each with size (H, W) and given plot with (n_rows, n_cols). Is there a formula for calculating the right figure size? For example, for the following code below:

images = [np.random.rand(20, 22) for i in range(32)]

fig = plt.figure(figsize=(6, 14))
axes = [fig.add_subplot(9,3,i+1) for i in range(9)]

for c, ax in enumerate(axes):
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.imshow(images[c])

fig.subplots_adjust(wspace=0, hspace=0)

enter image description here

I want to remove the gaps between images. So manually, I found that figsize=(6, 17) yields what I want:

enter image description here

torayeff
  • 9,296
  • 19
  • 69
  • 103
  • 1
    Since you were asking about the formulas, I marked as duplicate of [this one](https://stackoverflow.com/questions/42475508/how-to-combine-gridspec-with-plt-subplots-to-eliminate-space-between-rows-of-s/42481878#42481878). The dupe answer uses the formulas to adjust the subplot parameters. But of course you can equally rearange them to get a figure size out. – ImportanceOfBeingErnest Jun 04 '19 at 21:44
  • @ImportanceOfBeingErnest nice thanks! – torayeff Jun 04 '19 at 21:48

1 Answers1

1

As easy as this:

fig = plt.figure(figsize=(6, 14))
axes = [fig.add_subplot(9,3,i+1) for i in range(9)]

fig.subplots_adjust(wspace=0, hspace=0)
for c, ax in enumerate(axes):
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.imshow(images[c], aspect='auto')
                                  ^^

Output:

enter image description here

Juan C
  • 5,846
  • 2
  • 17
  • 51