Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add cylinder to plot

I would like to add a transparent cylinder to my 3D scatter plot. How can I do it?

This is the code I am using to make the plot:

fig = plt.figure(2, figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')

ax.scatter(X, Y, Z, c=Z,cmap=plt.cm.Paired)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
plt.xticks()
like image 619
albus_c Avatar asked Nov 18 '14 07:11

albus_c


People also ask

How to plot cylinders in matlab?

To draw the cylinder, pass X , Y , and Z to the surf or mesh function. [X,Y,Z] = cylinder( r ) returns the x-, y-, and z- coordinates of a cylinder with the specified profile curve, r , and 20 equally spaced points around its circumference.

How do you increase the height of a plot?

The best time to increase plant height is at or before first bract color. A single spray application of Fresco or Fascination at 3 ppm increases plant height by 1 to 2 inches. Based on preliminary research, similar rates of Fresco (3 to 5 ppm) is suggested when used as a drench.


2 Answers

Today I have to do the same thing in my project about adding a transparent cylinder in the result. This is the code I get finally. So I share it with you guys just for learning

import numpy as np

def data_for_cylinder_along_z(center_x,center_y,radius,height_z):
    z = np.linspace(0, height_z, 50)
    theta = np.linspace(0, 2*np.pi, 50)
    theta_grid, z_grid=np.meshgrid(theta, z)
    x_grid = radius*np.cos(theta_grid) + center_x
    y_grid = radius*np.sin(theta_grid) + center_y
    return x_grid,y_grid,z_grid

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

Xc,Yc,Zc = data_for_cylinder_along_z(0.2,0.2,0.05,0.1)
ax.plot_surface(Xc, Yc, Zc, alpha=0.5)

plt.show()

And you will get this beautiful figure. enter image description here

like image 81
Yong Yang Avatar answered Oct 21 '22 21:10

Yong Yang


One possible method is to use the plot_surface. Adapting the solution given in this blog post then have

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

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

# Scatter graph
N = 100
X = np.random.uniform(-1, 1, N)
Y = np.random.uniform(-1, 1, N)
Z = np.random.uniform(-2, 2, N)
ax.scatter(X, Y, Z)

# Cylinder
x=np.linspace(-1, 1, 100)
z=np.linspace(-2, 2, 100)
Xc, Zc=np.meshgrid(x, z)
Yc = np.sqrt(1-Xc**2)

# Draw parameters
rstride = 20
cstride = 10
ax.plot_surface(Xc, Yc, Zc, alpha=0.2, rstride=rstride, cstride=cstride)
ax.plot_surface(Xc, -Yc, Zc, alpha=0.2, rstride=rstride, cstride=cstride)

ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
plt.show()

enter image description here

I've added some minimal configuration of the surface, better can be achieved by consulting the docs.

like image 36
Greg Avatar answered Oct 21 '22 22:10

Greg