在matplotlib/plotly 3D图中添加外部对象

0 投票
1 回答
40 浏览
提问于 2025-04-14 17:06

我想知道,怎么才能在 matplotlibplotly 的3D图中添加或绘制3D模型,比如那些矩形框(门)。我找了很久,但一直没找到能让我做到这一点的方法。在这里输入图片描述 如果能把它们作为一个整体来实现,而不是单独的点,那就太好了,这样我可以更好地安排它们的位置,并与现有的图形融合。不过,任何能帮助我实现这个目标的建议,我都非常感激。

1 个回答

1

试着使用这个链接中提到的修改版的 pathpatch_2d_to_3d,可以参考这个回答,比如这样做:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle
# this library contains functions taken from https://stackoverflow.com/a/33213658/3715182
from special_pathpatch_2d_to_3d import pathpatch_2d_to_3d, pathpatch_translate

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

# make some parametric curve
theta = np.linspace(-1 * np.pi, 1 * np.pi, 20)
Z = np.linspace(-1, 1, 20)
r = Z**2 + 1
X = r * np.sin(theta)
Y = r * np.cos(theta)
ax.plot(X, Y, Z, color='blue', marker='o')

# draw 3D patches around all the curve points but the last one
for i, (x, y, z) in enumerate(zip(X[:-1], Y[:-1], Z[:-1])):
    # add a 2D patch at the origin
    p = Circle((0, 0), 0.2, facecolor='none', edgecolor='red')
    ax.add_patch(p)
    # transform it into a 3D patch at the origin, reorienting it to follow the current direction of the curve
    normal = (X[i+1] - x, Y[i+1] - y, Z[i+1] - z)
    pathpatch_2d_to_3d(p, z=0, normal=normal)
    # place the patch at the current curve coordinate
    pathpatch_translate(p, (x, y, z))

fig.tight_layout()
plt.show()

输出结果:

在这里输入图片描述

撰写回答