Blitting for performance in Matplotlib - Time & Space Complexity
When drawing plots repeatedly, like in animations, the time it takes can grow quickly.
We want to see how using blitting changes the time needed as the plot updates.
Analyze the time complexity of this matplotlib animation code using blitting.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
line, = ax.plot([], [])
ax.set_xlim(0, 10)
ax.set_ylim(-1, 1)
x = np.linspace(0, 10, 1000)
def update(frame):
line.set_data(x, np.sin(x + frame / 10))
return line,
ani = FuncAnimation(fig, update, frames=100, blit=True)
plt.show()
This code updates a sine wave plot 100 times using blitting to redraw only changed parts.
Look at what repeats as the animation runs.
- Primary operation: Updating the y-data of the line and redrawing the changed area.
- How many times: 100 times, once per frame.
As the number of frames grows, the redraw work grows too, but blitting redraws only small parts.
| Input Size (frames) | Approx. Operations |
|---|---|
| 10 | 10 redraws of small area |
| 100 | 100 redraws of small area |
| 1000 | 1000 redraws of small area |
Pattern observation: The work grows linearly with frames, but each redraw is fast because only part of the plot updates.
Time Complexity: O(n)
This means the time to update the animation grows directly with the number of frames, but each update is efficient.
[X] Wrong: "Blitting redraws the whole plot every time, so it doesn't save time."
[OK] Correct: Blitting redraws only the parts that change, making each update faster than redrawing everything.
Understanding how blitting improves redraw speed shows you can think about efficient updates, a useful skill in data visualization and animation tasks.
"What if we turned off blitting and redrew the entire plot each frame? How would the time complexity change?"