Note

Go to the endto download the full example code.

Animated histogram#

Use histogram'sBarContainer to draw a bunch of rectangles for an animatedhistogram.

importfunctoolsimportmatplotlib.pyplotaspltimportnumpyasnpimportmatplotlib.animationasanimation# Setting up a random number generator with a fixed state for reproducibility.rng=np.random.default_rng(seed=19680801)# Fixing bin edges.HIST_BINS=np.linspace(-4,4,100)# Histogram our data with numpy.data=rng.standard_normal(1000)n,_=np.histogram(data,HIST_BINS)

To animate the histogram, we need ananimate function, which generatesa random set of numbers and updates the heights of rectangles. Theanimatefunction updates theRectangle patches on an instance ofBarContainer.

defanimate(frame_number,bar_container):# Simulate new data coming in.data=rng.standard_normal(1000)n,_=np.histogram(data,HIST_BINS)forcount,rectinzip(n,bar_container.patches):rect.set_height(count)returnbar_container.patches

Usinghist() allows us to get an instance ofBarContainer, which is a collection ofRectangle instances. SinceFuncAnimation will only pass the frame number parameter to the animationfunction, we usefunctools.partial to fix thebar_container parameter.

# Output generated via `matplotlib.animation.Animation.to_jshtml`.fig,ax=plt.subplots()_,_,bar_container=ax.hist(data,HIST_BINS,lw=1,ec="yellow",fc="green",alpha=0.5)ax.set_ylim(top=55)# set safe limit to ensure that all data is visible.anim=functools.partial(animate,bar_container=bar_container)ani=animation.FuncAnimation(fig,anim,50,repeat=False,blit=True)plt.show()

Tags:plot-type: histogramcomponent: animation

Total running time of the script: (0 minutes 7.059 seconds)

Gallery generated by Sphinx-Gallery