Skip to content
Latchkey

Python "matplotlib: no display, needs Agg backend" in CI

On a headless CI runner there is no display server, so matplotlib cannot use an interactive backend (TkAgg, Qt). Attempting to render raises, commonly a Tkinter "no display name" or "Invalid DISPLAY variable" error. The fix is the non-interactive Agg backend.

What this error means

A test fails with "_tkinter.TclError: no display name and no $DISPLAY environment variable" or "UserWarning: Matplotlib is currently using agg ... cannot show" on a runner with no GUI.

python
_tkinter.TclError: no display name and no $DISPLAY environment variable

Common causes

An interactive backend selected on a headless runner

matplotlib defaulted to a GUI backend that needs a display the CI runner does not provide.

plt.show() called in a headless test

Showing a figure requires a display; in CI this errors instead of opening a window.

How to fix it

Force the Agg backend before importing pyplot

  1. Set the backend to Agg before any pyplot import (env var or matplotlib.use).
  2. Save figures to files instead of calling plt.show() in tests.
  3. Set MPLBACKEND=Agg in the CI job environment as a belt-and-braces default.
Python
import matplotlib
matplotlib.use("Agg")  # before importing pyplot
import matplotlib.pyplot as plt

How to prevent it

  • Default to the Agg backend in headless CI via MPLBACKEND=Agg.
  • Save figures to disk; never call plt.show() in tests.
  • Set the backend before importing pyplot.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →