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()
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')
with
forceAspect(ax,aspect=1.0)
Example with a colorbar
Another example with a colorbar
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
Links | Site |
---|---|
How can I set the aspect ratio in matplotlib? | stackoverflow |
matplotlib imshow display ratio fix to square | stackoverflow |
Imshow: extent and aspect | stackoverflow |
change figure size and figure format in matplotlib | stackoverflow |