Python 绘制 向量减法
flyfish
import matplotlib.pyplot as plt
# 向量数据
a = [1, 2]
b = [3, 2]
# 计算-a 和 a-b
minus_b = [-x for x in b] # 反转向量b得到-b
a_minus_b = [a[i] + minus_b[i] for i in range(2)] # 计算a - b
# 绘制原点
plt.plot([0], [0], 'ko') # 黑色圆点表示原点
# 绘制向量a、b、-b和a-b
colors = ['blue', 'red', 'purple', 'green']
labels = ['a=[1, 2]', 'b=[3, 2]', '-b=[-3, -2]', 'a-b=[-2, 0]']
for vec, color, label in zip([a, b, minus_b, a_minus_b], colors, labels):
plt.arrow(0, 0, vec[0], vec[1], head_width=0.1, head_length=0.15, fc=color, ec=color)
plt.text(vec[0]+0.1, vec[1]+0.1, label)
# 设置轴标签和标题
plt.xlabel('X')
plt.ylabel('Y')
# 显示网格线
plt.grid(True)
# 调整坐标轴范围
plt.xlim(-4, 4)
plt.ylim(-4, 4)
# 显示图形
plt.show()