首页 > 解决方案 > 没有 Matplotlib 的 Python 中 x、y、z 点的 2D 图

问题描述

我有一组 3d 点(我从开普勒方程生成恒星系统中行星和卫星的位置)我有所有点的坐标为 x,y,z,其中中心恒星为 0,0,0。产生点的代码完美无缺。

然而,目前我从上面绘制了这个系统的可视化——所以我只是为了可视化而忽略了 z 分量,并将 x 和 y 原样绘制到画布上。这按预期工作。

我将如何生成 x 和 y 坐标以绘制到考虑 z 坐标的画布,以便我可以从正上方以外的另一个角度绘制视图?

除了标准库之外,我唯一可以使用的库是 numpy。我不能使用 Matplotlib。

编辑感谢评论,我现在可以用一些伪代码来澄清。

假设我有一堆具有 xyz 位置的点。

我目前在做什么:

canvas.plot(point.x)

canvas.plot(point.y)

忽略点 z - 就好像所有 z 都是 0 并且从“上方”查看

所以我可以使用我当前的绘图代码 - 考虑到与画布有关的比例和偏移量,我需要新的 x 和 y 坐标,就好像视图来自“上方”以外的另一个角度。

从有用的评论看来,我要做的是旋转整个坐标系,使其具有一个新的 z 轴,这是整个系统围绕 x 和 y 轴旋转的结果。

类似下面的伪代码就可以了。

def rotate_about_axis(x_rotation_degrees, y_rotation_degrees, point.x, point.y, point.z):
    new_plot_x = canvas_point_to_plot after magic code to rotate coordinates x_rotation_degrees about x axis
    new_plot_y = canvas_point_to_plot after magic code to rotate coordinates y_rotation_degrees about y axis

return new_plot_x, new_plot_y

然后我可以将它应用于我绘制的所有点。

我将如何在 python 中执行此操作?

标签: python-3.xnumpycoordinates

解决方案


我想出了一个答案,我希望它对某人有所帮助。

import numpy, math

def rotate_about_axis(x_rotation_degrees, y_rotation_degrees, point_x, point_y, point_z):

    xrads = math.radians(x_rotation_degrees)
    yrads = math.radians(y_rotation_degrees)
    rotation = [xrads, yrads, 0]
    rotation_angle = numpy.linalg.norm(rotation)
    norm_rotation = rotation / numpy.linalg.norm(rotation)
    base_points = [point_x, point_y, point_z]
    points = numpy.dot(base_points, norm_rotation) * norm_rotation
    points_difference = base_points - points
    points_transform = numpy.cross(norm_rotation, base_points)
    rotated_points = points + points_difference * numpy.cos(rotation_angle) + points_transform * numpy.sin(rotation_angle)

    rotated_point_x = rotated_points[0]
    rotated_point_y = rotated_points[1]

    return(rotated_point_x, rotated_point_y)

推荐阅读