Matplotlib 3D动画坐标轴标签仅初始显示如何解决?
问题原因
代码中animate函数每次调用ax1.clear()会清空坐标轴上的所有元素,包括你在动画启动前设置的x/y/z轴标签,后续帧没有重新设置标签,就会出现仅首帧显示标签、后续标签消失的问题。
解决方案
方案1:清空后重新设置标签(修改成本最低)
每次清空坐标轴后重新添加标签即可,修改后的完整代码如下:
from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation np.set_printoptions(threshold=np.inf) fig = plt.figure() ax1 = fig.add_subplot(111, projection='3d') points = None def init(): global points points = np.loadtxt('Surface.txt') def animate(i): ax1.clear() # 重绘时重新设置坐标轴标签 ax1.set_xlabel('x') ax1.set_ylabel('y') ax1.set_zlabel('z') ax1.plot(points[:i, 0], points[:i, 1], points[:i, 2]) ani = animation.FuncAnimation(fig, animate, init_func=init, interval = 1000) plt.show()
方案2:更新线数据而非清空坐标轴(性能更优)
无需每次清空整个坐标轴,直接更新线对象的数据源即可,既不会丢失预设置的标签,也能提升动画运行性能,适合数据量更大、帧率更高的场景:
from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation np.set_printoptions(threshold=np.inf) fig = plt.figure() ax1 = fig.add_subplot(111, projection='3d') # 提前一次性设置标签,后续无需重复设置 ax1.set_xlabel('x') ax1.set_ylabel('y') ax1.set_zlabel('z') # 创建空的3D线对象 line, = ax1.plot([], [], []) points = None def init(): global points points = np.loadtxt('Surface.txt') # 固定坐标轴范围,避免每帧自动缩放导致视角跳动 ax1.set_xlim(points[:,0].min(), points[:,0].max()) ax1.set_ylim(points[:,1].min(), points[:,1].max()) ax1.set_zlim(points[:,2].min(), points[:,2].max()) return line, def animate(i): # 直接更新线的坐标数据,不需要清空坐标轴 line.set_data(points[:i, 0], points[:i, 1]) line.set_3d_properties(points[:i, 2]) return line, # 开启blit优化,仅重绘变化的元素 ani = animation.FuncAnimation(fig, animate, init_func=init, interval = 1000, blit=True) plt.show()
内容的提问来源于stack exchange,提问作者Koh Kheng Hong
相关产品推荐
相关产品推荐

