fosho
fosho

Reputation: 1676

How to plot a cylinder with non-constant radius

I have written code to generate a cylinder with a constant fixed radius:

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from math import sin, cos, pi

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

theta = np.linspace(-2*pi,2*pi, 600)
Z = np.linspace(0,1,700)

Z,theta = np.meshgrid(Z, theta)

R = 0.1
X = (R*np.cos(theta))
Y = (R*np.sin(theta))

ax.plot_surface(X,Y,Z,linewidth = 0,facecolor = 'r', shade = True, alpha = 0.6)
plt.show()

How can I change this so that the cylinder radius can vary. For example the radius starts at 0.1 at the one end of the cylinder and each successive 'circle' drawn has a radius 0.01 more than before? In other words, I want to 'connect' circles with different radii together to form a cylinder with inconstant radius.

Upvotes: 3

Views: 391

Answers (1)

Szabolcs Dombi
Szabolcs Dombi

Reputation: 5783

Changed R = np.linspace(0,1,700)

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from math import sin, cos, pi

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

theta = np.linspace(-2*pi,2*pi, 600)
Z = np.linspace(0,1,700)

Z,theta = np.meshgrid(Z, theta)

R = np.linspace(0,1,700)
X = (R*np.cos(theta))
Y = (R*np.sin(theta))

ax.plot_surface(X,Y,Z,linewidth = 0,facecolor = 'r', shade = True, alpha = 0.6)
plt.show()

You can also try a function like R = np.sin(np.linspace(0,1,700) * 4) + 1

Upvotes: 3

Related Questions