可视化向量运算with numpy & matplotlib
import numpy as nimport matplotlib.pyplot as m
vec_a = n.array()
vec_b = n.array([-1,1])
vec_sum = vec_a + vec_b
vec_dif = vec_a - vec_b
vec_tim = vec_a * 0.5
print(vec_a)
print(vec_b)
print(vec_sum)
print(vec_dif)
m.quiver(0,0,vec_a,vec_a,
angles = 'xy',scale_units = 'xy',
scale = 1,color = 'red',label = 'a')
m.quiver(0,0,vec_b,vec_b,
angles = 'xy',scale_units = 'xy',
scale = 1,color = 'blue',label = 'b')
m.quiver(0,0,vec_sum,vec_sum,
angles = 'xy',scale_units = 'xy',
scale = 1,color = 'lime',label = 'a+b')
m.quiver(0,0,vec_dif,vec_dif,
angles = 'xy',scale_units = 'xy',
scale = 1,color = 'violet',label = 'a-b')
m.quiver(0,0,vec_tim,vec_tim,
angles = 'xy',scale_units = 'xy',
scale = 1,color = 'yellow',label = '0.5a')
m.title('Vector Samples')
m.xticks(n.arange(-2, 3, 1))
m.yticks(n.arange(0, 4, 1))
m.figure(figsize = (5,5))
m.show() 问题主要出在vec_a和vec_b没有给具体数值,n.array()会报错;另外quiver的用法不太对,前两个参数是起点坐标,后两个参数是向量的U、V分量,不能直接把整个向量传进去。
可以先改成这样:
import numpy as np
import matplotlib.pyplot as plt
vec_a = np.array()
vec_b = np.array()
vec_sum = vec_a + vec_b
vec_dif = vec_a - vec_b
vec_tim = vec_a * 0.5
print(vec_a)
print(vec_b)
print(vec_sum)
print(vec_dif)
plt.figure(figsize=(5, 5))
plt.quiver(0, 0, vec_a, vec_a,
angles='xy', scale_units='xy', scale=1,
color='red', label='a')
plt.quiver(0, 0, vec_b, vec_b,
angles='xy', scale_units='xy', scale=1,
color='blue', label='b')
plt.quiver(0, 0, vec_sum, vec_sum,
angles='xy', scale_units='xy', scale=1,
color='lime', label='a+b')
plt.quiver(0, 0, vec_dif, vec_dif,
angles='xy', scale_units='xy', scale=1,
color='violet', label='a-b')
plt.quiver(0, 0, vec_tim, vec_tim,
angles='xy', scale_units='xy', scale=1,
color='yellow', label='0.5a')
plt.title('Vector Samples')
plt.xticks(np.arange(-2, 3, 1))
plt.yticks(np.arange(0, 4, 1))
plt.legend()
plt.show()
记得先调用plt.figure再画图,不然画面尺寸设置不生效。这样就能正确显示向量了。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页:
[1]