I’m using numpy 1.6 and matplotlib 1.1.1, trying to generate a velocity field from a scalar field that I have. So far, I’m generating my scalar data as such:
num_samples = 50
dim_x = np.linspace(self.min_x, self.max_x,num_samples)
dim_y = np.linspace(self.min_y, self.max_y,num_samples)
X, Y = np.meshgrid(dim_x, dim_y)
len_x = len(dim_x)
len_y = len(dim_y)
a = np.zeros([len_x, len_y], dtype=float)
for i, y in enumerate(dim_y):
for j, x in enumerate(dim_x):
a[i][j] = x*y # not exactly my function, just an example
Then I get the gradient:
(velx,vely) = np.gradient(a)
From the numpy documentation, velx is the x component and vely is the y component of the vector field. Checking the docs for matplotlib, I use quiver to plot a vector field using arrows. It states that velx and vely are the x component and y component of the vector field:
fig0 = plt.figure()
ax = fig0.add_subplot(111)
Q = ax.quiver(X,Y, velx, vely )
plt.show()
This gives the wrong result for the velocity field:

The only way of the graph looks ok is if I invert the components on quiver:
Q = ax.quiver(X,Y, vely, velx )#WHY???

I’m suspecting that is something like row-or-column ordering, but I can’t figure it out if the output of np.gradient is inverted, or if quiver is inverted. All one dimensional problems are working as expected. Thanks!
EDIT: just to make even more clear how this is inverted, change the function
a[i][j] = x*y
to
a[i][j] = x*x
The gradient should be in the x direction, increasing with increasing x. The results are still wrong: if I use
Q = ax.quiver(X,Y, velx, vely )
I get

and if I invert it
Q = ax.quiver(X,Y, vely, velx )
I get

Maybe there’s a more pythonic (and correct!) way to do it…
I think you’re right, (this is an array ordering issue).
ais built asa[yidx,xidx]but when you take the gradient, you do:velx, vely = np.gradient(a)when you should be doingvely, velx = np.gradient(a). Since the gradient along the 0th axis should give youvely(presumablyd/dy(a) = vely)? — unless I’m missing something (in which case I’ll happily delete this answer).Also note that I think you can build “
a” without the nested lists:which should work for more complicated functions as well…