将箭头放在 3d 图中的向量上

2024-03-22

I plotted the eigenvectors of some 3D-data and was wondering if there is currently (already) a way to put arrowheads on the lines? Would be awesome if someone has a tip for me. enter image description here

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

####################################################
# This part is just for reference if
# you are interested where the data is
# coming from
# The plot is at the bottom
#####################################################

# Generate some example data
mu_vec1 = np.array([0,0,0])
cov_mat1 = np.array([[1,0,0],[0,1,0],[0,0,1]])
class1_sample = np.random.multivariate_normal(mu_vec1, cov_mat1, 20)

mu_vec2 = np.array([1,1,1])
cov_mat2 = np.array([[1,0,0],[0,1,0],[0,0,1]])
class2_sample = np.random.multivariate_normal(mu_vec2, cov_mat2, 20)

# concatenate data for PCA
samples = np.concatenate((class1_sample, class2_sample), axis=0)

# mean values
mean_x = mean(samples[:,0])
mean_y = mean(samples[:,1])
mean_z = mean(samples[:,2])

#eigenvectors and eigenvalues
eig_val, eig_vec = np.linalg.eig(cov_mat)

################################
#plotting eigenvectors
################################    

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

ax.plot(samples[:,0], samples[:,1], samples[:,2], 'o', markersize=10, color='green', alpha=0.2)
ax.plot([mean_x], [mean_y], [mean_z], 'o', markersize=10, color='red', alpha=0.5)
for v in eig_vec:
    ax.plot([mean_x, v[0]], [mean_y, v[1]], [mean_z, v[2]], color='red', alpha=0.8, lw=3)
ax.set_xlabel('x_values')
ax.set_ylabel('y_values')
ax.set_zlabel('z_values')

plt.title('Eigenvectors')

plt.draw()
plt.show()

要将箭头补丁添加到 3D 绘图中,简单的解决方案是使用FancyArrowPatch类定义于/matplotlib/patches.py。但是,它仅适用于 2D 绘图(在撰写本文时),因为它的posA and posB应该是长度为 2 的元组。

因此我们创建一个新的箭头补丁类,将其命名为Arrow3D,它继承自FancyArrowPatch。我们唯一需要覆盖它的posA and posB。为此,我们发起Arrow3d with posA and posB of (0,0)是。 3D 坐标xs, ys, zs然后使用从 3D 投影到 2Dproj3d.proj_transform(),并将所得的 2D 坐标分配给posA and posB using .set_position()方法,替换(0,0)s。这样我们就可以让 3D 箭头发挥作用。

投影步骤进入.draw方法,它重写了.draw的方法FancyArrowPatch object.

这可能看起来像黑客攻击。但是,那mplot3d目前仅通过提供 3D-2D 投影来提供(再次强调)简单的 3D 绘图功能,并且基本上以 2D 方式进行所有绘图,这不是真正的 3D。

import numpy as np
from numpy import *
from matplotlib import 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)

####################################################
# This part is just for reference if
# you are interested where the data is
# coming from
# The plot is at the bottom
#####################################################

# Generate some example data
mu_vec1 = np.array([0,0,0])
cov_mat1 = np.array([[1,0,0],[0,1,0],[0,0,1]])
class1_sample = np.random.multivariate_normal(mu_vec1, cov_mat1, 20)

mu_vec2 = np.array([1,1,1])
cov_mat2 = np.array([[1,0,0],[0,1,0],[0,0,1]])
class2_sample = np.random.multivariate_normal(mu_vec2, cov_mat2, 20)

实际绘图。请注意,我们只需要更改一行代码,即添加一个新的箭头艺术家:

# concatenate data for PCA
samples = np.concatenate((class1_sample, class2_sample), axis=0)

# mean values
mean_x = mean(samples[:,0])
mean_y = mean(samples[:,1])
mean_z = mean(samples[:,2])

#eigenvectors and eigenvalues
eig_val, eig_vec = np.linalg.eig(cov_mat1)

