
在 matplotlib 的 3d 图中绘制矢量上的箭头
想要将箭头放置在 3d 图形中绘制的特征向量上。
解决方案
创建自定义箭头补丁类
由于 matplotlib 的 fancyarrowpatch 类仅适用于 2d 图形,因此需要创建一个新的箭头补丁类 arrow3d,该类继承自 fancyarrowpatch。覆盖 posa 和 posb 方法,将 3d 坐标投影到 2d,然后将其分配给 posa 和 posb。
修改绘图代码
在绘图代码中,将箭头艺术家添加到包含特征向量的绘图对象中。使用自定义的 arrow3d 类,为每个特征向量绘制一个箭头,从平均位置延伸到特征向量末端。
最终代码
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
class Arrow3D(FancyArrowPatch):
def __init__(self, xs, ys, zs, *args, **kwargs):
FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
FancyArrowPatch.draw(self, renderer)
# 数据生成和特征向量计算
...
# 绘图
fig = plt.figure(figsize=(15,15))
ax = fig.add_subplot(111, projection='3d')
...
for v in eig_vec:
a = Arrow3D([mean_x, v[0]], [mean_y, v[1]],
[mean_z, v[2]], mutation_scale=20,
lw=3, arrowstyle="-|>", color="r")
ax.add_artist(a)
...输出
将看到带箭头的特征向量绘制在 3d 图中。
以上就是如何在 Matplotlib 的 3D 图中绘制矢量上的箭头?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号