python imshow调整比例_python – 如何在matplotlib中设置宽高比?

第三次的魅力。我的猜测是,这是一个错误,

Zhenya’s answer建议它在最新版本中修复。我有版本0.99.1.1,我创建了以下解决方案:

import matplotlib.pyplot as plt

import numpy as np

def forceAspect(ax,aspect=1):

im = ax.get_images()

extent = im[0].get_extent()

ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)

data = np.random.rand(10,20)

fig = plt.figure()

ax = fig.add_subplot(111)

ax.imshow(data)

ax.set_xlabel('xlabel')

ax.set_aspect(2)

fig.savefig('equal.png')

ax.set_aspect('auto')

fig.savefig('auto.png')

forceAspect(ax,aspect=1)

fig.savefig('force.png')

这是’force.png’:

下面是我不成功,但希望信息的尝试。

第二个答案:

我的’原始答案’下面是过度杀伤,因为它做类似于axes.set_aspect()。我想你想使用axes.set_aspect(‘auto’)。我不明白为什么会是这样,但它为我产生一个正方形图像,例如这个脚本:

import matplotlib.pyplot as plt

import numpy as np

data = np.random.rand(10,20)

fig = plt.figure()

ax = fig.add_subplot(111)

ax.imshow(data)

ax.set_aspect('equal')

fig.savefig('equal.png')

ax.set_aspect('auto')

fig.savefig('auto.png')

生成具有“相等”宽高比的图像绘图:

和一个具有“自动”宽高比:

下面在“原始答案”中提供的代码为明确控制的宽高比提供了起点,但是一旦调用imshow,它似乎被忽略。

原始答案:

下面是一个例程,它将调整子图参数,以便获得所需的宽高比:

import matplotlib.pyplot as plt

def adjustFigAspect(fig,aspect=1):

'''

Adjust the subplot parameters so that the figure has the correct

aspect ratio.

'''

xsize,ysize = fig.get_size_inches()

minsize = min(xsize,ysize)

xlim = .4*minsize/xsize

ylim = .4*minsize/ysize

if aspect < 1:

xlim *= aspect

else:

ylim /= aspect

fig.subplots_adjust(left=.5-xlim,

right=.5+xlim,

bottom=.5-ylim,

top=.5+ylim)

fig = plt.figure()

adjustFigAspect(fig,aspect=.5)

ax = fig.add_subplot(111)

ax.plot(range(10),range(10))

fig.savefig('axAspect.png')

这产生了一个这样的图:

我可以想象如果你有多个子图在图中,你想要包括y和x子图的数量作为关键字参数(默认为1)提供的例程。然后使用这些数字和hspace和wspace关键字,可以使所有子图都具有正确的长宽比。

你可能感兴趣的:(python,imshow调整比例)