Updating bar and plot subplots over loop iterations

ⅰ亾dé卋堺 提交于 2019-12-02 10:54:42

Axes has a method clear() to achieve this.

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

But relim() will always adjust your dimension to the new data so you will get a static image. Instead I would use set_ylim([min, max]) to set a fix area of values.

Without the need to reset the axes limits or using relim, you may want to update the bar height only.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!