欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-03-18 23:35:54
...

【时间】2018.12.29

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

【参考链接】https://*.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