Visualizing the Magnetic Field in Python

A Guide to Using Matplotlib with the Biot-Savart Law
Photo by Dan Cristian Pădureț on Unsplash

In this article, we will discuss how to visualize the magnetic field of a current using the Biot-Savart law. We will also provide Python code examples to illustrate how to generate magnetic field plots for different current configurations.

The Biot-Savart Law

The Biot-Savart law describes the magnetic field created by a current-carrying wire. It states that the magnetic field at a point in space due to a small segment of wire carrying a current is directly proportional to the current and the length of the segment, and inversely proportional to the distance between the segment and the point.

The Biot-Savart law can be expressed mathematically as:

where B⃗is the magnetic field vector at a point r, μ₀ is the permeability of free space, I is the current in the wire, dl⃗ is an infinitesimal length element of the wire, r’ is the vector from the length element to the point r, and the integral is taken over the entire wire C.

Using the Biot-Savart law, we can calculate the magnetic field at any point in space due to a current-carrying wire. In the case of a straight wire, the magnetic field is calculated using the formula:

where 𝐼 is the current in the wire, 𝑟 is the distance from the wire to the point 𝑟⃗, and 𝑧̂ is the unit vector pointing along the wire (the z-axis, here).

Plotting the Vector Fields

To visualize the magnetic field, we can use Python and the Matplotlib library to create plots of the field lines. Here’s an example code for a straight wire:

import numpy as np
import matplotlib.pyplot as plt

# Define the current strength and location
I = 1.0  # current strength
x_c = 0.0  # current x-coordinate
y_c = 0.0  # current y-coordinate

# Define the mesh grid of points
x, y = np.meshgrid(np.linspace(-2, 2, 200), np.linspace(-2, 2, 200))

# Define the magnetic field components due to the magnet
r = np.sqrt((x-x_c)**2 + (y-y_c)**2)
B_x = I * (y-y_c) / r**3
B_y = -I * (x-x_c) / r**3

# Plot the magnetic field lines
fig, ax = plt.subplots(figsize=(8, 8))
ax.streamplot(x, y, B_x, B_y, color='blue', linewidth=1, density=1, arrowstyle='->')

# Add the wire to the plot
circle = plt.Circle((x_c, y_c), 0.1, color='red')
ax.add_artist(circle)

# Set the plot limits and axis labels
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
ax.set_xlabel('x')
ax.set_ylabel('y')

# Show the plot
plt.show()

This code defines the current strength and location, as well as a mesh grid of points where the magnetic field will be calculated. It then calculates the magnetic field components due to the wire, and plots the field lines using the streamplot function. Finally, it adds a red circle to represent the wire and sets the plot limits and axis labels.

We can see that the field lines are circular around the wire.

We can also visualize the magnetic field in 3D using the quiver function from Matplotlib:

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

# Define the magnet strength and location
I = 1.0  # current strength
x_c = 0.0  # current x-coordinate
y_c = 0.0  # current y-coordinate


# Define the mesh grid of points
x, y, z = np.meshgrid(np.linspace(-2, 2, 20),
                      np.linspace(-2, 2, 20),
                      [0])

# Define the magnetic field components due to the current
r = np.sqrt((x-x_c)**2 + (y-y_c)**2 + (z)**2)
B_x = I * (y-y_c) / r**3
B_y = -I * (x-x_c) / r**3
B_z = np.zeros_like(r)

# Create the figure and axes
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111, projection='3d')

# Create the quiver plot of the magnetic field
ax.quiver(x, y, z, B_x, B_y, B_z, length=0.2, normalize=True)

# Plot the wire carrying the current
z_wire = np.linspace(-2, 2, 50)
x_wire = np.zeros_like(z_wire)
y_wire = np.zeros_like(z_wire)
ax.plot(x_wire, y_wire, z_wire, lw=3, color='red')


# Set the plot limits and axis labels
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
ax.set_zlim(-2, 2)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

# Show the plot
plt.show()

This code defines the current strength and location, as well as a mesh grid of points where the magnetic field will be calculated. It then calculates the magnetic field components due to the wire, and creates a 3D plot of the field using the quiver function. Finally, it adds a red wire to represent the current-carrying wire and sets the plot limits and axis labels.

Finally, let’s use the Biot-Savart law to visualize the magnetic field due to multiple current-carrying wires. Here’s an example code for two parallel wires. I have put the plotting stuff into a function so that I can plot different cases by a single function call.

import numpy as np
import matplotlib.pyplot as plt

def plot_parallel_wires(I_1, x_c1, y_c1, I_2, x_c2, y_c2):
    # Define the mesh grid of points
    x, y = np.meshgrid(np.linspace(-2, 2, 200), np.linspace(-2, 2, 200))

    # Define the magnetic field components due to the currents
    r1 = np.sqrt((x-x_c1)**2 + (y-y_c1)**2)
    B_x1 = I_1 * (y-y_c1) / r1**3
    B_y1 = -I_1 * (x-x_c1) / r1**3

    r2 = np.sqrt((x-x_c2)**2 + (y-y_c2)**2)
    B_x2 = I_2 * (y-y_c2) / r2**3
    B_y2 = -I_2 * (x-x_c2) / r2**3

    B_x = B_x1 + B_x2
    B_y = B_y1 + B_y2

    # Plot the magnetic field lines
    fig, ax = plt.subplots(figsize=(8, 8))
    ax.streamplot(x, y, B_x, B_y, color='blue', linewidth=1, density=1, arrowstyle='->')

    # Add the wires
    circle = plt.Circle((x_c1, y_c1), 0.1, color='red')
    ax.add_artist(circle)
    circle = plt.Circle((x_c2, y_c2), 0.1, color='red')
    ax.add_artist(circle)

    # Set the plot limits and axis labels
    ax.set_xlim(-2, 2)
    ax.set_ylim(-2, 2)
    ax.set_xlabel('x')
    ax.set_ylabel('y')

    # Show the plot
    plt.show()

For two parallel wires with current in the same direction, we get

plot_parallel_wires(1.0, -1.0, 0.0, 1.0, 1.0, 0.0)

And for two wires with current in opposite directions, we get:

plot_parallel_wires(1.0, -1.0, 0.0, -1.0, 1.0, 0.0)

The latter plot corresponds to the field lines of a ring current.

In conclusion, Matplotlib provides powerful tools for visualizing magnetic fields, or vector fields in general. With Matplotlib, we can create visualizations of magnetic field lines and streamlines, and add current-carrying wires as visual elements. These visualizations can help us understand complex electromagnetic phenomena, and can be used in physics, engineering, and many other fields.