0
0
Matplotlibdata~30 mins

Interactive animation with widgets in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Interactive Animation with Widgets
📖 Scenario: You are working on a simple data visualization project where you want to animate a sine wave and control its frequency interactively using a slider widget. This will help you understand how changing parameters affect the wave in real time.
🎯 Goal: Build an interactive sine wave animation using matplotlib and a slider widget to control the frequency of the wave.
📋 What You'll Learn
Create a time array for the sine wave
Set an initial frequency value
Create an animation function that updates the sine wave
Add a slider widget to control the frequency interactively
Display the animated plot with the slider
💡 Why This Matters
🌍 Real World
Interactive animations help in exploring data and understanding how changing parameters affect results in real time, useful in education and presentations.
💼 Career
Data scientists and analysts often create interactive visualizations to communicate insights clearly and allow stakeholders to explore data dynamically.
Progress0 / 4 steps
1
Create the time array for the sine wave
Create a variable called t that is a NumPy array of 100 values evenly spaced between 0 and 2 * pi.
Matplotlib
Need a hint?

Use np.linspace to create evenly spaced values.

2
Set the initial frequency value
Create a variable called freq and set it to 1. This will be the initial frequency of the sine wave.
Matplotlib
Need a hint?

Just assign the number 1 to the variable freq.

3
Create the animation function and plot setup
Import matplotlib.pyplot as plt and matplotlib.animation as animation. Create a figure and axis using plt.subplots(). Plot the initial sine wave using ax.plot(t, np.sin(freq * t)) and save the line object as line. Define a function called update that takes a frame number frame and updates the y-data of line to np.sin(freq * t + 0.1 * frame). Create an animation object called ani using animation.FuncAnimation with the figure, update function, and 100 frames.
Matplotlib
Need a hint?

Use plt.subplots() to create the plot and animation.FuncAnimation to animate.

4
Add a slider widget to control frequency interactively
Import matplotlib.widgets.Slider. Create a slider axis below the plot using plt.axes([0.25, 0.02, 0.50, 0.03]). Create a slider called freq_slider with label 'Frequency', minimum 0.1, maximum 5, and initial value freq. Define a function called update_freq that takes a value val, updates the global variable freq to val, and updates the y-data of line to np.sin(freq * t). Connect freq_slider.on_changed(update_freq). Finally, call plt.show() to display the interactive plot.
Matplotlib
Need a hint?

Use Slider to add the slider and connect it with on_changed.