Keywords: WSL | Matplotlib | X11 Server | Graphical Interface | Windows Subsystem for Linux
Abstract: This article provides a detailed solution for configuring Matplotlib graphical interface display in Windows Subsystem for Linux (WSL1 and WSL2) environments. By installing an X11 server (such as VcXsrv or Xming), setting the DISPLAY environment variable, and installing necessary dependencies, users can directly use plt.show() to display plots without modifying code to save images. The guide covers steps from basic setup to advanced troubleshooting, including special network configurations for WSL2, firewall settings, and common error handling, offering developers a reliable visualization workflow in cross-platform environments.
Introduction
When using Matplotlib for data visualization in Windows Subsystem for Linux (WSL), developers often encounter a common issue: by default, plt.show() cannot display graphical interfaces directly, requiring the use of the Agg backend to save image files instead. This limitation hinders interactive data analysis. Based on high-scoring answers from Stack Overflow, this article systematically explains how to configure an X11 server in WSL1 and WSL2 to enable native display of Matplotlib plots.
Core Principles and Configuration Steps
WSL does not include a graphical subsystem natively, so it relies on an X11 server to render graphics on the Windows side. X11 is a network-transparent windowing system that allows graphical applications to run remotely and display locally. The configuration process primarily involves three key steps: installing an X11 server, setting environment variables, and installing necessary dependencies.
Installing an X11 Server
First, install X11 server software on Windows. Recommended options include VcXsrv or Xming, both open-source tools. For VcXsrv, download it from SourceForge, run xlaunch.exe, select "Multiple windows" mode, and complete the setup with default settings. Once started, the X11 server will run in the background, listening for graphical requests from WSL.
Environment Variable Configuration
In the WSL terminal, set the DISPLAY environment variable to specify the X11 server address. For WSL1, use the local loopback address:
export DISPLAY=localhost:0.0Add this command to the ~/.bashrc file to make the configuration permanent. For WSL2, which runs in a virtual network, obtain the IP address dynamically from /etc/resolv.conf:
export DISPLAY=`grep -oP "(?<=nameserver ).+" /etc/resolv.conf`:0.0If the IP from this command is invalid, manually extract it using ifconfig:
export DISPLAY=$(ifconfig | grep inet | awk '{print $2}' | head -n 1 | awk '{print $0":0"}')Dependency Installation and Verification
Install necessary Python and graphical library dependencies in WSL. Update the package list and install python3-tk (adjust based on Python version):
sudo apt-get update
sudo apt-get install python3-tkEnsure Matplotlib is installed (via pip install matplotlib). Then, run the following test code to verify the configuration:
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
plt.plot(t, s)
plt.title('Test Plot Display')
plt.show()If configured correctly, a plot window will pop up on the Windows side.
Advanced Configuration and Troubleshooting
Firewall Settings
In Windows Security Center, ensure VcXsrv is allowed through the firewall. Go to "Windows Security → Firewall & network protection → Allow an app through firewall" and check both private and public network permissions for VcXsrv. The system may prompt for authorization when launching xlaunch for the first time.
Disabling Access Control
When starting VcXsrv, check "Disable access control" in the configuration interface to prevent permission errors that could cause connection failures.
Common Error Handling
If encountering a "couldn't connect to display" error, check the DISPLAY variable value:
echo $DISPLAYEnsure the IP address is correct and the X11 server is running. For WSL2, network configurations may change with system updates, requiring periodic verification.
Code Examples and Best Practices
The following example demonstrates how to use standard Matplotlib code for interactive plotting after configuration, without backend modifications:
import matplotlib
# No need to set Agg backend
matplotlib.use('TkAgg') # Optional, specify Tkinter backend
import matplotlib.pyplot as plt
import numpy as np
# Generate data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create plot
plt.figure(figsize=(8, 4))
plt.plot(x, y, label='sin(x)', color='blue')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
plt.grid(True)
# Display plot directly
plt.show()This code will directly open a plot window in a properly configured WSL environment, supporting interactive operations like zooming and saving.
Extended Applications and Alternatives
Beyond Matplotlib, this configuration supports other X11-based GUI applications, such as xeyes or GTK apps. Install the x11-apps package to extend functionality:
sudo apt-get install x11-appsRun xeyes to test; eye graphics will follow mouse movements. For more complex visualization needs, consider using Jupyter Notebook, which provides interactive plotting through a browser interface, avoiding X11 dependencies.
Conclusion
By configuring an X11 server and the DISPLAY environment variable, developers can seamlessly use Matplotlib's graphical interface in WSL. The steps provided in this article cover main scenarios for WSL1 and WSL2, including troubleshooting guidance, helping users quickly set up a cross-platform visualization environment. With native WSL GUI support in Windows 11, future configurations may simplify further, but the current solution remains effective for most users.