Automatic detection of display availability with Matplotlib

To detect display availability with Matplotlib, you need to check if a graphical display is available before creating plots. This is especially important when running Python scripts on servers or headless systems.

Steps

  • Import the os module to access environment variables.

  • Use os.environ.get("DISPLAY") to check for available display.

  • Handle cases where no display is available by setting appropriate backend.

Basic Display Detection

Here's how to check if a display is available ?

import os

display = os.environ.get("DISPLAY")

if display:
    print(f"Display available: {display}")
else:
    print("No display available")
Display available: :0

Automatic Backend Selection

You can automatically set the appropriate Matplotlib backend based on display availability ?

import os
import matplotlib

# Check display availability
if not os.environ.get("DISPLAY"):
    print("No display detected - using non-interactive backend")
    matplotlib.use('Agg')  # Non-interactive backend
else:
    print("Display detected - using default backend")

import matplotlib.pyplot as plt
import numpy as np

# Create a simple plot
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure(figsize=(8, 4))
plt.plot(x, y)
plt.title("Sample Plot")
plt.xlabel("X values")
plt.ylabel("Y values")

# Save instead of show when no display
if not os.environ.get("DISPLAY"):
    plt.savefig('plot.png')
    print("Plot saved as plot.png")
else:
    plt.show()
    print("Plot displayed")
Display detected - using default backend
Plot displayed

Complete Detection Function

Here's a robust function to handle display detection and backend configuration ?

import os
import matplotlib

def setup_display():
    """Detect display and configure matplotlib backend accordingly"""
    display = os.environ.get("DISPLAY")
    
    if display:
        print(f"Display found: {display}")
        return True
    else:
        print("No display found - configuring for headless mode")
        matplotlib.use('Agg')
        return False

# Use the function
has_display = setup_display()

import matplotlib.pyplot as plt
import numpy as np

# Create plot
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 1, 5, 3])

plt.figure()
plt.bar(x, y)
plt.title("Bar Chart Example")

if has_display:
    plt.show()
else:
    plt.savefig('chart.png', dpi=150, bbox_inches='tight')
    print("Chart saved as chart.png")
Display found: :0

Common Backends

Backend Type Use Case
Agg Non-interactive Headless servers, file output
Qt5Agg Interactive Desktop applications
TkAgg Interactive Cross-platform GUI

Conclusion

Use os.environ.get("DISPLAY") to detect display availability and configure Matplotlib backends accordingly. This ensures your plotting code works both in interactive and headless environments.

Updated on: 2026-03-25T21:50:45+05:30

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements