python - 如何在 matplotlib 中设置纵横比?

标签 python 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 的一个问题)。

最佳答案

魅力的三倍。我的猜测是这是一个错误,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”: enter image description here

以下是我不成功的尝试,但希望能提供有用的信息。

第二个答案:

我在下面的“原始答案”有点矫枉过正,因为它的作用类似于 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')

生成具有“相等”纵横比的图像图: enter image description here 和一个具有“自动”纵横比的: enter image description here

下面“原始答案”中提供的代码为明确控制的纵横比提供了起点,但一旦调用 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')

这会产生一个像这样的图形: enter image description here

我可以想象,如果您在图中有多个子图,您可能希望将 y 和 x 子图的数量作为关键字参数(每个默认为 1)包含在提供的例程中。然后使用这些数字和 hspacewspace 关键字,您可以使所有子图具有正确的纵横比。

关于python - 如何在 matplotlib 中设置纵横比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7965743/

相关文章:

python - 如何在 python 中递增数字字符串 '0000000001'?

python - 我求1000以下所有3或5的倍数之和的方法

python - 隐藏刻度标签值但保留轴标签

python - 如何更改使用 Matplotlib 绘制的图形的大小?

python - 使用chdir后找不到任何文件或目录

python - 有效地找到字符串列表中的所有子字符串

python - Pandas 中的子列表

python - 在同一角图中绘制多个数据集

python - 交互式数据可视化 - Python

matplotlib - matplotlib hexbin 中的不规则图 block 大小