You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu系统运行Python matplotlib绘图程序无弹窗问题求助

Ubuntu环境Matplotlib调用plt.show()无弹窗故障修复

问题场景

运行Python基础折线图测试代码时,已安装相关Python依赖,但执行后无绘图窗口弹出,测试代码如下:

import matplotlib.pyplot as plt
  
# line 1 points
x1 = [1,2,3]
y1 = [2,4,1]
# plotting the line 1 points 
plt.plot(x1, y1, label = "line 1")
  
# line 2 points
x2 = [1,2,3]
y2 = [4,1,3]
# plotting the line 2 points 
plt.plot(x2, y2, label = "line 2")
  
# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
# giving a title to my graph
plt.title('Two lines on same graph!')
  
# show a legend on the plot
plt.legend()
  
# function to show the plot
plt.show()

修复步骤

  • 确认当前Matplotlib后端类型
    Matplotlib需要匹配GUI交互后端才能弹出绘图窗口,Ubuntu环境下默认可能加载了无界面渲染后端。执行以下代码查看当前生效后端:
    import matplotlib
    print(matplotlib.get_backend())
    
    如果输出结果为Agg、pdf、svg这类非交互后端,即可定位到故障原因。
  • 安装系统级GUI依赖
    仅通过pip安装matplotlib不会自动安装Ubuntu下的GUI框架依赖,执行以下终端命令安装必需组件:
    sudo apt update
    sudo apt install python3-tk tk-dev python3-gi python3-gi-cairo gir1.2-gtk-3.0
    
  • 显式指定交互后端
    依赖安装完成后,在导入pyplot前指定可用的TkAgg交互后端即可正常弹窗,修改后的代码开头如下:
    import matplotlib
    matplotlib.use('TkAgg')
    import matplotlib.pyplot as plt
    
    # 其余绘图逻辑保持原有代码不变
    
    如需永久生效,可修改Matplotlib全局配置:先执行print(matplotlib.matplotlib_fname())获取配置文件路径,打开路径下的matplotlibrc文件,找到被注释的#backend: Agg行,去掉开头的注释符,将值改为TkAgg,保存后重启Python环境即可。
  • 特殊运行环境适配
    • 若在WSL环境运行,需升级到WSL2并安装WSLg组件,或配置X11转发才能显示GUI窗口
    • 若通过SSH远程连接运行,连接时需添加-X参数开启X11转发,否则无法将窗口转发到本地显示

内容的提问来源于stack exchange,提问作者Chukwuemeka Elendu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 20:27:18