Untitled
unknown
python
a year ago
1.7 kB
10
Indexable
import numpy as np
import matplotlib.pyplot as plt
# Function to plot electric field lines
def plot_field_lines(q, pos, num_lines, ax, label):
# Create a grid
x = np.linspace(-5, 5, 20)
y = np.linspace(-5, 5, 20)
X, Y = np.meshgrid(x, y)
# Calculate the electric field components
r = np.sqrt((X - pos[0])**2 + (Y - pos[1])**2)
Ex = (q * (X - pos[0])) / r**3
Ey = (q * (Y - pos[1])) / r**3
# Normalize the field lines
E_magnitude = np.sqrt(Ex**2 + Ey**2)
Ex_normalized = Ex / E_magnitude
Ey_normalized = Ey / E_magnitude
# Plot the field lines
for i in range(num_lines):
start_x = pos[0] + 0.1 * np.cos(i * (2 * np.pi / num_lines))
start_y = pos[1] + 0.1 * np.sin(i * (2 * np.pi / num_lines))
ax.quiver(start_x, start_y, Ex_normalized[start_y, start_x] * 0.5, Ey_normalized[start_y, start_x] * 0.5,
angles='xy', scale_units='xy', scale=1, color='b')
# Mark the charge position
ax.scatter(*pos, color='red', s=100)
ax.text(pos[0], pos[1] + 0.3, label, fontsize=12, ha='center')
# Create figure
fig, axs = plt.subplots(1, 2, figsize=(12, 6))
# Plot for +2q
plot_field_lines(q=2, pos=(1, 0), num_lines=8, ax=axs[0], label='+2q')
# Plot for -3q
plot_field_lines(q=-3, pos=(-1, 0), num_lines=12, ax=axs[1], label='-3q')
# Set limits and labels
for ax in axs:
ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)
ax.set_aspect('equal')
ax.axhline(0, color='black', lw=0.5, ls='--')
ax.axvline(0, color='black', lw=0.5, ls='--')
ax.set_title('Electric Field Lines')
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
plt.tight_layout()
# Save the figure
plt.savefig('electric_field_lines.png', dpi=300)
plt.show()
Editor is loading...
Leave a Comment