Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a 3D revolution plot in matplotlib?

Suppose you have a 2D curve, given by e.g.:

from matplotlib import pylab
t = numpy.linspace(-1, 1, 21)
z = -t**2
pylab.plot(t, z)

which produces

http://i.imgur.com/feQzk.png

I would like to perform a revolution to achieve a 3d plot (see http://reference.wolfram.com/mathematica/ref/RevolutionPlot3D.html). Plotting a 3d surface is not the problem, but it does not produce the result I'm expecting:

http://i.imgur.com/ljXHQ.png

How can I perform a rotation of this blue curve in the 3d plot ?

like image 478
mmgp Avatar asked Nov 17 '12 16:11

mmgp


1 Answers

Your plot on your figure seems to use cartesian grid. There is some examples on the matplotlib website of 3D cylindrical functions like Z = f(R) (here: http://matplotlib.org/examples/mplot3d/surface3d_radial_demo.html). Is that what you looking for ? Below is what I get with your function Z = -R**2 :Plot of Z = -R**2 function

And to add cut off to your function, use the following example: (matplotlib 1.2.0 required)

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
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)

Z = -(abs(X) + abs(Y))

## 1) Initial surface
# Flatten mesh arrays, necessary for plot_trisurf function
X = X.flatten()
Y = Y.flatten()
Z = Z.flatten()

# Plot initial 3D surface with triangles (more flexible than quad)
#surfi = ax.plot_trisurf(X, Y, Z, cmap=cm.jet, linewidth=0.2)

## 2) Cut off
# Get desired values indexes
cut_idx = np.where(Z > -5)

# Apply the "cut off"
Xc = X[cut_idx]
Yc = Y[cut_idx]
Zc = Z[cut_idx]

# Plot the new surface (it would be impossible with quad grid)
surfc = ax.plot_trisurf(Xc, Yc, Zc, cmap=cm.jet, linewidth=0.2)

# You can force limit if you want to compare both graphs...
ax.set_xlim(-5,5)
ax.set_ylim(-5,5)
ax.set_zlim(-10,0)

plt.show()

Result for surfi:

surfi

and surfc:

surfc

like image 168
Remy F Avatar answered Sep 18 '22 13:09

Remy F