Matplotlib
02 / 02

Backends, Memory & Performance

Backends, Memory & Performance

Headless Servers — the Agg Backend

import matplotlib
matplotlib.use('Agg')  # MUST be set before importing pyplot
import matplotlib.pyplot as plt

# Interactive GUI backends (TkAgg, Qt5Agg) need a display server that
# doesn't exist on a headless server/CI runner — plt.show() would hang.
# Agg renders purely to an in-memory buffer, correct for savefig()-only use.
plt.plot(x, y)
plt.savefig('chart.png')

Closing Figures in a Loop

for name, df in datasets.items():
    fig, ax = plt.subplots()
    ax.plot(df['x'], df['y'])
    fig.savefig(f'{name}.png')
    plt.close(fig)  # WITHOUT this, every figure stays in memory even
                    # after saving — hundreds of iterations exhaust memory

Large Datasets

# Millions of individual points slow down rendering significantly.
# Show DENSITY instead of every point:
plt.hexbin(x, y, gridsize=50, cmap='viridis')
plt.hist2d(x, y, bins=50)

# Or rasterize a specific element even in an otherwise vector (PDF/SVG) export
ax.scatter(x, y, rasterized=True)

pandas Integration

# df.plot() is a thin wrapper — returns a real Matplotlib Axes,
# customizable with standard plt.*/ax.* calls afterward
ax = df.plot(x='date', y='revenue', kind='line')
ax.set_title('Revenue Over Time')
ax.grid(True)

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free