当我们给定中心点和半径大小时,如何绘制球体?

2024-03-17

我有一个像 [[1, 2, 2.23], [2, 3, 3.6],[-3, 4, 5], ...] 的矩阵,每一行表示一个点。

What I wish to do is like this:
I want to create a function which is given two parameters :
A center like [0,0,0] and the matrix above.
Then it calculates the maximum distance of points to the center as the radius of sphere and draw a sphere along with the points in matrix.
The sphere is transparent, so if we plot the points, we can see the points inside the sphere.
the sphere is transparent, so if we plot the points, we can see the points inside the sphere.
I also need to differentiate the point with maximum distance in some way. like draw a vector from center to the point or draw it with different color. Any help would be appreciated.


基于这个答案 https://stackoverflow.com/questions/11140163/python-matplotlib-plotting-a-3d-cube-a-sphere-and-a-vector:

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

# interactive mode off, can [normally] be safely removed
plt.ioff()

# define an arrow class:
class Arrow3D(FancyArrowPatch):
    def __init__(self, start=[0,0,0], end=[1,1,1], *args, **kwargs):
        if "arrowstyle" not in kwargs:
            kwargs["arrowstyle"] = "-|>"
        if "mutation_scale" not in kwargs:
            kwargs["mutation_scale"] = 20
        if "color" not in kwargs:
            kwargs["color"] = "k"
        FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
        xs = [start[0], end[0]]
        ys = [start[1], end[1]]
        zs = [start[2], end[2]]
        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)

def WireframeSphere(centre=[0.,0.,0.], radius=1.,
                    n_meridians=20, n_circles_latitude=None):
    """
    Create the arrays of values to plot the wireframe of a sphere.

    Parameters
    ----------
    centre: array like
        A point, defined as an iterable of three numerical values.
    radius: number
        The radius of the sphere.
    n_meridians: int
        The number of meridians to display (circles that pass on both poles).
    n_circles_latitude: int
        The number of horizontal circles (akin to the Equator) to display.
        Notice this includes one for each pole, and defaults to 4 or half
        of the *n_meridians* if the latter is larger.

    Returns
    -------
    sphere_x, sphere_y, sphere_z: arrays
        The arrays with the coordinates of the points to make the wireframe.
        Their shape is (n_meridians, n_circles_latitude).

    Examples
    --------
    >>> fig = plt.figure()
    >>> ax = fig.gca(projection='3d')
    >>> ax.set_aspect("equal")
    >>> sphere = ax.plot_wireframe(*WireframeSphere(), color="r", alpha=0.5)
    >>> fig.show()

    >>> fig = plt.figure()
    >>> ax = fig.gca(projection='3d')
    >>> ax.set_aspect("equal")
    >>> frame_xs, frame_ys, frame_zs = WireframeSphere()
    >>> sphere = ax.plot_wireframe(frame_xs, frame_ys, frame_zs, color="r", alpha=0.5)
    >>> fig.show()
    """
    if n_circles_latitude is None:
        n_circles_latitude = max(n_meridians/2, 4)
    u, v = np.mgrid[0:2*np.pi:n_meridians*1j, 0:np.pi:n_circles_latitude*1j]
    sphere_x = centre[0] + radius * np.cos(u) * np.sin(v)
    sphere_y = centre[1] + radius * np.sin(u) * np.sin(v)
    sphere_z = centre[2] + radius * np.cos(v)
    return sphere_x, sphere_y, sphere_z

def find_most_distants(points, center=[0.,0.,0.], tol=1e-5):
    """
    Finds and returns a list of points that are the most distante ones to
    the center.    

    Parameters
    ----------
    points: list
        A list of points (see center to know what a point is)
    center: array like
        A point, defined as an iterable of three numerical values.
    """
    # make central point an array to ease vector calculations
    center = np.asarray(center)
    # find most distant points
    max_distance = 0
    most_distant_points = []
    for point in points:
        distance = np.linalg.norm(center-point)
        if abs(distance - max_distance) <= tol:
            most_distant_points.append(point)
        elif distance > max_distance:
            most_distant_points = [point]
            max_distance = distance
    return max_distance, most_distant_points

def list_of_points_TO_lists_of_coordinates(list_of_points):
    """
    Converts a list of points to lists of coordinates of those points.

    Parameter
    ---------
    list_of_points: list
        A list of points (each defined as an iterable of three numerical values)

    Returns
    -------
    points_x, points_y, points_z: array
        Lists of coordinates
    """
    points_x = []
    points_y = []
    points_z = []
    for point in list_of_points:
        points_x.append(point[0])
        points_y.append(point[1])
        points_z.append(point[2])
    return points_x, points_y, points_z

