如何用Python Matplotlib封闭半圆柱体的曲面?

xxls0lw8  于 2023-01-26  发布在  Python
关注(0)|答案(1)|浏览(185)

我有这个半圆柱图,但是它在表面上不是封闭的,怎么让它封闭呢?
可以从顶点和边绘制圆柱体吗?2个顶点变成一个弧?

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
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, 1*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)

# Annotation
ax.set_title("Half Cylinder"))
plt.show()

5rgfhyps

5rgfhyps1#

如果您可以接受手动绘制每个平面以包围形状,则代码如下:

def data_for_horizontal_plane(center_x, center_y, radius, height_z):
    # define the horizontal surface using polar coordinates
    _radius = np.linspace(0, radius)
    _theta = np.linspace(0, np.pi)
    R, T = np.meshgrid(_radius, _theta)
    # convert polar to cartesian coordinates and add translation
    X = R*np.cos(T) + center_x
    Y = R*np.sin(T) + center_y
    Z = np.zeros(X.shape) + height_z
    return X, Y, Z

def data_for_vertical_plane(center_x, center_y, radius, height_z):
    # define the vertical rectangle on the X-Z plane
    x = np.linspace(center_x - radius, center_x + radius)
    z = np.linspace(0, height_z)
    X, Z = np.meshgrid(x, z)
    Y = np.zeros(X.shape) + center_y
    return X, Y, Z

X, Y, Z = data_for_horizontal_plane(0.2, 0.2, 0.05, 0.0)
ax.plot_surface(X, Y, Z, alpha=0.5)
X, Y, Z = data_for_horizontal_plane(0.2, 0.2, 0.05, 0.1)
ax.plot_surface(X, Y, Z, alpha=0.5)
X, Y, Z = data_for_vertical_plane(0.2, 0.2, 0.05, 0.1)
ax.plot_surface(X, Y, Z, alpha=0.5)

相关问题