Home >Backend Development >Python Tutorial >How to Generate PNGs with Matplotlib in a Headless Environment?
The error message indicates that matplotlib is trying to use an interactive backend, which requires a display. However, the DISPLAY environment variable is not set. Setting matplotlib's backend to Agg (non-interactive) can resolve this error.
Import matplotlib and force it to use the Agg backend before importing any other matplotlib module:
import matplotlib # Force matplotlib to not use any Xwindows backend. matplotlib.use('Agg')
This ensures that matplotlib uses a non-interactive backend, eliminating the dependency on a display.
Alternatively, set the backend in your ~/.matplotlibrc configuration file:
backend: Agg
To use the Agg backend without adding any lines of code, create or edit the configuration file (~/.matplotlibrc) with the following content:
backend: Agg
By ensuring that matplotlib uses a non-interactive backend, you can generate PNG files without requiring a display. This solution is particularly useful when running scripts on servers or in headless environments where a display is not available.
The above is the detailed content of How to Generate PNGs with Matplotlib in a Headless Environment?. For more information, please follow other related articles on the PHP Chinese website!