Search code examples
python-3.xmatplotlibplotcalculus

How can we plot solids of revolution in python 3 (with matplotlib)?


I was a Scilab user, but I am changing to python (because I need Symbolic analys also), now I am new Python user, how to plot a solid of revolution?


Solution

  • Matplotlib plots 3D meshes. With that you can plot a solid of revolution. You have several examples here. One such example is this:

    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    import matplotlib.pyplot as plt
    import numpy as np
    
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    X = np.arange(-5, 5, 0.25)
    Y = np.arange(-5, 5, 0.25)
    X, Y = np.meshgrid(X, Y)
    R = np.sqrt(X**2 + Y**2)
    Z = np.sin(R)
    surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False)
    ax.set_zlim(-1.01, 1.01)
    
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    
    fig.colorbar(surf, shrink=0.5, aspect=5)
    
    plt.show()
    

    If you want something more direct you might want to try using pycsg, pythonOCC framework or sympy.

    The last resource is a bit outside Python. You can use Sage (uses Python syntax) to do Solids of Revolution.