在循环迭代中更新条形图和图子图

Updating bar and plot subplots over loop iterations

我写了下面的片段,我试图让它更新情节。 相反,我得到的是新图与旧图的重叠。 我研究了一下,发现我在当前轴上需要 relim()autoscale_view(True,True,True)。 我仍然无法获得所需的行为。 有没有办法在调用 plt.draw() 之前强制 pyplot delete/remove 旧绘图?

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')
    # ...

Matplotlib Axes Documentation

但是 relim() 将始终根据新数据调整尺寸,因此您将获得静态图像。相反,我会使用 set_ylim([min, max]) 来设置值的固定区域。

无需重置轴限制或使用 relim,您可能只想更新条形高度。

import numpy as np
import matplotlib.pyplot as plt

plt.ion()
a = np.arange(10)

fig,ax = plt.subplots(2,1)
plt.show()

b = 10 * np.random.randint(0,10,size=10)
rects = ax[0].bar(a,b, align='center')
line, = ax[1].plot(a,b,'r-')
ax[0].set_ylim(0,100)
ax[1].set_ylim(0,100)

for i in range(100):
    b = 10 * np.random.randint(0,10,size=10)
    for rect, h in zip(rects, b):
        rect.set_height(h)
    line.set_data(a,b)
    plt.draw()
    plt.pause(0.02)