鱼C论坛

 找回密码
 立即注册
查看: 6|回复: 1

[作品展示] 可视化向量运算with numpy & matplotlib

[复制链接]
发表于 前天 14:01 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
import numpy as n
import matplotlib.pyplot as m

vec_a = n.array([1,1])
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[0],vec_a[1],
        angles = 'xy',scale_units = 'xy',
        scale = 1,color = 'red',label = 'a')

m.quiver(0,0,vec_b[0],vec_b[1],
        angles = 'xy',scale_units = 'xy',
        scale = 1,color = 'blue',label = 'b')

m.quiver(0,0,vec_sum[0],vec_sum[1],
        angles = 'xy',scale_units = 'xy',
        scale = 1,color = 'lime',label = 'a+b')

m.quiver(0,0,vec_dif[0],vec_dif[1],
        angles = 'xy',scale_units = 'xy',
        scale = 1,color = 'violet',label = 'a-b')

m.quiver(0,0,vec_tim[0],vec_tim[1],
        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()
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 前天 14:02 | 显示全部楼层
问题主要出在vec_avec_b没有给具体数值,n.array()会报错;另外quiver的用法不太对,前两个参数是起点坐标,后两个参数是向量的UV分量,不能直接把整个向量传进去。

可以先改成这样:


  1. import numpy as np
  2. import matplotlib.pyplot as plt

  3. vec_a = np.array([1, 2])
  4. vec_b = np.array([2, 1])

  5. vec_sum = vec_a + vec_b
  6. vec_dif = vec_a - vec_b
  7. vec_tim = vec_a * 0.5

  8. print(vec_a)
  9. print(vec_b)
  10. print(vec_sum)
  11. print(vec_dif)

  12. plt.figure(figsize=(5, 5))

  13. plt.quiver(0, 0, vec_a[0], vec_a[1],
  14.            angles='xy', scale_units='xy', scale=1,
  15.            color='red', label='a')

  16. plt.quiver(0, 0, vec_b[0], vec_b[1],
  17.            angles='xy', scale_units='xy', scale=1,
  18.            color='blue', label='b')

  19. plt.quiver(0, 0, vec_sum[0], vec_sum[1],
  20.            angles='xy', scale_units='xy', scale=1,
  21.            color='lime', label='a+b')

  22. plt.quiver(0, 0, vec_dif[0], vec_dif[1],
  23.            angles='xy', scale_units='xy', scale=1,
  24.            color='violet', label='a-b')

  25. plt.quiver(0, 0, vec_tim[0], vec_tim[1],
  26.            angles='xy', scale_units='xy', scale=1,
  27.            color='yellow', label='0.5a')

  28. plt.title('Vector Samples')
  29. plt.xticks(np.arange(-2, 3, 1))
  30. plt.yticks(np.arange(0, 4, 1))
  31. plt.legend()
  32. plt.show()
复制代码


记得先调用plt.figure再画图,不然画面尺寸设置不生效。这样就能正确显示向量了。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-8-20 23:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表