display image with maximum width keeping an equal ratio

Viewed 103

How to display an image with imshow on all the width of an axe (viewport) but keeping the ratio 'equal' ?

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(nrows=2, figsize=(8,8))
img = ax[0].imshow(np.random.random((10,10)), aspect='equal')
line = ax[1].plot([12,34],[45,78])

enter image description here

I would like that the image width be aligned on the line plot keeping an equal ratio even if that implies having blank around. My application has a zooming feature coded on the image in fact so I would to offer all the width possible for its display.

So in few words, I would like the same width as with aspect='auto' but with square pixels. Is it possible ? Thanks.

1 Answers

Found with a reading of Axes class - set explicitly size (width/height) of axes in given units and the use of

set_adjustable('datalim')
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(nrows=2, figsize=(8,8))
img = ax[0].imshow(np.random.random((10,10)), aspect='equal')
ax[0].set_adjustable('datalim')
line = ax[1].plot([12,34],[45,78])

enter image description here

Related