Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Random 3-D Shapes in Python

How can I use Python to generate a bunch of spheres and ellipses in one plot? Ideally it would just entail setting the endpoints (or radii/axes) of each object and a color, like how you can easily generate rectangles/circles using endpoints.

I was imagining using something like matplotlib's 3-D module, where you can rotate & play with the plot once it's outputted. I'm open to using other libraries though!

I could possibly plot the equations as surfaces by manipulating & graphing a bunch of ellipsoid equations, but is there an easier solution?

like image 416
kennysong Avatar asked Jun 14 '26 15:06

kennysong


2 Answers

VPython might be the quickest path to getting some spheres and ellipsoids on the screen. Also, VPython is much more interactive than matplotlib (in the sense that you can rotate, zoom, etc), and it's very easy to get started. In the end, it depends on what you're looking for. There are lots of ways to get spheres and ellipsoids on the screen.

from visual import *
myell = ellipsoid(pos=(x0,y0,z0), length=L, height=H, width=W) 

enter image description here

ball = sphere(pos=(1,2,1), radius=0.5)

enter image description here

like image 69
tom10 Avatar answered Jun 17 '26 06:06

tom10


Were you looking for functionality that isn't included in matplotlib's mpl_toolkits.mplot3d module? From the 3D Surface demo:

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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

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

x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b')

plt.show()

I don't see any reason why you couldn't define another shape in the same field:

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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

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

x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))
x1 = 7 + 10 * np.outer(np.cos(u), np.sin(v))
y1 = 7 + 10 * np.outer(np.sin(u), np.sin(v))
z1 = 7 + 10 * np.outer(np.ones(np.size(u)), np.cos(v))

ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b')
ax.plot_surface(x1, y1, z1, rstride=4, cstride=4, cmap=cm.coolwarm)

plt.show()
like image 27
MattDMo Avatar answered Jun 17 '26 06:06

MattDMo