How to change imshow aspect ratio and fit the colorbar size in matplotlib ?

Published: May 20, 2019

DMCA.com Protection Status

An example of how to change imshow aspect ratio and adjust the colorbar accordingly in matplotlib:

Comment changer la forme d'une figure imshow et avoir la barre de couleurs de même taille avec matplotlib ?
Comment changer la forme d'une figure imshow et avoir la barre de couleurs de même taille avec matplotlib ?

import numpy as np
import matplotlib.pyplot as plt

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

plt.imshow(data)

plt.colorbar()

plt.savefig("imshow_extent_custum_aspect_ratio_00.png", bbox_inches='tight')
plt.close()

How to change imshow aspect ratio and fit the colorbar size in matplotlib ?
How to change imshow aspect ratio and fit the colorbar size 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