python 用 matplotlib 在 3D 空间中连点成线,绘制立体图形
图形预览:
0、import
import matplotlib as mpl
from matplotlib import cm
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
1、简单的连点成线
# 创建画布
fig = plt.figure(figsize=(12, 8),
facecolor='lightyellow'
)
# 创建 3D 坐标系
ax = fig.gca(fc='whitesmoke',
projection='3d'
)
# 绘制 3D 图形
ax.plot3D(xs=[2, 0, 2, 2, 2, 0, 2], # x 轴坐标
ys=[0, 2, 2, 0, 2, 2, 2], # y 轴坐标
zs=[2, 2, 2, 2, 0, 2, 2], # z 轴坐标
zdir='z', #
c='k', # color
marker='o', # 标记点符号
mfc='r', # marker facecolor
mec='g', # marker edgecolor
ms=10, # size
)
ax.plot(xs=[2, 0, 0, 0, 1, 2, 0, 1, 2],
ys=[0, 0, 2, 0, 1, 2, 0, 1, 2],
zs=[2, 0, 2, 0, 1, 2, 0, 0, 0],
ls=':',
color='grey',
marker='o',
mfc='r',
mec='g'
)
# 设置坐标轴标题和刻度
ax.set(xlabel='X',
ylabel='Y',
zlabel='Z',
xticks=np.arange(0, 4, 0.5),
yticks=np.arange(0, 4, 0.5),
zticks=np.arange(0, 4, 0.5)
)
# 调整视角
ax.view_init(elev=20, # 仰角
azim=40 # 方位角
)
# 显示图形
plt.show()
图形:
2、立方体
# 创建画布
fig = plt.figure(figsize=(12, 8),
facecolor='lightyellow'
)
# 创建 3D 坐标系
ax = fig.gca(fc='whitesmoke',
projection='3d'
)
x = [7, 7, 7, 7, 3, 3, 3, 3]
y = [3, 7, 7, 3, 3, 7, 7, 3]
z = [7, 7, 3, 3, 7, 7, 3, 3]
A, B, C, D, E, F, G, H = zip(x, y, z)
# 绘制 3D 图形
lines_1 = zip(A, B, C, D, A, E, F, G, C, B, F)
ax.plot3D(*lines_1,
zdir='z', #
c='k', # color
marker='o', # 标记点符号
mfc='r', # marker facecolor
mec='g', # marker edgecolor
ms=10, # size
)
lines_2 = zip(D, H, E, G, H)
ax.plot(*lines_2,
ls=':',
color='b',
marker='o',
mfc='r',
mec='g'
)
# 设置坐标轴标题和刻度
ax.set(xlabel='X',
ylabel='Y',
zlabel='Z',
xlim=(0, 9),
ylim=(0, 9),
zlim=(0, 9),
xticks=np.arange(0, 10, 2),
yticks=np.arange(0, 10, 1),
zticks=np.arange(0, 10, 1)
)
# 添加顶点字母标注
for pos in list('abcdefgh'.upper()):
ax.text(*eval(pos),
s=pos,
fontsize=18,
color='darkgreen')
# 调整网格线
ax.grid()
# 调整视角
ax.view_init(elev=15, # 仰角
azim=40 # 方位角
)
# 显示图形
plt.show()
图形:
软件信息:
非学无以广才,非志无以成学。