Search code examples
pythonmatplotlibsurfacematplotlib-3d

Plotting spheres of radius R


How can we make spheres of radius R centered at given coordinates(x,y,z). Like if there are 10 set of coordinates for the centers of the spheres and correspondingly 10 different values of the radii. How can we plot it in python ? Is there any way to do this in python ,like in MATLAB this can be done using surf command. In python how can we achieve this ?


Solution

  • This will solve your problem

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt
    import numpy as np
    
    list_center = [(1,2,3),(-4,-5,6), (5,5,6)]
    list_radius = [1,2,1]
    
    def plt_sphere(list_center, list_radius):
      for c, r in zip(list_center, list_radius):
        ax = fig.add_subplot(projection='3d')
        
        # draw sphere
        u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
        x = r*np.cos(u)*np.sin(v)
        y = r*np.sin(u)*np.sin(v)
        z = r*np.cos(v)
    
        ax.plot_surface(x-c[0], y-c[1], z-c[2], color=np.random.choice(['g','b']), alpha=0.5*np.random.random()+0.5)
    fig = plt.figure()
    plt_sphere(list_center, list_radius) 
    

    surface plot