我如何在 matplotlib 中强制执行方形网格

Ric*_*ker 6 python matplotlib

使用 matplotlib.pyplot 我需要绘制基本的 2D 向量空间图,我需要 x 轴和 y 轴单位的长度在视觉上相等(1 到 1),以便每个网格单元看起来都是方形的(不是压扁的,不是拉长的) )。需要明确的是,我不需要也不想要方形图,但是无论图形纵横比或任一轴的长度如何,我都需要单位始终看起来是方形的。

我试过使用 axis('equal') ,但这不起作用。请注意,我在 Jupyter notebook 中工作,它似乎想限制比例尺的高度。(这可能对 pyplot 有一些干扰限制?我不知道)。我已经为此挣扎了几个小时,但没有找到任何有效的方法。

def plot_vector2d(vector2d, origin=[0, 0], **options):
    return plt.arrow(origin[0], origin[1], vector2d[0], vector2d[1],
          head_width=0.2, head_length=0.3, length_includes_head=True,
          width=0.02, 
          **options)

plot_vector2d([1,0], color='g')
plot_vector2d([0,1], color='g')

plot_vector2d([2,10], color='r')
plot_vector2d([3,1], color='r')

plt.axis([-3, 6, -2, 11], 'equal')
plt.xticks(np.arange(-3, 7, 1))
plt.yticks(np.arange(-2, 11, 1))
plt.grid()
plt.show()
Run Code Online (Sandbox Code Playgroud)

看看与水平轴相比,垂直轴是如何被压缩的。axis('equal') 似乎没有效果。

看看与水平轴相比,垂直轴是如何被压缩的。 axis('equal') 似乎没有效果。

Dav*_*idG 7

您需要将轴的纵横比设置为“相等”。您可以使用set_aspect. 该文件指出:

“相等”从数据到 x 和 y 的绘图单位的相同缩放

然后您的代码变为:

def plot_vector2d(vector2d, origin=[0, 0], **options):
    return plt.arrow(origin[0], origin[1], vector2d[0], vector2d[1],
          head_width=0.2, head_length=0.3, length_includes_head=True,
          width=0.02, 
          **options)

plot_vector2d([1,0], color='g')
plot_vector2d([0,1], color='g')

plot_vector2d([2,10], color='r')
plot_vector2d([3,1], color='r')

plt.axis([-3, 6, -2, 11], 'equal')
plt.grid()
plt.gca().set_aspect("equal")

plt.show()
Run Code Online (Sandbox Code Playgroud)

这使:

在此处输入图片说明