0

I am plotting 4 subplots in one figure, and I want to adjust the space in-between evenly.

I tried grid.GridSpec.update.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

plt.figure(figsize=(8,8))
gs2 = gridspec.GridSpec(2, 2)
gs2.update(wspace=0.01, hspace=0.01)

ax1 = plt.subplot(gs2[0,0],aspect='equal')
ax1.imshow(img)
ax1.axis('off')

ax2 = plt.subplot(gs2[0,1],aspect='equal')
ax2.imshow(img)
ax2.axis('off')

ax3 = plt.subplot(gs2[1,0],aspect='equal')
ax3.imshow(img)
ax3.axis('off')

ax4 = plt.subplot(gs2[1,1],aspect='equal')
ax4.imshow(img)
ax4.axis('off')

The vertical space in-between 2 plots is too big, and it does not change no matter how I adjust gs2.update(hspace= ), as shown below:

enter image description here

Community
  • 1
  • 1
Jundong
  • 261
  • 4
  • 20
  • 1
    When using subplots with defined aspect, the separation between subplots as defined by the hspace of the grid needs to be seen as the minimal space, depending on the other subplot parameters. So to have the exact spacing as desired you need to set the margins and/or figure size accordingly. – ImportanceOfBeingErnest Dec 28 '17 at 22:35
  • @ImportanceOfBeingErnest. Thank you very much! It is the case. Is there anyway to get around the 'figure size aspect ratio' setting? – Jundong Dec 28 '17 at 22:39
  • 1
    I might recommend [this post](https://stackoverflow.com/questions/42475508/how-to-combine-gridspec-with-plt-subplots-to-eliminate-space-between-rows-of-s). There is also the option to use [AxesGrid](https://matplotlib.org/examples/axes_grid/demo_axes_grid.html). – ImportanceOfBeingErnest Dec 28 '17 at 22:49

1 Answers1

0

It's likely your aspect='equal' that's causing the problem.

Try this

import numpy as np
%matplotlib inline # if in a jupyter notebook like environment

img = np.ones((30, 30))

fig, axes = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(8,8),
                         gridspec_kw={'wspace': 0.01, 'hspace': 0.01})
axes = axes.ravel()

for ax in axes:
    # aspect : ['auto' | 'equal' | scalar], optional, default: None
    ax.imshow(img, aspect='auto')
    ax.axis('off')

enter image description here

zyxue
  • 7,904
  • 5
  • 48
  • 74