12
12
13
13
import matplotlib .animation as animation
14
14
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.
18
18
HIST_BINS = np .linspace (- 4 , 4 , 100 )
19
19
20
- # histogram our data with numpy
21
- data = np . random . randn (1000 )
20
+ # Histogram our data with numpy.
21
+ data = rng . standard_normal (1000 )
22
22
n , _ = np .histogram (data , HIST_BINS )
23
23
24
24
# %%
25
25
# 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) .
29
29
30
30
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 )
32
37
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
41
39
42
40
# %%
43
41
# 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.
47
43
48
44
# Output generated via `matplotlib.animation.Animation.to_jshtml`.
49
45
@@ -52,8 +48,7 @@ def animate(frame_number):
52
48
ec = "yellow" , fc = "green" , alpha = 0.5 )
53
49
ax .set_ylim (top = 55 ) # set safe limit to ensure that all data is visible.
54
50
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 )
57
52
plt .show ()
58
53
59
54
# %%
0 commit comments