def function(central_point=[0.,0.,0.],
             other_points=[[1., 2., 2.23],
                           [2., 3., 3.6],
                           [-3., 4., 5.]],):
    """
    Draws a wireframe sphere centered on central_point and containing all
    points in other_points list. Also draws the points inside the sphere and
    marks the most distant ones with an arrow.

    Parameters
    ----------
    central_point: array like
        A point, defined as an iterable of three numerical values.
    other_points: list
        A list of points (see central_point to know what a point is)
    """
    # find most distant points
    max_distance, most_distant_points = find_most_distants(other_points, central_point)
    #prepare figure and 3d axis
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.set_aspect("equal")
    #draw sphere
    ax.plot_wireframe(*WireframeSphere(central_point, max_distance), color="r", alpha=0.5)
    # draw points
    ax.scatter(*list_of_points_TO_lists_of_coordinates(other_points))
    # draw arrows to most distant points:
    for extreme_point in most_distant_points:
        ax.add_artist(Arrow3D(start=central_point, end=extreme_point))
    fig.show()

if __name__ == '__main__':
    function([0,0,0], 2*np.random.rand(50,3)-1)
    # make a list with equally most distant point:
    repeated_max_list = 2*np.random.rand(10,3)-1
    distance, points = find_most_distants(repeated_max_list)
    repeated_max_list =  np.concatenate((repeated_max_list,points))
    repeated_max_list[-1][0] = -repeated_max_list[-1][0]
    repeated_max_list[-1][1] = -repeated_max_list[-1][1]
    repeated_max_list[-1][2] = -repeated_max_list[-1][2]
    function([0,0,0], repeated_max_list)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当我们给定中心点和半径大小时,如何绘制球体? 的相关文章

  • 如何向类添加对十六进制函数的支持

    我写了一个类来实现 int 方法 以便实例可以表现得像整数 class MyClass def init self value self value value def int self return self value 使用int实例上
  • 在同一进程中多次运行Scrapy

    我有一个网址列表 我想抓取其中的每一个 请注意 将此数组添加为start urls不是我正在寻找的行为 我希望它在单独的爬网会话中一一运行 我想在同一个进程中多次运行Scrapy 我想将 Scrapy 作为脚本运行 如常见做法 https
  • 如何导入Python文件?

    抱歉 这绝对是重复的 但我找不到答案 我正在使用 Python 3 这是我的应用程序的结构 home common py australia new south wales fetch py 我在home 目录 运行fetch py 我如何
  • Matplotlib 将颜色图 tab20 更改为三种颜色

    Matplotlib 有一些新的且非常方便的颜色图 选项卡颜色图 https matplotlib org examples color colormaps reference html 我错过的是生成像 tab20b 或 tab20c 这
  • 使用 pandas 绘制带有误差线的条形图

    我正在尝试从 DataFrame 生成条形图 如下所示 Pre Post Measure1 0 4 1 9 这些值是我从其他地方计算出来的中值 我还有它们的方差和标准差 以及标准误差 我想将结果绘制为具有适当误差线的条形图 但指定多个误差值
  • bool() 和operator.truth() 有什么区别?

    bool https docs python org 3 library functions html bool and operator truth https docs python org 3 library operator htm
  • 如何在 Matplotlib 中编写自己的 LaTeX 序言?

    我正在尝试创建一个数字matplotlib插入我的LaTeX文档 我需要粗体 i and j 没有圆点和帽子的符号 我一直在使用代码 mathbf hat textnormal bfseries i 在我的文档中 但由于这使用了amsmat
  • Python子类方法从超类方法继承装饰器

    我有一个具有retrieve 方法的超类 并且它的子类每个都实现自己的retrieve 方法 我希望每个retrieve 方法都被装饰为在收到相同参数时缓存返回值 而不必在每个子类中装饰该方法 装饰器似乎不能被继承 我可能可以调用超类的方法
  • keras 中的增量学习

    我正在寻找 scikit learn 的 keras 等效项partial fit https scikit learn org 0 15 modules scaling strategies html incremental learni
  • 如何更改Python使用的SQLite版本?

    我在 Debian 9 12 上安装了 Python 3 8 和 SQLite 3 16 2 并且需要升级到较新版本的 SQLite 我已经下载并编译了 SQLite 网站上提供的合并 并将其放入 usr bin 所以当我这样做时 sqli
  • matplotlib imshow() 和像素强度

    我试图了解矩阵的值是如何输入到 matplotlib 的imshow 函数确定灰度模式下像素的强度 考虑示例代码 import random import matplotlib pyplot as plt import matplotlib
  • Python 3:http.server 支持 ipv6 吗?

    Does http server http作为 Python 3 x 模块 支持 ipv6 例如 使用以下命令行代码 启动网络服务器 python m http server port 从 Python 3 8 开始 python m ht
  • requests.iter_content() 认为文件已完成,但事实并非如此

    这个问题与我见过的其他问题不同requests iter content 在那里面requests似乎认为它已成功到达我正在迭代的文件末尾 实际上 该文件已被截断且不完整 我尝试处理的文件是一个 17gb gzip 需要丰富并存储在数据库中
  • 当传递命名参数时,matplotlib 不会绘图

    有人可以解释这种行为吗 import matplotlib pyplot as plt plt plot x 0 05 0 1 0 15 y 102 211 393 plt show import matplotlib pyplot as
  • 类unix系统中的python和python3命令有什么区别?

    我通读了每个命令的描述 但每个命令的描述都是完全相同的 所以我不明白这两个命令在类 Unix 系统中的工作方式有何不同 谁能解释其中的区别吗 Python3命令的引入是因为python命令指向了python2 从那时起 Python3 已成
  • 使用 matplotlib 为水平条形图创建替代 y 轴标签

    这是我刚刚提出的问题的 更清晰的 转发 我的去身份化让人们感到困惑 你好 我是使用 matplotlib pyplot 在 python 中绘图的新手 并花了很多时间在这个网站和其他网站上搜索 并试图弄清楚这一点 但我还没有成功完成我想做的
  • 防止脚本目录被添加到Python 3中的sys.path

    有没有办法阻止脚本的目录被添加到python3中的sys path 由于导入在 python 中是相对的 因此我遇到了导入冲突 我正在处理的一个遗留项目有一个名为logger py在与内置冲突的脚本的根目录中logger 我使用的自定义构建
  • 如何从分组数据创建直方图

    我正在尝试根据 pandas 中的分组数据创建直方图 到目前为止 我已经能够创建标准线图 但我不知道如何做同样的事情来获取直方图 条形图 我想获得泰坦尼克号事故中幸存者和未幸存者的 2 个年龄直方图 看看年龄分布是否存在差异 来源数据 ht
  • Python range() 和 zip() 对象类型

    我了解功能如何range and zip 可以在 for 循环中使用 然而我期望range 输出一个列表 很像seq在 Unix shell 中 如果我运行以下代码 a range 10 print a 输出是range 10 表明它不是一
  • Tweepy 流式传输错误

    我正在尝试使用 tweepy 和 textblob 分析推文的情绪 我执行了 pip install tweepy 并且安装成功 但出现以下错误 错误信息 文件 C Users joshey Desktop sent py 第 2 行 位于

