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
Creating 3D animation using matplotlib
To create a 3D animation using matplotlib, we can combine the power of mpl_toolkits.mplot3d for 3D plotting and matplotlib.animation for creating smooth animated sequences.
Required Imports
First, we need to import the necessary libraries ?
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from mpl_toolkits.mplot3d import Axes3D # Set figure size plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True
Creating the Animation Function
The animation function updates the 3D plot for each frame ?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
def animate(num, data, line):
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
line.set_color(colors[num % len(colors)])
line.set_alpha(0.7)
line.set_data(data[0:2, :num])
line.set_3d_properties(data[2, :num])
return line
# Generate parametric curve data
t = np.arange(0, 20, 0.2)
x = np.cos(t) - 1
y = 1 / 2 * (np.cos(2 * t) - 1)
data = np.array([x, y, t])
N = len(t)
# Create 3D figure and axis
fig = plt.figure()
ax = Axes3D(fig)
ax.axis('off')
# Initial plot
line, = plt.plot(data[0], data[1], data[2], lw=7, c='red')
# Create animation
line_ani = animation.FuncAnimation(fig, animate, frames=N,
fargs=(data, line), interval=50, blit=False)
plt.show()
How It Works
The animation creates a growing 3D parametric curve with the following key components:
- animate function: Updates the line data for each frame and changes colors cyclically
- Parametric equations: Generate x, y coordinates based on trigonometric functions with t as the parameter
- FuncAnimation: Calls the animate function repeatedly to create smooth animation
- set_3d_properties: Updates the z-axis data for the 3D line plot
Key Parameters
| Parameter | Purpose | Value |
|---|---|---|
| frames | Number of animation frames | N (length of data) |
| interval | Delay between frames (ms) | 50 |
| blit | Optimize drawing performance | False (for 3D compatibility) |
Output
The code produces an animated 3D parametric curve that grows progressively while cycling through different colors. The curve follows the mathematical equations defined by the cosine functions, creating a spiral-like pattern in 3D space.
Conclusion
Creating 3D animations in matplotlib combines parametric equations with FuncAnimation to produce dynamic visualizations. The key is defining an animate function that updates 3D properties progressively and using appropriate timing intervals for smooth playback.
