import numpy as npimport matplotlibpyplot as plt# 行星参数轨道半长轴、偏心率、轨道倾角planet_params = Mercury 0387 0205 70 Venus 0723 0007 34 Earth 10 0017 00 Mars 1524 0093 19 Jupiter 5203 0048 13 S
在获取行星轨道线的循环中,使用了错误的索引,导致出现了"list index out of range"错误。正确的做法是在外层循环中使用ax.lines来获取所有的轨道线。
修改后的代码如下:
# 点击行星时弹出新窗口显示行星和其卫星的轨道运行
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())
# 在这里添加代码计算和绘制行星及其卫星的轨道运行
planet = event.artist.get_label()
params = planet_params[planet]
x, y, z = calculate_orbit(*params)
ax.plot(x, y)
plt.show()
# 绘制太阳系行星运行轨道
plot_orbits()
# 为每个行星添加点击事件
fig = plt.gcf()
for planet, params in planet_params.items():
for line in fig.axes[0].lines:
if line.get_label() == planet:
line.set_picker(5)
break
fig.canvas.mpl_connect('pick_event', on_click)
运行修改后的代码,即可正常绘制行星及其卫星的轨道运行
原文地址: http://www.cveoy.top/t/topic/hAgb 著作权归作者所有。请勿转载和采集!