How to change imshow aspect ratio in matplotlib ?

Published: May 20, 2019

DMCA.com Protection Status

Examples of how to change imshow aspect ratio in matplotlib:

Matplotlib imshow function can return figures with very elongated shapes, example:

import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(50,1000)

plt.imshow(data, extent=[-1,1,-10,10])
plt.savefig("imshow_extent_custum_aspect_ratio_01.png", bbox_inches='tight')
plt.close()

How to change imshow aspect ratio in matplotlib ?
How to change imshow aspect ratio in matplotlib ?

Imshow option 'aspect'

A solution to change imshow aspect ratio is to use the imshow option "aspect", example:

plt.imshow(data, extent=[-1,1,-10,10],aspect='auto')

or

plt.imshow(data, extent=[-1,1,-10,10],aspect=10)

Create your function 'aspect ratio':

However, it is difficult to adjust manually the figure shape using the option 'aspect'. A better solution (found here ) is to create a function that adjust automatically the aspect ratio:

import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(50,1000)

def forceAspect(ax,aspect):
    im = ax.get_images()
    extent =  im[0].get_extent()
    ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.imshow(data, extent=[-1,1,-10,10])
forceAspect(ax,aspect=0.5)
fig.savefig("imshow_extent_custum_aspect_ratio_02.png", bbox_inches='tight')

How to change imshow aspect ratio in matplotlib ?
How to change imshow aspect ratio in matplotlib ?

with

 forceAspect(ax,aspect=1.0)

How to change imshow aspect ratio in matplotlib ?
How to change imshow aspect ratio in matplotlib ?

Example with a colorbar

Another example with a colorbar

How to change imshow aspect ratio in matplotlib ?
How to change imshow aspect ratio in matplotlib ?

import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(50,1000)

def forceAspect(ax,aspect):
    im = ax.get_images()
    extent =  im[0].get_extent()
    ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)

fig = plt.figure()
ax = fig.add_subplot(111)

img = plt.imshow(data, extent=[-1,1,-10,10])
forceAspect(ax,aspect=1.0)


v1 = np.linspace(data.min(), data.max(), 8, endpoint=True)
cb = plt.colorbar(ticks=v1)
cb.ax.set_yticklabels(["{:4.2f}".format(i) for i in v1], fontsize='7')

fig.savefig("imshow_extent_custum_aspect_ratio_04.png", bbox_inches='tight')

References

Image

of