首页 > 解决方案 > 以矢量图的形式绘制一组向量

问题描述

我在笛卡尔网格上有一组 100 个向量,需要在 python 的矢量图中表示。这些向量已使用列表存储。

grid = [ [ [v1x,v1y] , [v2x,v2y] , ..., [v10x,v10y] ],
         [ [v11x,v11y] , [v12x,v12y] , ..., [v20x,v20y] ],  
         [ [v21x,v21y] , [v22x,v22y] , ..., [v30x,v30y] ],
         ...
         [ [v91x,v92y] , [v93x,v94y] , ..., [v100x,v100y] ] ]

这个多维列表包含有关每个向量以及位置的信息。要访问随机位置的任何向量,以下操作必须为我们提供网格上坐标 (i,j) 处的向量:

grid[i][j]

例如,声明:

grid[2][4]

会给我们坐标 (2,4) 处的向量:

[v24x,v24y]

如何将此信息表示为矢量图?

标签: pythonpython-3.xmatplotlibvectorgraph

解决方案


这是一种方法,将列表列表的 3d 列表转换为ndarray,然后将其切片以选择每个向量的 u(x 方向)分量和每个向量的 v(y 方向)分量。然后使用注意进行绘图matplotlib.pyplot.quiver() :为简单起见,我开始将向量编号为 0, 0 而不是 1, 1 在您的初始问题中使用

import numpy as np
import matplotlib.pyplot as plt

grid = [ 
        [ [1, 5] , [-3, 0] , [2, 4], [-3, 1] ],
        [ [2, 2] , [-1, -2] , [0, 1], [0, 0] ],  
        [ [3, 1] , [4, 2] , [2, 1], [4, 2] ],
]

grid = np.array(grid)

u = grid[:,:,0]    # slice x direction component into u array
v = grid[:,:,1]    # slice y direction component into v array

plt.quiver(u, v)   # plot it!
plt.show()

# if u and v are too dense we could subsample with another slice

u = u[::2, ::2]    # pick out every other vector in the x dimension
v = v[::2, ::2]    # pick out every other vector in the y dimension

plt.quiver(u, v)   # plot it again!
plt.show()

在此处输入图像描述


推荐阅读