问题
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)
回答1:
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.
回答2:
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)
来源:https://stackoverflow.com/questions/35843885/updating-bar-and-plot-subplots-over-loop-iterations