在matplotlib/plotly 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()
输出结果: