循环迭代更新柱形图和折线图子图

3

我写了下面的代码片段,试图让它更新绘图。但实际上,新的图形会与旧的图形重叠在一起。我做了一些研究,发现我需要在当前轴上使用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)

output image

2个回答

1
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文档

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


1

无需重置轴限制或使用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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接