import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.animation import FuncAnimation

创建木星及其卫星的数据

data = { 'Jupiter': { 'radius': 69911, 'color': 'orange', 'orbit_radius': 0, 'orbit_speed': 0, }, 'Io': { 'radius': 1821.6, 'color': 'gray', 'orbit_radius': 421.6, 'orbit_speed': 17, }, 'Europa': { 'radius': 1560.8, 'color': 'lightblue', 'orbit_radius': 671.1, 'orbit_speed': 13, }, 'Ganymede': { 'radius': 2631.2, 'color': 'lightyellow', 'orbit_radius': 1070.4, 'orbit_speed': 10, }, 'Callisto': { 'radius': 2410.3, 'color': 'lightgreen', 'orbit_radius': 1882.7, 'orbit_speed': 8, }, }

创建交互式可视化界面

def interactive_visualization(): fig = plt.figure() ax = fig.add_subplot(111, projection='3d')

for name, satellite in data.items():
    radius = satellite['radius']
    color = satellite['color']
    orbit_radius = satellite['orbit_radius']
    orbit_speed = satellite['orbit_speed']

    # 绘制卫星
    ax.scatter(orbit_radius, 0, 0, c=color, s=radius, label=name)

    # 绘制卫星轨道
    orbit = plt.Circle((0, 0), orbit_radius, fill=False)
    ax.add_patch(orbit)

ax.set_xlim([-3000, 3000])
ax.set_ylim([-3000, 3000])
ax.set_zlim([-3000, 3000])
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

# 添加交互操作
def update_orbits(frame):
    for name, satellite in data.items():
        orbit_radius = satellite['orbit_radius']
        orbit_speed = satellite['orbit_speed']

        # 更新卫星位置
        angle = orbit_speed * frame
        x = orbit_radius * 1.5 * 0.8 * (1.5 * 0.8) ** angle
        y = orbit_radius * 0.8 * (0.8) ** angle
        ax.collections[name]._offsets3d = ([x], [y], [0])

# 动画效果
frames = 100
anim = FuncAnimation(fig, update_orbits, frames=frames, interval=50, repeat=True)

plt.legend()
plt.show()

运行交互式可视化界面

interactive_visualization()

代码有bug,原因:AttributeError: 'Circle' object has no attribute 'do_3d_projection' 要怎么解决呢内容:这个问题是因为在更新卫星位置时,使用了错误的方法来更新卫星的位置信息。正确的方法是更新卫星的坐标数组,而不是直接更新卫星对象的位置。

以下是修复代码中的问题的示例:

# 添加交互操作
def update_orbits(frame):
    for name, satellite in data.items():
        orbit_radius = satellite['orbit_radius']
        orbit_speed = satellite['orbit_speed']

        # 更新卫星位置
        angle = orbit_speed * frame
        x = orbit_radius * 1.5 * 0.8 * (1.5 * 0.8) ** angle
        y = orbit_radius * 0.8 * (0.8) ** angle
        ax.collections[name]._offsets3d = ([x], [y], [0])

# 动画效果
frames = 100
anim = FuncAnimation(fig, update_orbits, frames=frames, interval=50, repeat=True)

plt.legend()
plt.show()

这样,应该就能够正确地更新卫星的位置并播放动画了。


原文地址: https://www.cveoy.top/t/topic/o1Ss 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录