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
Saving scatterplot animations with matplotlib
To save scatterplot animations with matplotlib, we need to create an animation loop that generates multiple frames and exports them as a video file or GIF. This technique is useful for visualizing data that changes over time or showing algorithmic processes.
Basic Setup
First, let's set up the required imports and create sample data for our animation ?
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Animation parameters
steps = 50
nodes = 100
positions = []
solutions = []
# Generate random data for each frame
for i in range(steps):
positions.append(np.random.rand(2, nodes))
solutions.append(np.random.random(nodes))
print(f"Generated {steps} frames with {nodes} points each")
Generated 50 frames with 100 points each
Creating the Animation
Now we'll create the animation function and save it as a GIF file ?
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
# Setup
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
steps = 50
nodes = 100
positions = []
solutions = []
# Generate data
for i in range(steps):
positions.append(np.random.rand(2, nodes))
solutions.append(np.random.random(nodes))
# Create figure and axis
fig, ax = plt.subplots()
marker_size = 50
def animate(i):
fig.clear()
ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=(0, 1), ylim=(0, 1))
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_title(f'Frame {i+1}/{steps}')
# Create scatter plot with color mapping
scatter = ax.scatter(positions[i][0], positions[i][1],
s=marker_size, c=solutions[i],
cmap="RdBu_r", marker="o", edgecolor='black')
# Add colorbar for reference
plt.colorbar(scatter, ax=ax)
# Create animation
plt.grid(True)
ani = animation.FuncAnimation(fig, animate, interval=100, frames=range(steps))
# Save as GIF
ani.save('scatterplot_animation.gif', writer='pillow')
print("Animation saved as 'scatterplot_animation.gif'")
Animation saved as 'scatterplot_animation.gif'
Key Parameters
Understanding the important parameters for creating smooth animations ?
| Parameter | Purpose | Typical Values |
|---|---|---|
interval |
Delay between frames (ms) | 50-200ms |
frames |
Number of animation frames | 20-100 |
writer |
Output format handler | 'pillow', 'ffmpeg' |
cmap |
Color mapping scheme | 'viridis', 'RdBu_r' |
Alternative Save Formats
You can save animations in different formats depending on your needs ?
# Save as MP4 (requires ffmpeg)
ani.save('animation.mp4', writer='ffmpeg', fps=10)
# Save as HTML with JavaScript controls
ani.save('animation.html', writer='html')
# Save individual frames as images
for i, frame in enumerate(range(steps)):
animate(frame)
plt.savefig(f'frame_{i:03d}.png', dpi=150, bbox_inches='tight')
Conclusion
Saving matplotlib scatterplot animations involves creating a function that updates the plot for each frame and using FuncAnimation with the save() method. Choose appropriate intervals and file formats based on your specific visualization needs.
