mickkk
mickkk

Reputation: 1192

Vector field not displaying correctly with matplotlib

I'm trying to plot a vector field with matplotlib, however it doesn't plot correctly and I cannot figure out what I'm doing wrong.

The vector field to be plotted is the magnetic field of an infinitely long straight wire at a fixed height. What I should get is this:

enter image description here

I know that the equation for the vector field (in cylindrical coordinates) is:

B(r) = (u0/2*pi)*(i/r)

where: u0 is a constant (positive), i is the current in the wire, r is the distance from the wire (the z axis).

Here is the picture I get by using the code below: enter image description here As you can see, aside from the problem with the center of the wire, the vectors in the left half are directed in the wrong direction. Also, is there a function to plot the field in 3d? such as quiver3 in matlab? Thanks

x,y = np.meshgrid(x,y)

def E(x,y):
    i = 3
    mu = 2
    mag = (mu/(2*np.pi))*(i/np.sqrt((x)**2+(y)**2))
    ey = mag * (np.cos(np.arctan(y/x)))
    ex = mag * (-np.sin(np.arctan(y/x)))
    return ex,ey

ex,ey = E(x,y)
plt.quiver(x,y,ex,ey,pivot='middle',color='r',headwidth=4,headlength=6)
plt.show()

Upvotes: 1

Views: 1236

Answers (1)

wflynny
wflynny

Reputation: 18521

  1. The long arrows at the core are due to the magnetic field blowing up very close to the wire. Either remove/mask x,y values in your grid which correspond to r=sqrt(x**2 + y**2) < r_min for some r_min such that those big arrows are removed, or increase the spacing of your mesh grid so those big arrows have some room to breathe.

  2. The wrong arrow directions for x<0 are due to you using arctan instead of arctan2 which is specifically designed for use in 4 quadrants (measured from the +x axis).

  3. There is indeed a 3D quiver. To get started with that, you can do


from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

X, Y, Z = #3D meshgrid of positions
U, V, W = #3D meshgrid of directions

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.quiver(X, Y, Z, U, V, W, **kwargs)

Upvotes: 3

Related Questions