1

I would like to show two images like these.

import matplotlib as plt
import numpy as np    
fig, axes = plt.subplots(2, 1, )
axes[0].imshow(np.random.random((3, 3)))
axes[1].imshow(np.random.random((6, 3)))

enter image description here Then, I tried sharex=True, which unexpectedly changed the ylim of the two plots. Why?? Is it possible to align the plots without changing the y axis limits?

fig, axes = plt.subplots(2, 1, sharex=True)
axes[0].imshow(np.random.random((3, 3)))
axes[1].imshow(np.random.random((6, 3)))

enter image description here

I use python 3.5.2 and matplotlib 1.5.1.

Community
  • 1
  • 1
Taro Kiritani
  • 724
  • 6
  • 24

1 Answers1

1

By default imshow axes have an equal aspect ratio. To preserve this, the limits are changed.

You have two options:

a) Dispense with equal aspect

Set the aspect to "auto". This allows the subplots to take the available space and share their axis.

import matplotlib.pyplot as plt
import numpy as np
   
fig, axes = plt.subplots(2, 1,sharex=True ) 
axes[0].imshow(np.random.random((3, 3)), aspect="auto")
axes[1].imshow(np.random.random((6, 3)), aspect="auto")

plt.show()

enter image description here

b) Adjust the figure size or spacings

You can adjust the figure size or the spacings such that the axes actually match. You'd then also need to set the height_ratios according to the image dimensions.

import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(2, 1,sharex=True, figsize=(3,5), 
                            gridspec_kw={"height_ratios":[1,2]} ) 
plt.subplots_adjust(top=0.9, bottom=0.1, left=0.295, right=0.705, hspace=0.2)
axes[0].imshow(np.random.random((3, 3)))
axes[1].imshow(np.random.random((6, 3)))

plt.show()

enter image description here

This method either involves some trial and error or a sophisticated calculation, as e.g. in this answer.

Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • I did `fig, axes = plt.subplots(2, 1, sharex=True ,figsize=(1, 5))`. This appends some white spaces in both images, but preserves the aspect ratio. – Taro Kiritani Mar 30 '17 at 22:30