我写了下面的片段,我试图让它更新情节。 相反,我得到的是新图与旧图的重叠。 我研究了一下,发现我需要在当前轴上使用 relim() 和 autoscale_view(True,True,True)。 我仍然无法获得所需的行为。 有没有办法强制 pyplot 在调用 plt.draw() 之前删除/移除旧绘图?
import numpy as np
import matplotlib.pyplot as plt
import time
plt.ion()
a = np.arange(10)
fig,ax = plt.subplots(2,1)
plt.show()
for i in range(100):
b = np.arange(10) * np.random.randint(10)
ax[0].bar(a,b,align='center')
ax[0].relim()
ax[0].autoscale_view(True,True,True)
ax[1].plot(a,b,'r-')
ax[1].relim()
ax[1].autoscale_view(True,True,True)
plt.draw()
time.sleep(0.01)
plt.pause(0.001)
请您参考如下方法:
Axes 有一个方法 clear() 来实现这一点。
for i in range(100):
b = np.arange(10) * np.random.randint(10)
ax[0].clear()
ax[1].clear()
ax[0].bar(a,b,align='center')
# ...
但是 relim() 将始终根据新数据调整尺寸,因此您将获得静态图像。相反,我会使用 set_ylim([min, max]) 来设置值的固定区域。
