Updating bar and plot subplots over loop iterations

Viewed 6216

I wrote the following snippet and I am trying to make it update the plots. What I get instead is an overlapping of new plots on the old ones. I researched a bit and found I needed relim() and autoscale_view(True,True,True) on the current axis. I still cannot get the desired behaviour. Is there a way to force pyplot to delete/remove the old drawing before calling 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 Answers
Related