我试图在中央服务器上运行模拟(用python编写),当模拟完成后,通过连接到我的本地PC将保存的图形文件/保存的数据文件移动到我的本地PC。代码如下:
import matplotlib.pyplot as plt
import subprocess
import scipy.io
import os
#Save data file:
scipy.io.savemat(data_path + Filename_str, dict(A=board))
#Create / Save figure by using imshow (Heatmap)
p = plt.imshow(mean_map.T, cmap = plt.cm.gist_yarg_r, origin = 'lower', extent = [0, phi, 0, Z], aspect='auto')
plt.savefig(figure_path + Filename_str + '-Homophily.pdf')
# Connect to my local host (arabian-knights) using ssh, and follow command.
ret = subprocess.call(['ssh', 'arabian-knights', 'mv Data/* /scratch/Data/'])
ret = subprocess.call(['ssh', 'arabian-knights', 'mv Figure/* /scratch/Figure/'])
我从本地计算机(阿拉伯骑士)连接到服务器计算机后,在服务器计算机的后台运行此模拟。即使我关闭与服务器计算机的连接,因为模拟在后台运行,它不会停止,并且模拟完成后数据文件正确地移动到我的本地计算机。但是,图文件(由 matplotlib.pyplot.imshow 生成)未保存,显示以下错误消息:
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"
是否有人可以解决此问题,将matplotlib.pyplot图形文件从服务器移动到本地计算机?
答案 0 :(得分:23)
问题是您正在使用交互式后端,它正在尝试为您创建图形窗口,因为您已经断开了启动模拟时可用的x-server,因此失败了。
将导入更改为
import matplotlib
matplotlib.use('pdf')
import matplotlib.pyplot as plt
答案 1 :(得分:12)
在没有窗口的情况下生成图像(背景)
使用非交互式后端(请参阅什么是backend?),例如Agg
(适用于PNG
s),PDF
,SVG
或PS
。在您的图形生成脚本中,只需在导入matplotlib.use()
或pylab
之前调用pyplot
指令:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('myfig')
注意:评论中简要提到了这个答案。我把它放在这里作为提高可见度的答案,因为它帮助了我,我很幸运,我决定阅读评论。