在 python matplotlib 中向量绘制不正确

问题描述 投票:0回答:1

我需要编写一个程序来绘制向量数组。我编写了以下代码:

import matplotlib.pyplot as plt

vectors = [
    [-1, 0, 1, 0],
    [9, 0, 11, 0],
    [0, 9, 0, 11],
    [10, 9, 10, 11]
]

for vector in vectors:
    plt.quiver(vector[0], vector[1], vector[2], vector[3])

plt.grid(True)
plt.show()

enter image description here

矢量渲染不正确,右上角的矢量发生了一些奇怪的事情。

我尝试将绘制向量的程序一一改写,但结果还是一样。

python matplotlib vector
1个回答
0
投票

默认情况下,

angles="uv"
,它使用
U
V
参数来确定箭头的方向。你想要的是
angles="xy"
文档说:

'xy':数据坐标中的箭头方向,即箭头从(x,y)指向(x+u,y+v)。使用这个例如用于绘制梯度场。

由于每个向量中的最后两个值是端点的坐标,因此您需要减去起始值,因为 matplotlib 期望

U
V
分别为
dx
dy

为了确保它们正确缩放,请遵循文档中关于

scale_units
参数的说明:

要在 x-y 平面上绘制向量,其中 u 和 v 与 x 和 y 具有相同的单位,请使用angle='xy'、scale_units='xy'、scale=1

因此,您的代码应如下所示。

import matplotlib.pyplot as plt

plt.close("all")

vectors = [
    [-1, 0, 1, 0],
    [9, 0, 11, 0],
    [0, 9, 0, 11],
    [10, 9, 10, 11]
]

for vector in vectors:
    print(vector[0], vector[1], vector[2] - vector[0], vector[3] - vector[1],)
    plt.quiver(vector[0], vector[1],
               vector[2] - vector[0], vector[3] - vector[1],
               angles="xy", scale_units="xy", scale=1)
plt.xlim(-2, 12)
plt.ylim(-1, 12)
plt.grid()
plt.show()

© www.soinside.com 2019 - 2024. All rights reserved.