0

I am writing code to plot spheres. I am generating random points using a separate function and I would like to add these as spheres to the same graph. For the moment, separate graphs are created for each sphere. The code is shown below. Disk here is a list of the form [x, y, z]. Also, is it possible to make the length of the x, y, and z axes equal? Many thanks.

def plot_disks2(disk, radius, c, ax=None):
    fig = plt.figure(figsize=(12,12), dpi=300)
    ax = fig.add_subplot(111, projection='3d')

    u = np.linspace(0, 2 * np.pi, 100)
    v = np.linspace(0, np.pi, 100)

    x = radius * np.outer(np.cos(u), np.sin(v))
    y = radius * np.outer(np.sin(u), np.sin(v))
    z = radius * np.outer(np.ones(np.size(u)), np.cos(v))


    ax.plot_surface(x+disk[0], y+disk[1], z+disk[2],  rstride=4, cstride=4, color=c, linewidth=0, alpha=0.5)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
Hello
  • 97
  • 1
  • 5

1 Answers1

0

In brief, is recommendable that you use a function to generate data and other one for plotting, as follows:

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

def disks2(disk, radius):
    u = np.linspace(0, 2 * np.pi, 100)
    v = np.linspace(0, np.pi, 100)
    x = radius * np.outer(np.cos(u), np.sin(v))
    y = radius * np.outer(np.sin(u), np.sin(v))
    z = radius * np.outer(np.ones(np.size(u)), np.cos(v))
    return x+disk[0],y+disk[1],z+disk[2]

def plotting_spheres(data, colors):
    fig = plt.figure(figsize=(12,12), dpi=300)
    ax = fig.add_subplot(111, projection='3d')
    for k,sph in enumerate(data):
        x, y, z = sph[0], sph[1], sph[2]
        ax.plot_surface(x, y, z,  rstride=4, cstride=4, 
                        color=colors[k], linewidth=0, alpha=0.5)
    ax.set_aspect("equal")
    plt.show()

N = 5 # spheres
points = np.random.randint(1,10,(N,3))
rs = np.random.random((N,1))
colors = ("r","g","b","y","m")

data = [disks2(points[k,:], rs[k]) for k in range(N)]
plotting_spheres(data, colors)

For axes aspect can you use the set_aspect method.