如何在 matplotlib 中设置纵横比?

新手上路,请多包涵

我正在尝试制作一个正方形图(使用 imshow),即 1:1 的纵横比,但我做不到。这些都不起作用:

 import matplotlib.pyplot as plt

ax = fig.add_subplot(111,aspect='equal')
ax = fig.add_subplot(111,aspect=1.0)
ax.set_aspect('equal')
plt.axes().set_aspect('equal')

似乎这些调用只是被忽略了(我似乎经常遇到 matplotlib 的一个问题)。

原文由 jtlz2 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

第三次魅力。我的猜测是这是一个错误, Zhenya 的回答 表明它已在最新版本中修复。我有 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)包含在提供的例程中。然后使用这些数字和 hspacewspace 关键字,您可以使所有子图具有正确的纵横比。

原文由 Yann 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 plt.gca() 获取当前轴和设置纵横比的简单选项

plt.gca().set_aspect('equal')

代替你的最后一行

原文由 Liz Deucker 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题