使用matplotlib.pyplot画图时出现 couldn't connect to display "localhost:28.0" 错误的解决办法

【时间】2018.12.29

【题目】使用matplotlib.pyplot画图时出现 couldn't connect to display "localhost:28.0" 错误的解决办法

【参考链接】https://stackoverflow.com/questions/19518352/tkinter-tclerror-couldnt-connect-to-display-localhost18-0

 

【出现的错误】

Traceback (most recent call last):
  File "./ThrHomoHeatmap-thrstep.py", line 179, in <module>
    p = plt.imshow(board.T, cmap = plt.cm.gist_yarg_r, vmin=0, vmax=n, origin = 'lower',  extent = [0, phi, 0, Z], aspect='auto')
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2370, in imshow
    ax = gca()
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 701, in gca
    ax =  gcf().gca(**kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 369, in gcf
    return figure()
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 343, in figure
    **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 80, in new_figure_manager
    window = Tk.Tk()
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1688, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: couldn't connect to display "localhost:18.0"

 

【出现问题的原因】 问题在于,您使用的是一个交互式后端,它试图为您创建图形窗口,但由于您断开了启动模拟时可用的x服务器,所以失败了。

【解决方法】

使用非交互式后端(请参见后端?)比如:Agg(用于Png格式,PDF, SVG或PS。在生成图形的脚本中,只需在import matplotlib.pyplot as plt之前调用matplotlib.use()即可,具体如下:

将导入更改为

import matplotlib

matplotlib.use('AGG')#或者PDF, SVG或PS

import matplotlib.pyplot as plt

 

 

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值