77histogram.
88"""
99
10+ import functools
11+
1012import matplotlib.pyplot as plt
1113import numpy as np
1214
1315import matplotlib.animation as animation
1416
15- # Fixing random state for reproducibility
16- np.random.seed( 19680801)
17- # Fixing bin edges
17+ # Setting up a random number generator with a fixed state for reproducibility.
18+ rng = np.random.default_rng(seed= 19680801)
19+ # Fixing bin edges.
1820HIST_BINS = np.linspace(-4, 4, 100)
1921
20- # histogram our data with numpy
21- data = np.random.randn (1000)
22+ # Histogram our data with numpy.
23+ data = rng.standard_normal (1000)
2224n, _ = np.histogram(data, HIST_BINS)
2325
2426# %%
2527# 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.
28+ # a random set of numbers and updates the heights of rectangles. The ``animate``
29+ # function updates the `.Rectangle` patches on an instance of `.BarContainer`.
2930
3031
31- def prepare_animation(bar_container):
32+ def animate(frame_number, bar_container):
33+ # Simulate new data coming in.
34+ data = rng.standard_normal(1000)
35+ n, _ = np.histogram(data, HIST_BINS)
36+ for count, rect in zip(n, bar_container.patches):
37+ rect.set_height(count)
3238
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
39+ return bar_container.patches
4140
4241# %%
4342# 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` .
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 .
4746
4847# Output generated via `matplotlib.animation.Animation.to_jshtml`.
4948
@@ -52,8 +51,8 @@ def animate(frame_number):
5251 ec="yellow", fc="green", alpha=0.5)
5352ax.set_ylim(top=55) # set safe limit to ensure that all data is visible.
5453
55- ani = animation.FuncAnimation(fig, prepare_animation( bar_container), 50,
56- repeat=False, blit=True)
54+ anim = functools.partial(animate, bar_container=bar_container)
55+ ani = animation.FuncAnimation(fig, anim, 50, repeat=False, blit=True)
5756plt.show()
5857
5958# %%
0 commit comments