Explain Codes LogoExplain Codes Logo

Generating a PNG with matplotlib when DISPLAY is undefined

python
matplotlib
backend
testing
Nikita BarsukovbyNikita Barsukov·Jan 20, 2025
TLDR

To save a matplotlib plot as a PNG image on a server or a headless machine (i.e., no display attached), you can use the Agg backend, instead of the default one. This should be set at the beginning of any script that imports matplotlib.

import matplotlib matplotlib.use('Agg') # Switching to Plan B, No DISPLAY? No problem!

Now, you're all set! You can continue creating your plot and then save it using plt.savefig('output.png'). Here's your code shield against "No DISPLAY found!" errors.

import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) plt.savefig('output.png') # Save the day, and the plot!

This setup won't need a GUI or a display and will ensure your image gets saved directly as a file.

Permanent and Dynamic Setups

Maybe you want to armour-up and make this setting permanent for all your scripts? In that case, you can update your .matplotlibrc file like this:

backend: Agg

Not sure where to find this hidden .matplotlibrc file? Fret not, good samaritan! You can find its location using:

import matplotlib print(matplotlib.matplotlib_fname()) # Sherlock! Where's my .matplotlibrc?

If you want to take a quick detour and switch the backend temporarily, you can use an environment variable as MPLBACKEND=agg. This is a sneaky way to do it either in your shell or with Python's os module:

import os os.environ['MPLBACKEND'] = 'agg' # Asphalt works fine, but let's try out a dirt road!

Suit up! If you've already imported a module that uses a backend, you can just switch it to 'agg' using plt.switch_backend('agg'):

import matplotlib.pyplot as plt plt.switch_backend('agg') # Wrong turn? No problem, It's a U-turn!

The Backend in Flashlight

Every backend has its own role in the matplotlib universe. The Agg backend is like a silent guardian, rendering to a canvas without needing a windowing environment. Other backends like TkAgg, Qt4Agg, or WXAgg need a GUI, making them a bad candidate to trust when no display is available.

Automated Tests and Continuous Integration

The Agg backend is your secret sauce for preparing plots in automated testing environments or continuous integration (CI) systems. You can literally test your visualizations in absence of an X-window system. This can boost your workflow and automate testing or checking of plots.

Docker, VMs, and No Display

Working with containers (like Docker) or virtual machines (VMs) is another scenario where you might encounter the missing display issue. Fortunately, switching the backend to 'Agg' can help you sail smoothly through these headless environments.