WSL环境下无法运行Matplotlib绘图代码的问题求助
问题描述
在VS Code中使用WSL:Ubuntu-18.04和Python3,运行以下Matplotlib绘图代码:
import matplotlib.pyplot as plt import numpy as np # Data for plotting t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='About as simple as it gets, folks') ax.grid() fig.savefig("test.png") plt.show()
出现报错:
Traceback (most recent call last): File "/home/megamero/Codes/Python/Tkinter/matplot.py", line 8, in <module> fig, ax = plt.subplots() File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 1176, in subplots fig = figure(**fig_kw) File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 539, in figure **kwargs) File "/usr/lib/python3/dist-packages/matplotlib/backend_bases.py", line 171, in new_figure_manager return cls.new_figure_manager_given_figure(num, fig) File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 1049, in new_figure_manager_given_figure window = Tk.Tk(className="matplotlib") File "/usr/lib/python3.6/tkinter/__init__.py", line 2023, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: no display name and no $DISPLAY environment variable
此前尝试结合Matplotlib与Tkinter时,导入from matplotlib.backends.backend_tkagg import NavigationToolbar2Tk出现ImportError: cannot import name 'NavigationToolbar2Tk'错误,后续用matplotlib.use("TkAgg")修改配置未解决,现在基础绘图也无法运行。
解决思路
一、解决$DISPLAY环境变量缺失问题(核心)
WSL默认无图形界面,Matplotlib调用plt.show()需要转发图形到Windows显示服务:
- 安装Windows端X服务器(如VcXsrv),启动时勾选Disable access control避免权限问题。
- 在WSL中配置DISPLAY变量:
- 临时生效:终端执行
export DISPLAY=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2}'):0 - 永久生效:编辑
~/.bashrc(或~/.zshrc,依使用的shell而定),添加上述命令,再执行source ~/.bashrc使配置生效。
- 临时生效:终端执行
二、修复NavigationToolbar2Tk导入错误
Ubuntu 18.04自带的Matplotlib版本较低(约2.2.x),存在API路径差异:
- 替换导入语句:改为
from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg as NavigationToolbar2Tk - 升级Matplotlib(推荐):执行
sudo pip3 install --upgrade matplotlib升级到3.x版本,之后可正常使用原导入语句。
三、临时绕过GUI显示(仅保存图片场景)
若只需保存图片无需显示,可将Matplotlib后端设为非交互式:
在代码开头添加:
import matplotlib matplotlib.use('Agg')
此配置会忽略plt.show(),仅执行fig.savefig("test.png"),适合无图形界面需求的场景。
内容的提问来源于stack exchange,提问作者neil_huygens
相关产品推荐
相关产品推荐