随机推荐

  • 将双精度数转换为没有小数位的字符串的最佳方法

    将双精度数转换为没有小数位的字符串的最佳方法是什么 关于什么String valueOf int documentNumber 双精度数小数点后始终为 0 我不需要舍入或截断 如果您确定 double 确实是一个整数 请使用这个 Numbe
  • Delphi - 反向查找“谁包括这个单元”

    我正在调试分布在许多单元上的大型应用程序 我在低级单元中遇到了编译错误 并且完全不知道该单元在应用程序的哪个部分被引用 有没有办法使用 RAD studio 2010 的 IDE 创建某种包含图 由于大多数使用的单元不是项目的一部分 并且分
  • React 表单,提交对象,然后将其推送到数组

    我是 React 新手 不确定如何执行此操作 我有一组已映射并在视图中渲染的对象 我想要做的是设置一个表单 将每个字段的值提交到新对象的相应属性 但我不确定如何执行此操作 这是我的初始数据 它在视图中呈现 contactArray name
  • C# Outlook 2007 COM 互操作应用程序不退出!

    知道为什么以下代码不退出通过 COM 互操作创建的 Outlook 2007 进程吗 Microsoft Office Interop Outlook Application app new Microsoft Office Interop
  • 为什么这个 readline 异步迭代器无法正常工作?

    这是一个更大流程的一部分 我在节点 v14 4 0 中将其提炼为最小的 可重现的示例 在此代码中 它从内部不输出任何内容for loop 我在控制台中只看到这个输出 before for loop finished finally done
  • 如何使用 pgx 记录查询?

    如果我使用 pgx 池 我找不到如何记录 sql 查询的文档 例如我创建了这样的池 func DB pgxpool Pool connStr os Getenv DATABASE URL conn err pgxpool Connect c
  • 迁移到Git时如何处理部分svn:externals?

    我想将 SVN 存储库导入 GitHub Enterprise 存储库 与此相关的问题有很多 其中大多数都可以通过 Git 子模块或 Git 子树来解决 就我而言 我有两个存储库 主项目存储库 模块存储库 超过 2 GB 的大型 SVN 存
  • 如果找不到 emacs 初始化文件怎么办?

    我正在尝试按照以下说明将 haskell 模式添加到 emacs http doc gnu darwin org haskell mode installation guide html http doc gnu darwin org ha
  • ASP.NET Core 2,jQuery POST 数据为空

    I use jQuery并发送数据POST方法 但在服务器方法中 值没有出现 可能是什么错误 client ajax type POST contentType application json charset utf 8 url AddT
  • 接受套接字函数超时

    我试图在接受套接字函数上设置超时 但没有成功 我希望接受功能块直到超时延迟结束 是否可以不将接受函数设置为非阻塞 我尝试了很多可能性都没有成功 感谢您的回答 下面是我的代码 struct timeval tv fd set readfds
  • 从 SwiftUI 中的切换列表中读取值

    我希望这个问题不要太愚蠢 我被这个问题困扰了很长时间 尝试了不同的方法 但仍然失败 我对 Swift 和 SwiftUI 还很陌生 这就是为什么我可能看不到明显的东西 我有一个包含切换列表的视图 切换列表依赖于setData它是由包含 id
  • 如何将 Express.js 变量传递给 MongoDB 函数?

    我正在研究一个博客应用程序 https github com Ajax30 XPressBlog 点击链接即可查看GitHub回购 与Express https expressjs com EJS https ejs co 和 MongoD
  • 为什么使用不匹配的参数调用重载函数仍然有效

    我无法解释为什么第二个电话 B 不会给出任何错误 因为有两个char元素 并且此调用没有确定的匹配 为什么叫第二个 2 但不是第一个 1 版本 我注意到有一些自动转换 我不明白的是为什么 a 被提升为 int 并且 c isn t 1 in
  • 如果使用了 waitFor,为什么杀死 JVM 也会终止其子进程?

    If waitFor不使用时 杀死JVM对其子进程没有影响 这是一个例子 重击脚本 usr bin env bash echo Sleeping gt log sleep 30 echo Wake up gt gt log Java代码 p
  • Java Applet 在 Safari 中沙箱化?

    自从升级到 Mavericks 后 如果从 Safari 使用 我们工作中的 Applet 就不再能够浏览文件 但在 Firefox 上仍然可以使用 Applet 处理文件上传 因此您可以想象这可能是一个问题 从 Safari 使用它时 我
  • 链接 ipython 小部件按钮和滑块值

    我试图弄清楚如何将按钮小部件控制的计数器的值链接到滑块小部件的值 这里的目标是使用 ipython 小部件创建一个简单的 类似 vcr 的界面 其中包含三个小部件 IntSlider和两个Button递增计数器和递减计数器 这就是我所拥有的
  • 如何将标题图像居中

    我有个问题 其他人问题的答案并没有解决我的问题 这是关于我的标题中的图像 代码如下 HTML div div img class center src http i imgur com jfDhpP5 png div div li a hr
  • 如何使用Python抓取需要先登录的网站

    首先 我认为值得一提的是 我知道有很多类似的问题 但没有一个对我有用 我是 Python html 和网络爬虫的新手 我正在尝试从需要先登录的网站中抓取用户信息 在我的测试中 我使用从 github 抓取我的电子邮件设置作为示例 主页是 h
  • 一个文件夹中包含 100 万个或更多文件,用于包含(缓存)[关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 我有一个 理论 问题 看看我正在计划的解决方案是否有意义 我有一个脚本 可以从数据库中读取大量数据 包括设置 配置等 并将其构建在一起 针对每个注册用
  • 当我们给定中心点和半径大小时,如何绘制球体?

    我有一个像 1 2 2 23 2 3 3 6 3 4 5 的矩阵 每一行表示一个点 What I wish to do is like this I want to create a function which is given two