21
votes

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

2
Do you want to plot a vectorfield with quiver? matplotlib.sourceforge.net/api/… - halex
There's a fairly good collection of examples (with code!) on the project site: matplotlib.sourceforge.net/examples/index.html , including a quiver demo: matplotlib.sourceforge.net/examples/pylab_examples/… - abought
@halex and at abought, thanks for your examples ;-), the thing is that I'd like to plot individual vectors. I added a code to make it clear. - pacodelumberg
There's also the possibility of the arrow plot - Seanny123
beautiful :-)! thanks @Seanny123 - pacodelumberg

2 Answers

36
votes

The suggestion in the comments by halex is correct, you want to use quiver (doc), but you need to tweak the properties a bit.

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()
0
votes

It's pretty straightforward. Hope this example helps.

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()

Will produce:

enter image description here

To plot the arrays you can just slice them up into 1D vectors and plot them. I'd read the full documentation of matplotlib for all the different options. But you can treat a numpy vector as if it were a normal tuple for most of the examples.