pythonsympymayavimayavi.mlab

Is it possible to plot implicit 3d equation using sympy?


Is there a way to plot a 3 variable implicit equation using sympy. Going by docs it has only support for implicit 2d plots. Or are there any other options for plotting a 3d plot using python where the equation can be an input from user


Solution

  • I am turning my comment into an answer. I suggest to use mayavi and contour3d for this task. You can always rewrite your implicit function to be f(x,y,z)=0. For a sphere we have x^2 + y^2 + z^2 = r^2, that can be rewritten as f(x,y,z) = x^2 + y^2 + z^2 - r^2 = 0.

    Below, some examples

    import numpy as np
    from mayavi import mlab
    
    mlab.clf()
    x, y, z = np.mgrid[-3:3:50j, -3:3:50j, -3:3:50j]
    
    # Plot a sphere of radius 1
    values = x*x + y*y + z*z - np.sqrt(3)
    mlab.contour3d(x, y, z, values, contours=[0])
    mlab.axes()
    
    # Plot a torus
    R = 2
    r = 1
    values = (R - np.sqrt(x**2 + y**2))**2 + z**2 - r**2
    mlab.figure()
    mlab.contour3d(x, y, z, values, contours=[0])
    mlab.axes()
    
    # Plot a Scherk's second surface
    x, y, z = np.mgrid[-4:4:100j, -4:4:100j, -8:8:100j]
    values = np.sin(z) - np.sinh(x)*np.sinh(y)
    mlab.figure()
    mlab.contour3d(x, y, z, values, contours=[0])
    mlab.axes()
    mlab.show()
    

    That gives as results

    Sphere: Sphere plotted with Mayavi

    Torus: Torus plotted with Mayavi

    Scherk's second surface: Scherk's second surface plotted with Mayavi