enterML
enterML

Reputation: 2285

Maintaing aspect ratio while saving a subplot in matplotlib

Maintaining the aspect ratio while plotting is quiet easy. I was trying to save the subplot while maintaining the aspect ratio but things didn't turn out the way I expected. This is the original plot along with the code how it is generated:

enter image description here

f,ax = plt.subplots()
ax.plot(x_new, y_new, 'black')
ax.set_xlim(0, img.shape[1])
ax.set_ylim(0, img.shape[0])
x0,x1 = ax.get_xlim()
y0,y1 = ax.get_ylim()
ax.set_aspect(abs(x1-x0)/abs(y1-y0))
plt.gca().invert_yaxis()

I saved the subplot as:

extent = ax.get_window_extent().transformed(f.dpi_scale_trans.inverted())
f.savefig('ax_figure.png', bbox_inches=extent) 

But when I read the saved figure and do plt.imshow(img), I get this:

enter image description here

What should I do to get the saved image as in the subplot?

Upvotes: 0

Views: 62

Answers (1)

dseuss
dseuss

Reputation: 1131

The problem is that imshow may change the aspect ratio of the image depending on your settings. To force imshow to use the image's aspect ratio use

plt.imshow(img, aspect='equal')

Upvotes: 1

Related Questions