gpt4 book ai didi

python - 如何使用 matplotlib 在 python 中绘制向量

转载 作者:太空狗 更新时间:2023-10-29 17:00:02 28 4
gpt4 key购买 nike

我正在学习线性代数类(class),我想可视化作用中的向量,例如向量加法、法向量等。

例如:

V = np.array([[1,1],[-2,2],[4,-7]])

在这种情况下,我想绘制 3 个向量 V1 = (1,1), M2 = (-2,2), M3 = (4,-7)

然后我应该能够添加 V1、V2 来绘制一个新的向量 V12(全部在一个图中)。

当我使用下面的代码时,情节不符合预期

import numpy as np
import matplotlib.pyplot as plt
M = np.array([[1,1],[-2,2],[4,-7]])

print("vector:1")
print(M[0,:])
# print("vector:2")
# print(M[1,:])
rows,cols = M.T.shape
print(cols)

for i,l in enumerate(range(0,cols)):
print("Iteration: {}-{}".format(i,l))
print("vector:{}".format(i))
print(M[i,:])
v1 = [0,0],[M[i,0],M[i,1]]
# v1 = [M[i,0]],[M[i,1]]
print(v1)
plt.figure(i)
plt.plot(v1)
plt.show()

最佳答案

怎么样

import numpy as np
import matplotlib.pyplot as plt

V = np.array([[1,1], [-2,2], [4,-7]])
origin = np.array([[0, 0, 0],[0, 0, 0]]) # origin point

plt.quiver(*origin, V[:,0], V[:,1], color=['r','b','g'], scale=21)
plt.show()

enter image description here

然后将任意两个向量相加并将它们绘制成同一个图形,在调用 plt.show() 之前执行此操作。像这样的东西:

plt.quiver(*origin, V[:,0], V[:,1], color=['r','b','g'], scale=21)
v12 = V[0] + V[1] # adding up the 1st (red) and 2nd (blue) vectors
plt.quiver(*origin, v12[0], v12[1])
plt.show()

enter image description here

注意:在 Python2 中使用 origin[0], origin[1] 而不是 *origin

关于python - 如何使用 matplotlib 在 python 中绘制向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42281966/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com