theQman
theQman

Reputation: 1780

How to get unit vectors using `quiver()` in matplotlib?

I'm trying to wrap my head around the quiver function to plot vector fields. Here's a test case:

import numpy as np
import matplotlib.pyplot as plt
X, Y = np.mgrid[1:1.5:0.5, 1:1.5:0.5]
print(X)
print(Y)
u = np.ones_like(X)
v = np.zeros_like(Y)
plt.quiver(X,Y, u, v)
plt.axis([0, 3, 0, 3], units='xy', scale=1.)
plt.show()

I am trying to get a vector of length 1, point from (1,0) to (2,0), but here is what I get:

enter image description here

I have tried adding the scale='xy' option, but the behaviour doesn't change. So how does this work?

Upvotes: 1

Views: 2066

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339765

First funny mistake is that you put the quiver arguments to the axis call. ;-)

Next, looking at the documentation, it says

If scale_units is ‘x’ then the vector will be 0.5 x-axis units. To plot vectors in the x-y plane, with u and v having the same units as x and y, use angles='xy', scale_units='xy', scale=1.

So let's do as the documentation tells us,

import numpy as np
import matplotlib.pyplot as plt
X, Y = np.mgrid[1:1.5:0.5, 1:1.5:0.5]

u = np.ones_like(X)
v = np.zeros_like(Y)
plt.quiver(X,Y, u, v, units='xy', angles='xy', scale_units='xy', scale=1.)
plt.axis([0, 3, 0, 3])
plt.show()

and indeed we get a one unit long arrow:

enter image description here

Upvotes: 2

Related Questions