I am trying to plot potential values as a function of x and y and use this to plot the electric field as a vector field. I am not succeeding in plotting the vector field as it seems that in order to use numpy.gradient
I need to either know function for my data, or have my data in some other form. Currently I have data in the form:
x = [3,3,3...9]
y = [1,2,3...9]
# v is potential as a function of the corresponding x and y values.
v = [0.436744, 0.411724...3.626803]
My code so far simply extracts the data from a file and then plots a contour and contourf plot using matplotlib as follows.
import numpy as np
from matplotlib import cm
import matplotlib.pyplot as plt
contours=plt.tricontour(x, y, v, colors='k',linewidths=2,linestyles='solid')
plt.tricontourf(x, y, v, cmap=cm.hsv)
plt.clabel(contours, inline=1, fontsize=14)
plt.colorbar()
plt.show()
It seems that I should be using np.gradient
coupled with plt.quiver(x, y, E)
where E is the electric field - using the fact that E=-Grad(V)
.
Here is an example of my current output:
I am trying to get it to look something like this:
Please notice the vector field overlaid.
Here the following code was used:
# Contour plot for regular grid
dx = 0.1
dy = 0.1
xr = np.arange(-1, 1, dx)
yr = np.arange(-1, 1, dy)
# Create grid corresponding to xr and yr arrays
xx, yy = np.meshgrid (xr, yr, indexing = 'ij')
zz = xx + yy*yy
gradx, grady = np.gradient (zz, dx, dy)
n = 20
#l = np.array([0.0, 0.5, 1.0, 1.5, 2.0])
plt.contourf(xx, yy, zz, n)
plt.contour(xx, yy, zz, levels = l, colors = 'k', linewidths = 1, linestyles = 'solid')
plt.quiver(xx, yy, gradx , grady)
plt.show()
The difference in the two situations is that in my situation I don't have a known function which can be used to calculate the gradient of the scalar field. In the latter situation the function is known, and thus the gradient can be calculated. I'm not sure how to proceed from here because of this difference.
Thanks in advance for any guidance and help you can provide.