Method to draw a 3D equipotential surface with matplotlib

I have a function, like:

fun=lambda x,y,z: np.exp(-x*x-y*y-z*z)

This function is only dependent on the radius, but could be also function of theta or phi, in spherical coordinates.

Having a range of coordinates x, y, z, I would like to plot a surface for the value V (let’s say 0.75) of the function fun.

Does matplotlib have such a method? Maybe some “contour” 3d…

How does it function?

One can use matplotlib with the S3Dlib third-party package to plot an implicit function.
For your example, the surface evaluated for four different functional values is shown below:

You can play around with different values, just be aware of the domain you are viewing.
The code follows. The lambda expression wasn’t used, but a function that can be described using spherical coordinates.

import numpy as np
import matplotlib.pyplot as plt
import s3dlib.surface as s3d

def implicit_func(xyz):
    r,t,p = s3d.SphericalSurface.coor_convert(xyz)
    f = np.exp(-r)    # Note: could use f = f(r,t,p)
    return f 

fig = plt.figure(figsize=plt.figaspect(1))
rez,dmn,mnmx = 5,2.5,(-2,0,2)
for i, val in enumerate( [0.607, 0.368, 0.223, 0.135] ) :
    ax = fig.add_subplot(221+i, projection='3d', aspect='equal')
    ax.set_title('n = '+str(val),fontweight='bold')
    ax.set(xticks=mnmx,yticks=mnmx,zticks=mnmx)
    surface = s3d.Surface3DCollection.implsurf( implicit_func,rez,dmn,val,color='orange').evert()
    ax.add_collection3d(surface.shade().hilite(.95,direction=[1,-0.7,2],focus=2))
fig.tight_layout(pad=3)
plt.show()

More examples of evaluating an implicit function is shown at: Implicit Surface Examples.
The S3Dlib package also provides methods to construct contours. You might also examine scikit-image as a resource.

1 Like