Python 绘制太阳系行星轨道并添加点击事件
Python 绘制太阳系行星轨道并添加点击事件
import numpy as np
import matplotlib.pyplot as plt
# 行星参数(轨道半长轴、偏心率、轨道倾角)
planet_params = {
'Mercury': [0.387, 0.205, 7.0],
'Venus': [0.723, 0.007, 3.4],
'Earth': [1.0, 0.017, 0.0],
'Mars': [1.524, 0.093, 1.9],
'Jupiter': [5.203, 0.048, 1.3],
'Saturn': [9.537, 0.056, 2.5],
'Uranus': [19.191, 0.046, 0.8],
'Neptune': [30.069, 0.010, 1.8]
}
# 计算行星的轨道位置
def calculate_orbit(semi_major_axis, eccentricity, inclination):
theta = np.linspace(0, 2*np.pi, 1000)
r = semi_major_axis * (1 - eccentricity**2) / (1 + eccentricity * np.cos(theta))
x = r * np.cos(theta)
y = r * np.sin(theta) * np.cos(np.radians(inclination))
z = r * np.sin(theta) * np.sin(np.radians(inclination))
return x, y, z
# 绘制太阳系行星运行轨道
def plot_orbits():
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for planet, params in planet_params.items():
x, y, z = calculate_orbit(*params)
ax.plot(x, y, z, label=planet)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.legend()
plt.show()
# 点击行星时弹出新窗口显示行星和其卫星的轨道运行
def on_click(event):
if event.artist.get_label() in planet_params:
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_title(event.artist.get_label())
# 在这里添加代码计算和绘制行星及其卫星的轨道运行
plt.show()
# 绘制太阳系行星运行轨道
plot_orbits()
# 保存axes对象
axes = plt.gca()
# 为每个行星添加点击事件
fig = plt.gcf()
for planet, params in planet_params.items():
for line in axes.get_lines():
if line.get_label() == planet:
line.set_picker(5)
break
fig.canvas.mpl_connect('pick_event', on_click)
代码说明:
- 首先定义了行星参数,包括轨道半长轴、偏心率和轨道倾角。
calculate_orbit
函数用于根据行星参数计算轨道位置。plot_orbits
函数绘制所有行星的轨道。on_click
函数用于处理点击事件,当用户点击行星时,该函数将弹出新窗口显示行星及其卫星的轨道运行。- 在绘制轨道后,使用
plt.gca()
获取当前 axes 对象,并保存到axes
变量中。 - 在添加点击事件的循环中,使用
axes.get_lines()
获取所有线对象,并为每个行星添加点击事件。
运行结果:
运行程序后,将显示太阳系行星的轨道图。点击任意行星,将弹出新窗口显示该行星及其卫星的轨道运行。
注意:
该代码示例仅演示了如何绘制行星轨道并添加点击事件。要实现显示行星及其卫星的轨道运行,需要添加相应的代码来计算和绘制卫星的轨道。
原文地址: http://www.cveoy.top/t/topic/o22N 著作权归作者所有。请勿转载和采集!