在matplotlib中保存子图时保持纵横比

时间:2017-09-13 09:35:52

标签: python python-2.7 matplotlib

在绘图时保持纵横比很容易。我试图在保持纵横比的同时保存子图,但事情并没有像我预期的那样。这是原始图以及代码生成方式:

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()

我将子剧情保存为:

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

但是,当我阅读已保存的数字并执行plt.imshow(img)时,我明白了:

enter image description here

如何在子图中获取保存的图像?

1 个答案:

答案 0 :(得分:1)

问题是imshow可能会根据您的设置更改图像的宽高比。要强制imshow使用图像的宽高比,请使用

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