Skip to content

Commit 187341c

Browse files
vamshipystory645
andcommitted
example of animation update function tha takes arguments
Co-authored-by: hannah <story645@gmail.com>
1 parent 879bde7 commit 187341c

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
"""
2+
==================================
3+
Parameterized animation function
4+
==================================
5+
6+
7+
Create an `.FuncAnimation` animation updating function that takes as input the frame,
8+
objects being animated, and data set.
9+
"""
10+
11+
import functools
12+
13+
import matplotlib.pyplot as plt
14+
import numpy as np
15+
16+
import matplotlib.animation as animation
17+
18+
19+
def update(frame, line, text, decades, widgets_data):
20+
# frame (int): The current frame number.
21+
# line (Line2D): The line object to update.
22+
# text (Text): The text annotation object to update.
23+
# decades (numpy.ndarray): Array of decades.
24+
# widgets_data (numpy.ndarray): Array of widgets data.
25+
26+
current_decade = decades[frame]
27+
current_widgets = int(widgets_data[frame])
28+
29+
line.set_data(decades[:frame + 1], widgets_data[:frame + 1])
30+
text.set_text(f'Decade: {current_decade}\nNumber of Widgets: {current_widgets}')
31+
32+
return line, text
33+
34+
# Set up the animation
35+
36+
# Constants
37+
decades = np.arange(1940, 2020, 10)
38+
initial_widgets = 10000 # Rough estimate of the no. of widgets in the 1950s
39+
40+
# Generate rough growth data
41+
growth_rate = np.random.uniform(1.02, 3.10, size=len(decades))
42+
widgets_data = np.cumprod(growth_rate) * initial_widgets
43+
44+
# Set up the initial plot
45+
fig, ax = plt.subplots()
46+
47+
# create an empty line
48+
line, = ax.plot([], [])
49+
50+
# display the current decade
51+
text = ax.text(0.5, 0.85, '', transform=ax.transAxes,
52+
fontsize=12, ha='center', va='center')
53+
54+
ax.set(xlabel='Decade', ylabel='Number of Widgets',
55+
xlim=(1940, 2020),
56+
ylim=(0, max(widgets_data) + 100000))
57+
58+
59+
ani = animation.FuncAnimation(
60+
fig,
61+
# bind arguments to the update function, leave only frame unbound
62+
functools.partial(update, line=line, text=text,
63+
decades=decades, widgets_data=widgets_data),
64+
frames=len(decades),
65+
interval=1000,
66+
)
67+
68+
plt.show()

0 commit comments

Comments
 (0)