77histogram.
88"""
99
10+ import functools
11+
1012import matplotlib .pyplot as plt
1113import numpy as np
1214
2426# %%
2527# To animate the histogram, we need an ``animate`` function, which generates
2628# a random set of numbers and updates the heights of rectangles. The ``animate``
27- # function updates the `.Rectangle` patches on a global instance of
28- # `.BarContainer` (which in this case is defined below).
29+ # function updates the `.Rectangle` patches on an instance of `.BarContainer`.
2930
3031
31- def animate (frame_number ):
32+ def animate (frame_number , bar_container ):
3233 # Simulate new data coming in.
3334 data = rng .standard_normal (1000 )
3435 n , _ = np .histogram (data , HIST_BINS )
@@ -39,7 +40,9 @@ def animate(frame_number):
3940
4041# %%
4142# Using :func:`~matplotlib.pyplot.hist` allows us to get an instance of
42- # `.BarContainer`, which is a collection of `.Rectangle` instances.
43+ # `.BarContainer`, which is a collection of `.Rectangle` instances. Since
44+ # `.FuncAnimation` will only pass the frame number parameter to the animation
45+ # function, we use `functools.partial` to fix the ``bar_container``` parameter.
4346
4447# Output generated via `matplotlib.animation.Animation.to_jshtml`.
4548
@@ -48,7 +51,8 @@ def animate(frame_number):
4851 ec = "yellow" , fc = "green" , alpha = 0.5 )
4952ax .set_ylim (top = 55 ) # set safe limit to ensure that all data is visible.
5053
51- ani = animation .FuncAnimation (fig , animate , 50 , repeat = False , blit = True )
54+ anim = functools .partial (animate , bar_container = bar_container )
55+ ani = animation .FuncAnimation (fig , anim , 50 , repeat = False , blit = True )
5256plt .show ()
5357
5458# %%
0 commit comments