# How to plot vector fields in Matplotlib

• Python

## Main Question or Discussion Point

Hi, I want to plot the vector field ##\vec F = ye^x \hat i + (x^2 + e^x) \hat j + z^2e^z \hat k##

The code I have tried:

Python:
# The components of the vector field

F_x = y*e**x

F_y = x**2 + e**x

F_z = z**2*e**z

# The grid

xf = np.linspace(-0.15, 2.25, 8)

yf = np.linspace(-0.15, 2.25, 8)

zf = np.linspace(-0.75, 2.50, 8)

X_grid, Y_grid, Z_grid = np.meshgrid(xf, yf, zf)

# The arrows; how to deal with them?

dx = 1

#dy = ...

#dz = ...

# Standardize the arrows; In this way all arrows have the same length.

length = np.sqrt(dx**2 + dy**2 + dz**2)

dx_N = dx/length

dy_N = dy/length

dz_N = dz/length

#how to involve numpy in the process??

# Drawing the figure

fig, ax = plt.subplots(1, 1)

ax.quiver(X_grid, Y_grid, Z_grid, dx_N, dy_N, dz_N, dy, dz, cmap=plt.get_cmap('gnuplot2'))

plt.show()
I am stuck in how to make sure that the arrows are not too long (I know I have to use length, but how?).

I attach next an example I am following of a plot of another vector field (##V = \hat i + xy \hat j##).

Python:
# The function to be applied
def rightmember(x, y):
return x*y

# The grid
x = np.linspace(-3, 3, 25)
y = np.linspace(-3, 3, 25)
X_grid, Y_grid = np.meshgrid(x, y)

# The arrows
dx = 1
dy = rightmember(X_grid, Y_grid)

# Standardize the arrows; In this way all arrows have the same length.
length = np.sqrt(dx**2 + dy**2)
dx_N = dx/length
dy_N = dy/length

# Drawing the figure
fig, ax = plt.subplots(1, 1)
ax.quiver(X_grid, Y_grid, dx_N, dy_N, dy, cmap=plt.get_cmap('gnuplot2'))

plt.show()
I have posted the same question on SO: https://stackoverflow.com/questions/55759028/how-to-plot-a-vector-field-using-numpy

Related Programming and Computer Science News on Phys.org
I am not too knowledgeable about vector plots in Python, however, a quick google search yielded: https://matplotlib.org/gallery/mplot3d/quiver3d.html
and they seem to have set:
- normalize = True
- length = 0.1

in the ax.quiver() in line 21...

Hope that is of some use.

• JD_PM