You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python绘制行星轨道:编程新手求助完整实现方案

行星轨道2D俯视图绘制任务解析与实现

一、朋友提供的线索代码解析

这段代码是绘图函数的雏形,逐行作用如下:

  • def plot_planet_orbit(planet_names)::定义一个可接收行星名称参数的绘图函数,支持单个或多个行星的选择
  • E = np.linspace(0,2*np.pi,10000):生成从0到2π的10000个均匀分布的偏近点角值,用来模拟轨道上的连续点,保证轨道曲线平滑
  • planets = [x for x in orb_elements if x[-1] in planets_names]:用列表推导式从全局轨道元素列表中筛选出指定名称的行星数据
  • 循环部分:遍历筛选后的行星,将轨道元素解包为单个变量,调用转换函数得到轨道的笛卡尔坐标,但这段代码只完成了坐标计算,缺少绘图逻辑

二、完整实现代码

首先需要导入依赖库,然后整合所有代码:

import numpy as np
import matplotlib.pyplot as plt

# 给定的行星轨道元素列表
orb_elements = [
    [0.3871, 0.20564, 7.006, 77.46, 48.34, 0.241, 'Mercury'],   # Mercury
    [0.7233, 0.00676, 3.398, 131.77, 76.67, 0.615, 'Venus'],  # Venus
    [1.0, 0.01673, 0.0, 102.93, 0.0, 1.0, 'Earth'],         # Earth
    [1.5237, 0.09337, 1.852, 336.08, 49.71, 1.881, 'Mars'],  # Mars
    [5.2025, 0.04854, 1.299, 14.27, 100.29, 11.87, 'Jupiter'],  # Jupiter
    [9.5415, 0.05551, 2.492, 92.86, 113.64, 29.47, 'Saturn'],  # Saturn
    [19.188, 0.04689, 0.773, 172.43, 73.96, 84.05, 'Uranus'],  # Uranus
    [30.070, 0.00895, 1.770, 46.68, 131.79, 164.9, 'Neptune'],  # Neptune
    [39.4821, 0.24883, 17.14, 113.76, 110.30, 247.94, 'Pluto'],# Pluto 
]

# 轨道元素转笛卡尔坐标函数
def orbitalElements2Cartesian(a, e, I, peri, node, E):
    """ Convert orbital elements to Cartesian coordinates in the Solar System.

    Args: 
        a (float): semi-major axis (AU)
        e (float): eccentricity
        I (float): inclination (degrees)
        peri (float): longitude of perihelion (degrees)
        node (float): longitude of ascending node (degrees)
        E (float): eccentric anomaly (radians) ; this can be an array or single value

    """

    # Convert degrees to radians
    I, peri, node = map(np.radians, [I, peri, node])

    # True anomaly
    theta = 2*np.arctan(np.sqrt((1.0 + e)/(1.0 - e))*np.tan(E/2.0))

    # Distance from the Sun to the point on orbit
    r = a*(1.0 - e*np.cos(E))

    # Cartesian coordinates
    x = r*(np.cos(node)*np.cos(peri + theta) - np.sin(node)*np.sin(peri + theta)*np.cos(I))
    y = r*(np.sin(node)*np.cos(peri + theta) + np.cos(node)*np.sin(peri + theta)*np.cos(I))
    z = r*np.sin(peri + theta)*np.sin(I)

    return x, y, z

# 完整的绘图函数
def plot_planet_orbit(planet_names):
    # 生成偏近点角数组
    E = np.linspace(0, 2*np.pi, 10000)
    # 筛选目标行星
    target_planets = [orbit for orbit in orb_elements if orbit[-1] in planet_names]
    
    # 创建画布并设置轴比例一致
    plt.figure(figsize=(10, 10))
    ax = plt.gca()
    ax.set_aspect('equal')  # 避免轨道因轴比例失衡变形
    
    # 遍历行星绘制轨道和位置点
    for orbit in target_planets:
        a, e, I, peri, node, period, name = orbit
        # 获取轨道全程坐标
        x_orbit, y_orbit, _ = orbitalElements2Cartesian(a, e, I, peri, node, E)
        # 绘制轨道曲线
        plt.plot(x_orbit, y_orbit, label=name, linewidth=1.5)
        # 获取行星近心点位置(E=0时的坐标)并绘制
        x_pos, y_pos, _ = orbitalElements2Cartesian(a, e, I, peri, node, 0)
        plt.scatter(x_pos, y_pos, s=60, zorder=5)
    
    # 添加太阳标记(中心位置(0,0))
    plt.scatter(0, 0, color='gold', s=250, label='Sun', zorder=10)
    
    # 设置图表样式
    plt.xlabel('X (Astronomical Units)')
    plt.ylabel('Y (Astronomical Units)')
    plt.title('Solar System Planet Orbits (Top-down View)')
    plt.legend(loc='upper right')
    plt.grid(True, linestyle='--', alpha=0.6)
    plt.show()

三、使用示例

  • 绘制单个行星(比如水星):
plot_planet_orbit(['Mercury'])
  • 绘制多个行星(比如地球、火星、木星):
plot_planet_orbit(['Earth', 'Mars', 'Jupiter'])

四、关键细节说明

  • ax.set_aspect('equal'):必须设置,否则椭圆轨道会因为x/y轴比例不同被拉伸变形
  • zorder参数:控制绘图层级,太阳在最上层,行星位置点在轨道曲线之上,避免被遮挡
  • 偏近点角的点数:10000个点足够让轨道曲线平滑,若追求效率可减少至5000个
  • 俯视图仅使用x和y坐标,z坐标代表轨道倾角的垂直分量,无需在2D图中展示

内容的提问来源于stack exchange,提问作者Plzhelpme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 09:55:27