################################
#plotting eigenvectors
################################    

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

ax.plot(samples[:,0], samples[:,1], samples[:,2], 'o', markersize=10, color='g', alpha=0.2)
ax.plot([mean_x], [mean_y], [mean_z], 'o', markersize=10, color='red', alpha=0.5)
for v in eig_vec:
    #ax.plot([mean_x,v[0]], [mean_y,v[1]], [mean_z,v[2]], color='red', alpha=0.8, lw=3)
    #I will replace this line with:
    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)
ax.set_xlabel('x_values')
ax.set_ylabel('y_values')
ax.set_zlabel('z_values')

plt.title('Eigenvectors')

plt.draw()
plt.show()

请检查这个帖子 https://stackoverflow.com/questions/11140163/python-matplotlib-plotting-a-3d-cube-a-sphere-and-a-vector,这激发了这个问题,以了解更多详细信息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将箭头放在 3d 图中的向量上 的相关文章

  • 如何使用 Python 裁剪图像中的矩形

    谁能给我关于如何裁剪两个矩形框并保存它的建议 我已经尝试过这段代码 但效果不佳 import cv2 import numpy as np Run the code with the image name keep pressing spa
  • 如何让python优雅地失败?

    我只是想知道如何让 python 在所有可能的错误中以用户定义的方式失败 例如 我正在编写一个处理 大 项目列表的程序 并且某些项目可能不符合我定义的格式 如果 python 检测到错误 它目前只会输出一条丑陋的错误消息并停止整个过程 但是
  • 正则表达式,选择最接近的匹配

    假设以下单词序列 BLA text text text text text text BLA text text text text LOOK text text text BLA text text BLA 我想做的是将 BLA 中的文本
  • Pandas 连接问题:列重叠但未指定后缀

    我有以下数据框 print df a mukey DI PI 0 100000 35 14 1 1000005 44 14 2 1000006 44 14 3 1000007 43 13 4 1000008 43 13 print df b
  • Python 的 mysqldb 晦涩文档

    Python 模块 mysqldb 中有许多转义函数 我不理解它们的文档 而且我努力查找它们也没有发现任何结果 gt gt gt print mysql escape doc escape obj dict escape any speci
  • Django 不会以奇怪的错误“AttributeError: 'module' object has no attribute 'getargspec'”启动

    我对 Django 的内部结构有点缺乏经验 所以我现在完全陷入困境 它昨天起作用了 但我不记得我改变过任何重要的东西 当我转身时DEBUG True任何恰好位于列表中第一个的模块上都有堆栈跟踪 Traceback most recent c
  • Python——捕获异常的效率[重复]

    这个问题在这里已经有答案了 可能的重复 Python 常见问题解答 异常有多快 https stackoverflow com questions 8107695 python faq how fast are exceptions 我记得
  • 在 Linux 上的 Python 中使用受密码保护的 Excel 工作表

    问题很简单 我每周都会收到一堆受密码保护的 Excel 文件 我必须解析它们并使用 Python 将某些部分写入新文件 我得到了文件的密码 当在 Windows 上完成此操作时 处理起来很简单 我只需导入 win32com 并使用 clie
  • 在 iPython/pandas 中绘制多条线会生成多个图

    我试图了解 matplotlib 的状态机模型 但在尝试在单个图上绘制多条线时遇到错误 据我了解 以下代码应该生成包含两行的单个图 import pandas as pd import pandas io data as web aapl
  • 在谷歌云上训练神经网络时出现“无法获取路径的文件系统”错误

    我正在使用 Google Cloud 在云上训练神经网络 如下例所示 https cloud google com blog big data 2016 12 how to classify images with tensorflow u
  • Pandas groupby apply 执行缓慢

    我正在开发一个涉及大量数据的程序 我正在使用 python pandas 模块来查找数据中的错误 这通常工作得非常快 然而 我当前编写的这段代码似乎比应有的速度慢得多 我正在寻找一种方法来加快速度 为了让你们正确测试它 我上传了一段相当大的
  • 如何使用 Celery 多工作人员启用自动缩放?

    命令celery worker A proj autoscale 10 1 loglevel info启动具有自动缩放功能的工作人员 当创建多个工人时 me mypc projects x celery multi start mywork
  • 如何正确导入主代码和模块中同时使用的模块?

    假设我有一个主脚本 main py 它导入另一个 python 文件import coolfunctions另一个 import chores 现在 假设 Coolfunctions 也使用家务活中的东西 因此我声明import chore
  • 为什么 __instancecheck__ 没有被调用?

    我有以下 python3 代码 class BaseTypeClass type def new cls name bases namespace kwd result type new cls name bases namespace p
  • 根据列索引重命名 Dataframe 列

    是否有内置函数可以按索引重命名 pandas 数据框 我以为我知道列标题的名称 但事实证明第二列中有一些十六进制字符 根据我接收数据的方式 我将来可能会在第 2 列中遇到这个问题 因此我无法将这些特定的十六进制字符硬编码到 datafram
  • Django Rest Framework POST 更新(如果存在或创建)

    我是 DRF 的新手 我阅读了 API 文档 也许这是显而易见的 但我找不到一个方便的方法来做到这一点 我有一个Answer与 a 具有一对一关系的对象Question 在前端 我曾经使用 POST 方法来创建发送到的答案api answe
  • 在Python中连续解析文件

    我正在编写一个脚本 该脚本使用 HTTP 流量行解析文件 并取出域 目前仅将它们打印到屏幕上 我正在使用 httpry 将流量连续写入文件 这是我用来删除域名的脚本 usr bin python import re input open r
  • 在 scipy 中创建新的发行版

    我试图根据我拥有的一些数据创建一个分布 然后从该分布中随机抽取 这是我所拥有的 from scipy import stats import numpy def getDistribution data kernel stats gauss
  • Pip 无法在 Windows 上安装 Twisted

    我正在尝试在 Windows 8 计算机上安装 Twisted 在 Twisted 官方网站上 只有一个 Windows 版的 Wheel 文件 https twistedmatrix com trac wiki Downloads htt
  • Streamlabs API 405 响应代码

    我正在尝试使用Streamlabs API https dev streamlabs com Streamlabs API 使用 Oauth2 来创建应用程序 因此 首先我将使用我的应用程序的用户发送到一个授权链接 其中包含我的应用程序的客

