|
| 1 | +""" |
| 2 | +================== |
| 3 | +Animated graph using funcAnimation |
| 4 | +================== |
| 5 | +use funcAnimation to create a graph of no of |
| 6 | +software engineers over the decades |
| 7 | +""" |
| 8 | +import matplotlib.pyplot as plt |
| 9 | +import matplotlib.animation as animation |
| 10 | +import numpy as np |
| 11 | + |
| 12 | +# Constants |
| 13 | +decades = np.arange(1940, 2020, 10) |
| 14 | +initial_engineers = 10000 # Rough estimate of the number of software engineers(not real) in the 1950s |
| 15 | + |
| 16 | +# Generate rough growth data |
| 17 | +growth_rate = np.random.uniform(1.02, 3.10, size=len(decades)) |
| 18 | +engineers_data = np.cumprod(growth_rate) * initial_engineers |
| 19 | + |
| 20 | +# Set up the initial plot |
| 21 | +fig, ax = plt.subplots() |
| 22 | +ax.set_xlim(1940, 2020) |
| 23 | +ax.set_ylim(0, max(engineers_data) + 100000) |
| 24 | +line, = ax.plot([], [], label='Software Engineers') |
| 25 | +ax.set_xlabel('Decade') |
| 26 | +ax.set_ylabel('Number of Software Engineers') |
| 27 | +ax.legend() |
| 28 | + |
| 29 | +# Text annotation to display the current decade |
| 30 | +text = ax.text(0.5, 0.85, '', transform=ax.transAxes, fontsize=12, ha='center', va='center') |
| 31 | + |
| 32 | +def update(frame, line, text, decades, engineers_data): |
| 33 | + """ |
| 34 | + Update function for FuncAnimation. |
| 35 | +
|
| 36 | + Parameters: |
| 37 | + frame (int): The current frame number. |
| 38 | + line (Line2D): The line object to update. |
| 39 | + text (Text): The text annotation object to update. |
| 40 | + decades (numpy.ndarray): Array of decades. |
| 41 | + engineers_data (numpy.ndarray): Array of software engineers' data. |
| 42 | +
|
| 43 | + Returns: |
| 44 | + tuple: Tuple containing the updated Line2D and Text objects. |
| 45 | + """ |
| 46 | + current_decade = decades[frame] |
| 47 | + current_engineers = int(engineers_data[frame]) |
| 48 | + |
| 49 | + line.set_data(decades[:frame + 1], engineers_data[:frame + 1]) |
| 50 | + |
| 51 | + text.set_text(f'Decade: {current_decade}\nEngineers: {current_engineers}') |
| 52 | + |
| 53 | + return line, text |
| 54 | + |
| 55 | +# Set up the animation |
| 56 | +ani = animation.FuncAnimation( |
| 57 | + fig, # Figure to update |
| 58 | + update, # Update function |
| 59 | + frames=len(decades), # Number of frames |
| 60 | + fargs=(line, text, decades, engineers_data), # Additional arguments for the update function |
| 61 | + interval=1000, # Delay between frames in milliseconds |
| 62 | + blit=False, # Whether to use blit for faster updates |
| 63 | +) |
| 64 | + |
| 65 | +plt.show() |
| 66 | + |
| 67 | + |
| 68 | + |
0 commit comments