0
0
Matplotlibdata~5 mins

Blitting for performance in Matplotlib

Choose your learning style9 modes available
Introduction

Blitting helps redraw only parts of a plot that change. This makes animations or updates faster and smoother.

When you want to animate a plot smoothly without redrawing everything.
When updating only a small part of a graph repeatedly, like a moving point.
When working with large plots and want to save computer resources.
When creating interactive visualizations that change often.
When you want to improve performance in real-time data displays.
Syntax
Matplotlib
fig, ax = plt.subplots()
background = fig.canvas.copy_from_bbox(ax.bbox)
# Draw static elements here
fig.canvas.blit(ax.bbox)
# Update dynamic elements
fig.canvas.restore_region(background)
# Draw updated elements
ax.draw_artist(dynamic_element)
fig.canvas.blit(ax.bbox)
fig.canvas.flush_events()

copy_from_bbox saves the background image of the plot area.

blit redraws only the changed parts for better speed.

Examples
This example moves a red dot diagonally by updating only the dot's position.
Matplotlib
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
line, = ax.plot([], [], 'ro')
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)

background = fig.canvas.copy_from_bbox(ax.bbox)

for x in range(10):
    fig.canvas.restore_region(background)
    line.set_data(x, x)
    ax.draw_artist(line)
    fig.canvas.blit(ax.bbox)
    fig.canvas.flush_events()
Here, the static plot is drawn once and saved as background for future updates.
Matplotlib
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
background = fig.canvas.copy_from_bbox(ax.bbox)
# Static plot drawn once
fig.canvas.blit(ax.bbox)
Sample Program

This program animates a sine wave moving horizontally. It uses blitting to update only the sine wave line, making the animation smooth and fast.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np
import time

plt.ion()  # Turn on interactive mode
fig, ax = plt.subplots()
ax.set_xlim(0, 2 * np.pi)
ax.set_ylim(-1.5, 1.5)
line, = ax.plot([], [], 'b-')

x = np.linspace(0, 2 * np.pi, 100)

# Draw static elements
fig.canvas.draw()
background = fig.canvas.copy_from_bbox(ax.bbox)

for phase in np.linspace(0, 2 * np.pi, 60):
    fig.canvas.restore_region(background)
    y = np.sin(x + phase)
    line.set_data(x, y)
    ax.draw_artist(line)
    fig.canvas.blit(ax.bbox)
    fig.canvas.flush_events()
    time.sleep(0.05)

plt.ioff()
plt.show()
OutputSuccess
Important Notes

Blitting works best with simple animations where only small parts change.

Interactive mode (plt.ion()) helps to see updates live.

Not all backends support blitting; use one that does (like TkAgg).

Summary

Blitting redraws only changed parts of a plot for better speed.

It is useful for animations and interactive updates.

Use copy_from_bbox, restore_region, and blit methods together.