Skip to content

Instantly share code, notes, and snippets.

@alexlib
Created December 2, 2019 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexlib/bac36d4c0db9f28fb4b4dbe7023b705d to your computer and use it in GitHub Desktop.
Save alexlib/bac36d4c0db9f28fb4b4dbe7023b705d to your computer and use it in GitHub Desktop.
Matplotlib quiver from stackoverflow
from __future__ import division, print_function
import numpy as np
import matplotlib.pyplot as plt
def elec_field(x, y, x_coords=[0], y_coords=[0], charges=[1]):
Ex = np.zeros_like(x)
Ey = np.zeros_like(x)
for x0, y0, q in zip(x_coords, y_coords, charges):
R = np.sqrt((x - x0)**2 + (y - y0)**2) + 1e-6
Ex += q*(x - x0)/R**3
Ey += q*(y - y0)/R**3
return Ex, Ey
y, x = np.mgrid[-3:3:21j, -3:3:21j]
Ex, Ey = elec_field(x, y, x_coords=[-1, 1], y_coords=[0,0],
charges=[1, -1])
Emag = np.sqrt(Ex**2 + Ey**2)
dir_x = Ex/Emag
dir_y = Ey/Emag
plt.figure(figsize=(8, 6))
plt.subplot(221)
plt.quiver(x[::2, ::2], y[::2, ::2], dir_x[::2, ::2], dir_y[::2, ::2],
np.log10(Emag[::2, ::2]), cmap="autumn", scale_units="inches",
scale=5, width=0.015, pivot="mid")
plt.colorbar()
plt.axis("image")
plt.subplot(222)
plt.streamplot(x, y, Ex, Ey, color=np.log10(Emag),cmap="autumn")
plt.colorbar()
plt.axis("image")
plt.subplot(223)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment