How to produce a revolution of a 2D plot with matplotlib in Python

Question:

I have created a 2D plot using matplotlib in Python, an example being this one: 2D plot of some points
It has been produced using 2 lists:

import matplotlib.pyplot as plt
import numpy as np

plt.plot(X, Y) #X and Y are lists, containing the x and y coordinates of points respectively
plt.show()

Now I want to create a revolution of that plot around the Y-axis, and visualizing it in a way that the Y-axis is vertical. How can that be done using matplotlib?

Asked By: Ivalin

||

Answers:

If you have a curve defined as a collection of x and y points in two 1D arrays and you want to revolve them about the y axis you simply need to construct 2D arrays to satisfy matplotlib’s Axes3D.plot_surface by taking the outer products, using np.outer(), of x with np.cos(theta) and np.sin(theta) for theta in [0, 2π]. This will give you a collection of cartesian points in xy space, which will represent the circles created by revolving each original point about the z axis. Constructing the z array is a bit tricky because of the shape expected by plot_surface().

Here is a complete example which demonstrates this method and compares it with the original 2D plot

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

n = 100

fig = plt.figure(figsize=(12,6))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122,projection='3d')
y = np.linspace(np.pi/8, np.pi*4/5, n)
x = np.sin(y)
t = np.linspace(0, np.pi*2, n)

xn = np.outer(x, np.cos(t))
yn = np.outer(x, np.sin(t))
zn = np.zeros_like(xn)

for i in range(len(x)):
    zn[i:i+1,:] = np.full_like(zn[0,:], y[i])

ax1.plot(x, y)
ax2.plot_surface(xn, yn, zn)
plt.show()

enter image description here

Answered By: William Miller
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.