Python 3D 太阳系模型:用 matplotlib 实现天体运动可视化
要创建一个 3D 的太阳系模型,可以使用 Python 中的 matplotlib 库来实现。下面是一个简单的示例代码,展示了如何使用 matplotlib 创建一个太阳、地球和月球的模型,并观察它们的运动。\n\npython\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# 创建画布\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\n# 定义太阳、地球和月球的初始位置\nsun_pos = np.array([0, 0, 0])\nearth_pos = np.array([10, 0, 0])\nmoon_pos = np.array([10, 0, 1])\n\n# 绘制太阳\nax.scatter(sun_pos[0], sun_pos[1], sun_pos[2], color='yellow', s=100)\n\n# 绘制地球和月球\nearth = ax.scatter(earth_pos[0], earth_pos[1], earth_pos[2], color='blue', s=20)\nmoon = ax.scatter(moon_pos[0], moon_pos[1], moon_pos[2], color='gray', s=10)\n\n# 设置坐标轴范围\nax.set_xlim([-15, 15])\nax.set_ylim([-15, 15])\nax.set_zlim([-15, 15])\n\n# 动画更新函数\ndef update(i):\n    # 计算地球和月球的新位置\n    angle = np.radians(i * 3)\n    earth_pos[0] = 10 * np.cos(angle)\n    earth_pos[1] = 10 * np.sin(angle)\n    moon_pos[0] = earth_pos[0] + 1 * np.cos(angle * 10)\n    moon_pos[1] = earth_pos[1] + 1 * np.sin(angle * 10)\n    \n    # 更新地球和月球的位置\n    earth._offsets3d = (earth_pos[0], earth_pos[1], earth_pos[2])\n    moon._offsets3d = (moon_pos[0], moon_pos[1], moon_pos[2])\n\n# 创建动画\nani = plt.FuncAnimation(fig, update, frames=np.arange(0, 120, 2), interval=50)\n\n# 显示动画\nplt.show()\n\n\n运行以上代码,将会创建一个显示太阳、地球和月球运动的动画。地球绕太阳旋转,同时月球绕地球旋转。你可以根据需要调整代码中的各种参数,如位置、颜色和速度等,以满足你的需求。
原文地址: https://www.cveoy.top/t/topic/pn7e 著作权归作者所有。请勿转载和采集!