Matplotlib Server-Side Rendering: Agg Backend and Object-Oriented API for Headless Environments
Generate Matplotlib charts in containers, CI, or serverless functions by selecting the Agg backend before importing pyplot and using the object-oriented Figure API with explicit savefig and close calls.
06 Jul 2025, 22:59 UTC

The Problem and the Takeaway
Generating charts in containers, CI pipelines, or web workers fails when Matplotlib defaults to an interactive backend that requires a display server. The fix is twofold: select the Agg non-interactive backend before importing pyplot, and use the object-oriented Figure API instead of the pyplot state machine. This combination avoids RuntimeError: Invalid DISPLAY variable, prevents memory leaks in long-running processes, and keeps each request isolated in multi-threaded workers.
Why the Default Fails in Headless Environments
Matplotlib chooses a backend at first import. On a desktop, that's typically TkAgg, Qt5Agg, or MacOSX—all of which need a running X11/Wayland server. In a Docker container, Kubernetes pod, or serverless function, $DISPLAY is unset, so the first import matplotlib.pyplot raises an exception or hangs waiting for a GUI event loop that will never start.
The Agg backend (Anti-Grain Geometry) renders directly to raster or vector buffers—PNG, PDF, SVG, PS—without any window system. It is the only backend guaranteed to work everywhere Python runs.
Worked Example: Request-Scoped Chart Generation
The pattern below is safe for a Flask, FastAPI, or Celery worker that serves charts per HTTP request. It demonstrates the correct import order, object-oriented figure creation, rendering to an in-memory buffer, and explicit cleanup.
# chart_service.py
import io
import matplotlib
matplotlib.use('Agg') # Must be called BEFORE importing pyplot
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
def generate_timeseries_png(timestamps, values, title="Metric") -> bytes:
"""Return a PNG bytes object for a single time-series chart."""
# Create figure and axes explicitly—no pyplot state involved
fig = Figure(figsize=(10, 4), dpi=150)
ax = fig.add_subplot(111)
ax.plot(timestamps, values, linewidth=1.5, color='#2c7bb6')
ax.set_title(title, fontsize=12)
ax.set_xlabel('Time')
ax.set_ylabel('Value')
ax.grid(True, alpha=0.3)
fig.autofmt_xdate() # Rotate date labels
# Render to BytesIO buffer
buf = io.BytesIO()
fig.savefig(
buf,
format='png',
dpi=150,
bbox_inches='tight',
facecolor=fig.get_facecolor(),
edgecolor='none'
)
# Critical: close the figure to release memory
plt.close(fig)
buf.seek(0)
return buf.read()
# Example usage in a request handler
if __name__ == '__main__':
import datetime
now = datetime.datetime.now()
ts = [now + datetime.timedelta(hours=i) for i in range(24)]
vals = [20 + 5 * (i % 7) for i in range(24)]
png_bytes = generate_timeseries_png(ts, vals, "CPU Utilization")
print(f"Generated {len(png_bytes)} bytes, PNG magic: {png_bytes[:8].hex()}")
Key Points in the Example
- Backend selection first.
matplotlib.use('Agg')appears beforeimport matplotlib.pyplot. Oncepyplotis imported, the backend is locked; later calls are ignored or raiseValueError. - Object-oriented API.
Figure(figsize=(10,4), dpi=150)andfig.add_subplot(111)create a figure and axes without touchingpyplotglobal state. Noplt.figure(),plt.plot(), orplt.title(). - Explicit
savefigon the Figure.fig.savefig(buf, ...)writes to a file-like object. Parameters:dpi=150overrides the default 100 DPI for sharper output.bbox_inches='tight'trims excess whitespace around artists.format='png'is explicit; the backend also supportspdf,svg,ps.
- Deterministic cleanup.
plt.close(fig)releases the figure's memory immediately. In a loop or worker, omitting this causes RSS to grow until the process is OOM-killed.
Verifying the Backend and Output
Run these checks in your target environment (container, CI job, serverless) to confirm the setup works before deploying.
# 1. Confirm Agg is active
python -c "import matplotlib; print(matplotlib.get_backend())"
# Expected output: Agg
# 2. Smoke test PNG generation
python -c "
import io, matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1,2,3], [4,5,6])
buf = io.BytesIO()
fig.savefig(buf, format='png')
plt.close(fig)
buf.seek(0)
print('PNG magic:', buf.read(8).hex())
"
# Expected: PNG magic: 89504e470d0a1a0a
# 3. Memory leak test (run in a loop, watch RSS)
python -c "
import io, matplotlib, os
matplotlib.use('Agg')
import matplotlib.pyplot as plt
for i in range(1000):
fig, ax = plt.subplots()
ax.plot([i])
fig.savefig(io.BytesIO(), format='png')
plt.close(fig)
print('Loop completed without OOM')
"
Common Mistakes and How to Avoid Them
1. Calling matplotlib.use() After Importing Pyplot
# WRONG
import matplotlib.pyplot as plt
matplotlib.use('Agg') # Ignored or raises ValueError
# RIGHT
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
Place the backend selection at the very top of your entry point or in a dedicated matplotlib_config.py that is imported first.
2. Sharing a Global Figure Across Threads
# WRONG: global figure reused by concurrent requests
FIG, AX = plt.subplots()
def handle_request(data):
AX.clear()
AX.plot(data)
FIG.savefig(buf) # Race condition, corrupted output
# RIGHT: new figure per request
def handle_request(data):
fig = Figure()
ax = fig.add_subplot(111)
ax.plot(data)
fig.savefig(buf)
plt.close(fig)
pyplot maintains a global figure registry protected by a module-level lock, but Axes drawing operations are not thread-safe. Create and close a Figure inside each request scope.
3. Forgetting plt.close() in Loops or Workers
Each Figure holds references to its artists, renderers, and backend resources. Matplotlib's garbage collector eventually reclaims them, but not predictably. In a Celery task that generates 500 charts, the process RSS can exceed 2 GB before GC runs. Always call plt.close(fig) or plt.close('all') immediately after savefig.
4. bbox_inches='tight' Clipping Annotations or Colorbars
bbox_inches='tight' computes a tight bounding box around visible artists. Artists placed outside the initial axes limits (e.g., ax.annotate(..., xy=(1.1, 1.1)) or a colorbar created via fig.colorbar()) may be clipped. Fixes:
- Use
fig.tight_layout()orfig.subplots_adjust()beforesavefigto make room. - Pass
bbox_extra_artists=[annotation, colorbar]tosavefig. - Set
bbox_inches=None(default) and manage margins manually for reproducible dimensions.
5. Assuming Default DPI Is Sufficient
The default savefig.dpi is 100. For retina displays or print, set dpi=200 or higher in savefig or via matplotlib.rcParams['savefig.dpi'] = 200. Vector formats (PDF, SVG) are resolution-independent; DPI only affects raster backends.
Limitations of the Agg Backend
- No interactivity. No mouse zoom, pan, hover tooltips, or GUI event loops. If you need interactive charts in a browser, render to SVG and add JavaScript interactivity client-side, or use a library like Plotly/Bokeh that emits HTML/JS.
- No GUI widget integration. Cannot embed in Tkinter, Qt, or wxPython windows. For desktop apps, choose a GUI backend instead.
- Text rendering depends on system fonts. Agg uses FreeType. In minimal containers (e.g.,
python:3.12-slim), installfonts-dejavu-coreorfontconfigto avoid missing-glyph warnings and fallback to DejaVu Sans. - Performance. Agg is CPU-bound. For high-throughput services (hundreds of charts/second), consider offloading to a worker pool or using a faster rasterizer like
cairoviapycairo+matplotlib.backends.backend_cairo.
Production Checklist
- Add
matplotlib.use('Agg')to your application's bootstrap module (e.g.,app/__init__.pyorworker/bootstrap.py). - Ensure
fontconfigand a basic font package are installed in the container image. - Use
Figure+add_subplotexclusively; banplt.plot,plt.figure,plt.showin server code. - Wrap every chart function with
try/finally: plt.close(fig)or a context manager. - Set
rcParams['savefig.dpi'] = 150(or higher) globally if all outputs need higher resolution. - Load-test with a memory profiler (
mprof runortracemalloc) to confirm flat RSS over thousands of requests.
Minimal Dockerfile Snippet
FROM python:3.12-slim
# System deps for Agg + FreeType font rendering
RUN apt-get update && apt-get install -y --no-install-recommends \
libfreetype6 fontconfig fonts-dejavu-core \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
With the backend locked to Agg, the object-oriented API, and deterministic cleanup, Matplotlib becomes a reliable, thread-safe chart generator for any headless deployment.