1212
1313import matplotlib .animation as animation
1414
15- # Fixing random state for reproducibility
16- np .random .seed ( 19680801 )
17- # Fixing bin edges
15+ # Setting up a random number generator with a fixed state for reproducibility.
16+ rng = np .random .default_rng ( seed = 19680801 )
17+ # Fixing bin edges.
1818HIST_BINS = np .linspace (- 4 , 4 , 100 )
1919
20- # histogram our data with numpy
21- data = np . random . randn (1000 )
20+ # Histogram our data with numpy.
21+ data = rng . standard_normal (1000 )
2222n , _ = np .histogram (data , HIST_BINS )
2323
2424# %%
2525# To animate the histogram, we need an ``animate`` function, which generates
26- # a random set of numbers and updates the heights of rectangles. We utilize a
27- # python closure to track an instance of `.BarContainer` whose `.Rectangle`
28- # patches we shall update .
26+ # 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) .
2929
3030
31- def prepare_animation (bar_container ):
31+ def animate (frame_number ):
32+ # Simulate new data coming in.
33+ data = rng .standard_normal (1000 )
34+ n , _ = np .histogram (data , HIST_BINS )
35+ for count , rect in zip (n , bar_container .patches ):
36+ rect .set_height (count )
3237
33- def animate (frame_number ):
34- # simulate new data coming in
35- data = np .random .randn (1000 )
36- n , _ = np .histogram (data , HIST_BINS )
37- for count , rect in zip (n , bar_container .patches ):
38- rect .set_height (count )
39- return bar_container .patches
40- return animate
38+ return bar_container .patches
4139
4240# %%
4341# Using :func:`~matplotlib.pyplot.hist` allows us to get an instance of
44- # `.BarContainer`, which is a collection of `.Rectangle` instances. Calling
45- # ``prepare_animation`` will define ``animate`` function working with supplied
46- # `.BarContainer`, all this is used to setup `.FuncAnimation`.
42+ # `.BarContainer`, which is a collection of `.Rectangle` instances.
4743
4844# Output generated via `matplotlib.animation.Animation.to_jshtml`.
4945
@@ -52,8 +48,7 @@ def animate(frame_number):
5248 ec = "yellow" , fc = "green" , alpha = 0.5 )
5349ax .set_ylim (top = 55 ) # set safe limit to ensure that all data is visible.
5450
55- ani = animation .FuncAnimation (fig , prepare_animation (bar_container ), 50 ,
56- repeat = False , blit = True )
51+ ani = animation .FuncAnimation (fig , animate , 50 , repeat = False , blit = True )
5752plt .show ()
5853
5954# %%
0 commit comments