Matplotlib selects a GUI backend when DISPLAY exists but no X server runs
0 reputation · 29 May 2023, 14:19 UTC
0 reputation · 29 May 2023, 14:19 UTC
Matplotlib's backend selection prefers a GUI backend when the DISPLAY environment variable is set, a behavior introduced in version 3.5. In headless continuous integration, DISPLAY can exist without an active X server, so the chosen backend may import successfully but fail when a figure is created or drawn. The auto backend option added in version 3.6 verifies only that the backend module imports; it does not confirm that window creation or interactive drawing works at runtime.
The goal is to diagnose whether matplotlib can fall back to a non-GUI backend automatically when DISPLAY advertises a display that cannot actually be used, without requiring manual backend overrides before importing pyplot.
No. Matplotlib does not distinguish import-time backend availability from runtime display capability. There is no supported configuration that makes backend selection validate a usable X display before pyplot is imported. You cannot determine from the backend name alone whether interactive calls will fail or produce no visible output; you must either pin a non-GUI backend or probe at runtime.
Established behavior: backend selection occurs at import time. Starting with Matplotlib 3.5, the library prefers a GUI backend whenever DISPLAY is set. The auto backend added in 3.6 only checks that the backend module imports; it does not open a window or verify that drawing works.
Likely explanation: CI exports DISPLAY, but no X server is listening on that address. Pyplot imports successfully, yet creating or drawing a figure fails later because the backend cannot connect to the display.
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import os
import matplotlib
if os.environ.get("CI") == "true":
matplotlib.use("Agg")
import matplotlib.pyplot as plt
python -c "import matplotlib; print(matplotlib.get_backend())"
python - <<'PY'
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0, 1], [0, 1])
fig.savefig("/tmp/matplotlib-probe.png")
print(matplotlib.get_backend())
PY
Which Matplotlib version is installed? The GUI preference described here applies to version 3.5 and later; earlier versions defaulted to Agg even when DISPLAY was set. The fix is the same for 3.6+, but the version determines whether the behavior is expected.
Assumption: this covers CPython with the standard Matplotlib wheel; platform-specific Qt or Tk availability is not addressed.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.