Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to animate a sine curve in Matplotlib?
To create an animated sine curve in Matplotlib, we use the animation module to continuously update the curve's position. This creates a smooth wave motion effect by shifting the sine wave over time.
Steps to Create Animated Sine Curve
Follow these steps to animate a sine curve −
- Set the figure size and adjust the padding between and around the subplots
- Create a new figure and add axes with appropriate limits
- Initialize an empty line plot that will be updated during animation
- Define an initialization function to reset the line data
- Create an animation function that updates the sine curve values for each frame
- Use
FuncAnimationto create the animation with specified frames and interval - Display the animated figure using
show()method
Example
Here's how to create a smooth animated sine wave ?
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# Set figure parameters
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create figure and axes
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2, color='blue')
# Add labels and title
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title('Animated Sine Wave')
def init():
"""Initialize the line with empty data"""
line.set_data([], [])
return line,
def animate(frame):
"""Update the sine curve for each animation frame"""
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * frame))
line.set_data(x, y)
return line,
# Create animation
anim = animation.FuncAnimation(
fig, animate, init_func=init,
frames=200, interval=20, blit=True
)
plt.show()
How It Works
The animation works by continuously shifting the phase of the sine wave −
- init() function: Resets the line data to empty lists before animation starts
- animate() function: Called for each frame, updates the y-values by shifting the phase
-
Phase shift: The term
(x - 0.01 * frame)creates the leftward motion - FuncAnimation: Manages the animation loop with 200 frames at 20ms intervals
Parameters
| Parameter | Description | Value |
|---|---|---|
frames |
Number of animation frames | 200 |
interval |
Delay between frames (ms) | 20 |
blit |
Optimize drawing for better performance | True |
Output
The animation creates a smooth sine wave that moves continuously from right to left, creating a wave motion effect.
Conclusion
Use FuncAnimation with phase shifting to create smooth animated sine curves. The blit=True parameter optimizes performance by only redrawing changed parts of the plot.
Advertisements