随机推荐

  • LibGit2Sharp CheckoutPaths()

    我做了一次提交 49916 现在我想将提交的一个文件检出到工作目录中 该文件名为 NEW txt 如果我输入 Git 签出 49916 NEW txt 进入 Git Bash 后 它会创建 NEW txt 文件 其内容位于我的工作目录中 但
  • 非重叠串行端口挂在 CloseHandle 处

    我编写了一个自己开发的串行端口类 为了简单起见 我使用了阻塞 同步 不重叠 我浏览了所有 MSDN 文档 这对我来说很困难 我在从端口打开 传输或接收字节方面没有任何问题 所有操作都是同步并且不存在线程复杂性 function TSeria
  • Crystal Reports 11 - 添加无用的空白页,仅添加有数据的组标题

    我遇到了一个在使用 Crystal Reports 之前从未见过的奇怪问题 我为一家银行制作了一份复杂的 PDF 月度报告 生成了 200 多页 这些规范花了几个月的时间与客户进行调整 但现在它工作得很好 显示了所有应该显示的数据 所有数据
  • Kubernetes API 服务器日志中的 TLS 握手错误

    我正在研究一个AWS 中 Kubernetes 集群的 terraform 配置 https github com ericandrewlewis kubernetes via terraform 我已经让集群运行起来了 我可以通过 kub
  • 是否有通用方法将约束应用于类型应用程序?

    A comment https stackoverflow com questions 41111715 making a constraint of maybe a where eq a 41111825 noredirect 1 com
  • 不使用循环操作数组

    学习 VBA for Excel 我尝试在不使用循环的情况下完成尽可能多的编码 作为练习 将两个相邻范围的数字相乘 我想出了这个 Sub multiply range Dim a b c As Range Set a Range a1 a5
  • Polly 使用不同的请求主体重试请求

    我以前从未使用过 Polly 并且不确定这对 Polly 来说是否是一个好的场景 我正在调用一个列表为 1000 的端点DTO in the POST身体 现在端点将对每个执行一些验证DTO如果其中任何 DTO 验证失败 则返回 HTTP
  • 使用 WIF 在 .NET Web Farm 中为多个电子商务网站实施 SSO?

    我有一个我认为相当复杂的问题 所以我会尽力在这里阐明它 我正在寻找单点登录 SSO 解决方案 我知道有很多选择 但在我添加了它们需要满足的标准时排除了其中的大多数 以下是标准 1 SSO 必须添加到现有 系统 中 2 现有 系统 由 X 个
  • 谷歌是如何获得地图上邮政编码的轮廓的?

    例如 http g co maps 2dpkj http g co maps 2dpkj有邮政编码区域周围的轮廓 我知道这无法通过 API 获得 但我还可以从哪里获取此数据 例如 KML 格式 这是英国数据 最有可能的Google 与英国地
  • 外部 SQLite 文件内容访问错误

    我有以下代码 它给出了如下运行时错误 为什么 try String myPath DB PATH DB NAME mDB SQLiteDatabase openDatabase myPath null SQLiteDatabase OPEN
  • Push API 和服务器发送事件有什么区别?

    从文档中我可以看出Push API http w3c github io push api and 服务器发送事件 http www html5rocks com en tutorials eventsource basics 两者都是半双
  • 在没有源的情况下更改 .jar 文件?

    我有一个基于 Java 的 TCP 客户端 它与我们的生产服务器通信 我正在重写它 客户端对服务器的 IP 和端口进行硬编码 我想要做的就是将客户端中的 IP 地址更改为 127 0 0 1 我可以在我的开发盒上使用相同的端口号 问题是 我
  • 爪哇。隐式超级构造函数 Employee() 未定义。必须显式调用另一个构造函数[重复]

    这个问题在这里已经有答案了 您好 我是 Java 新手 我在生产工作线程类中遇到此错误 我的生产工作线程构造函数显示显式调用另一个构造函数 我不知道该怎么办 import java util Date public class Employ
  • Python 或 PHP 中的感知哈希算法? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 相同运算符优先级的结合性 -- *start++

    为什么会出现下面的表达式 total start 评估为 total start And not total start though this doesn t really matter either it would be the sa
  • 有 Delphi XE2 样式库吗?

    在 XE2 中 有一个新函数 styles 用于 VCL vsf 和 Firemonkey styles 有些是在C Program Files Embarcadero RAD Studio 9 0 Redist styles目录 创建新样
  • 同步视图模型和视图

    我有一个由一些节点和一些连接器组成的视图模型 public class ViewModel public List
  • 更改滚动时的 URL 哈希并保持后退按钮正常工作

    在具有固定顶部菜单和锚点导航的一页布局上 我有一个 scrollspy 它可以更改滚动时的片段标 识符 根据滚动位置为菜单链接提供一个活动类 并使用 Velocity js 将滚动动画到锚点 不幸的是 它还做了什么 当单击浏览器后退按钮时
  • 在 JavaScript 中递归构建 Promise 链 - 内存注意事项

    In 这个答案 https stackoverflow com a 29906627 3478010 递归地构建承诺链 稍微简化一下 我们有 function foo function doo always return a promise
  • 将箭头放在 3d 图中的向量上

    I plotted the eigenvectors of some 3D data and was wondering if there is currently already a way to put arrowheads on th