You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Numpy实现两个向量求和并通过Matplotlib绘制矢量图

代码调整方案

原代码存在的问题

  • 未导入matplotlib.pyplot库,直接调用plt会触发名称报错
  • plt.quiver()传参逻辑错误,该函数标准输入为(起点X坐标, 起点Y坐标, 向量X分量, 向量Y分量),原参数无法正确渲染向量
  • 缺少坐标轴范围、标签等配置,向量会显示不全也无法区分

可直接运行的修正后代码

import numpy as np
import matplotlib.pyplot as plt

# 定义原始向量
first = np.array([3, 2])
second = np.array([5, 1])
# 执行向量求和
sum_vector = first + second

# 初始化画布
plt.figure(figsize=(6, 3))
# 绘制第一个向量:原点出发,红色
plt.quiver(0, 0, first[0], first[1], angles='xy', scale_units='xy', scale=1, color='r', label='first向量')
# 绘制第二个向量:原点出发,蓝色
plt.quiver(0, 0, second[0], second[1], angles='xy', scale_units='xy', scale=1, color='b', label='second向量')
# 绘制求和结果向量:原点出发,绿色
plt.quiver(0, 0, sum_vector[0], sum_vector[1], angles='xy', scale_units='xy', scale=1, color='g', label='求和结果向量')

# 配置坐标轴
plt.xlim(0, 9)
plt.ylim(0, 4)
plt.xlabel('X轴数值')
plt.ylabel('Y轴数值')
plt.grid(True)
plt.legend()

# 展示图表、打印结果
plt.show()
print("向量求和结果:", sum_vector)

补充说明

代码中quiver的angles='xy'、scale_units='xy'、scale=1三个参数组合使用,是为了保证向量的实际长度和数值大小完全匹配,不会被matplotlib自动缩放。运行代码后会输出求和结果[8 3],同时弹出包含三个向量的可视化图表。

内容的提问来源于stack exchange,提问作者HoesMad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 14:45:02