Sphere
Log in Join

Matplotlib 'No display name and no $DISPLAY environment variable' on a headless server

The plot-rendering cron job worked on my laptop and failed on the server, which is the most annoying kind of bug. The server is Ubuntu 22.04, no desktop, Python 3.11 with matplotlib 3.8.2 installed from pip. First run produced this:

Traceback (most recent call last):
File "/srv/reports/make_plot.py", line 4, in <module>
import matplotlib.pyplot as plt
File "/home/deploy/.local/lib/python3.11/site-packages/matplotlib/pyplot.py", line 151, in <module>
import matplotlib.backends.backend_tkagg
File "/home/deploy/.local/lib/python3.11/site-packages/matplotlib/backends/backend_tkagg.py", line 7, in <module>
from . import _tkagg
matplotlib.backends.backend_tkagg.TkBackend: Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running

Older versions gave a shorter and more famous version of this: _tkinter.TclError: no display name and no $DISPLAY environment variable.

## Why pyplot guessed TkAgg

matplotlib picks a backend at import time. It checks whether a GUI framework is available and whether a display is configured. My laptop has Tk installed and a DISPLAY, so TkAgg wins. The server has neither, but it does have tkinter installed (pulled in by some unrelated notebook dependency), so matplotlib tries TkAgg and then fails when there's no X server behind it.

The fix is to pick a non-interactive backend explicitly, before pyplot is imported. That ordering is the part people get wrong.

## Setting Agg the right way

At the very top of the script, above every other matplotlib import:

python
import matplotlib
matplotlib.use("Agg") # must come before pyplot
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot([1, 2, 3], [4, 5, 6])
fig.savefig("/srv/reports/out.png", dpi=150)

Or set it from the environment, which is handy when you can't edit the script:

bash
export MPLBACKEND=Agg
python /srv/reports/make_plot.py

MPLBACKEND is read on import, so it has the same effect as matplotlib.use() but without touching code. We put it in the cron entry. One caveat: calling matplotlib.use() after importing pyplot is too late, and matplotlib prints a message saying so but carries on with the wrong backend. The environment variable avoids that whole class of ordering mistake because it's read before any of your code runs.

## Check what backend you actually got

Confusingly, a wrong backend can survive until you call plt.show(), which never happens in a batch job. So a script can "work" while doing something odd. Print it once:

python
import matplotlib
print(matplotlib.get_backend()) # should print 'agg'

It prints lowercase agg for the Agg backend. If it prints module://matplotlib_inline.backend_inline you're running under Jupyter; if it prints TkAgg you're still going to have a bad time on the server.

## The Docker case

If you're rendering in a container, install only what you need. There's no reason to carry Tk:

dockerfile
RUN pip install --no-cache-dir matplotlib==3.8.2
ENV MPLBACKEND=Agg

Don't apt-get install python3-tk "just in case". That's what caused the misdetection in the first place, and it adds a surprising amount of image weight.

One more thing: if you use plt.show() anywhere in a shared module, delete it. In a headless job it's a no-op under Agg at best, and a crash under anything else. We had one buried in a helper that only ran on Mondays, which is why this took two weeks to show up.