Python N体模拟中如何固定Matplotlib的3D坐标轴长度?
解决Matplotlib 3D可视化坐标轴随点缩放的问题
问题出在你每次循环用ax.cla()清空坐标轴时,会把之前的坐标轴范围设置一并清除,导致Matplotlib每次自动缩放坐标轴适配当前点的位置。这里给两种简单的解决办法:
方法一:每次清空后重新固定坐标轴范围
先根据你的N体模拟场景,预估坐标的最大最小值(或者先跑一次模拟获取实际范围),然后在每次清空坐标轴后重新设置固定范围:
plt.ion() fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # 根据模拟需求调整数值,比如坐标不会超出[-20,20]就这么设 x_range = (-20, 20) y_range = (-20, 20) z_range = (-20, 20) for t in np.arange(0, 10000, dt): update_coords() ax.cla() # 重新设置固定坐标轴范围 ax.set_xlim(x_range) ax.set_ylim(y_range) ax.set_zlim(z_range) ax.scatter(coords[:, 0], coords[:, 1], coords[:, 2]) plt.draw() plt.pause(0.02)
方法二:不清空坐标轴,只移除旧散点
这种方式不用每次重置坐标轴设置,只需移除上一次绘制的散点,再画新的即可:
plt.ion() fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # 一次性设置好固定坐标轴范围 x_range = (-20, 20) y_range = (-20, 20) z_range = (-20, 20) ax.set_xlim(x_range) ax.set_ylim(y_range) ax.set_zlim(z_range) last_scatter = None # 保存上一次的散点对象 for t in np.arange(0, 10000, dt): update_coords() if last_scatter is not None: last_scatter.remove() # 移除旧散点 # 绘制新散点并保存对象 last_scatter = ax.scatter(coords[:, 0], coords[:, 1], coords[:, 2]) plt.draw() plt.pause(0.02)
两种方法都能让坐标轴保持固定长度,你可以根据习惯选择。如果不确定坐标范围,也可以先运行几次update_coords(),打印coords的极值来确定合适的范围值。
内容的提问来源于stack exchange,提问作者raziuuu
相关产品推荐
相关产品推荐

