21

How can we plot 2D math vectors with matplotlib? Does anyone have an example or suggestion about that?

I have a couple of vectors stored as 2D numpy arrays, and I would like to plot them as directed edges.

The vectors to be plotted are constructed as below:

import numpy as np
# a list contains 3 vectors;
# each list is constructed as the tail and the head of the vector
a = np.array([[0, 0, 3, 2], [0, 0, 1, 1], [0, 0, 9, 9]]) 

Edit:

I just added the plot of the final answer of tcaswell for anyone interested in the output and want to plot 2d vectors with matplotlib: enter image description here

4

2 回答 2

36

halex 评论中的建议是正确的,您想使用 quiver ( doc ),但您需要稍微调整一下属性。

import numpy as np
import matplotlib.pyplot as plt

soa = np.array([[0, 0, 3, 2], [0, 0, 1, 1], [0, 0, 9, 9]])
X, Y, U, V = zip(*soa)
plt.figure()
ax = plt.gca()
ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1)
ax.set_xlim([-1, 10])
ax.set_ylim([-1, 10])
plt.draw()
plt.show()
于 2012-09-04T16:13:59.293 回答
0

这很简单。希望这个例子有所帮助。

import matplotlib.pyplot as plt
import numpy as np
x = np.random.normal(10,5,100)
y = 3 + .5*x + np.random.normal(0,1,100)
myvec = np.array([x,y])
plt.plot(myvec[0,],myvec[1,],'ro')
plt.show()

将产生:

在此处输入图像描述

要绘制数组,您可以将它们切成一维向量并绘制它们。我已经阅读了 matplotlib 的所有不同选项的完整文档。但是对于大多数示例,您可以将 numpy 向量视为普通元组。

于 2012-09-04T14:15:21.473 回答