Generating a PNG with matplotlib when DISPLAY is undefined
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.
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.
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:
Not sure where to find this hidden .matplotlibrc
file? Fret not, good samaritan! You can find its location using:
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:
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')
:
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.
Was this article helpful?