此代码连接到MySQL并获取我使用pandas读取的数据集。一旦数据集在pandas数据帧中,我需要绘制它。但这会引发错误。这是片段
#!/usr/bin/python
import MySQLdb as mdb
import pandas as pd
import matplotlib.pyplot as plt
con = mdb.connect('hostname', 'username', 'password', 'database');
with con:
cur = con.cursor()
cur.execute("select month, post, comment, reply, dm, review")
rows = cur.fetchall()
df = pd.DataFrame( [[ij for ij in i] for i in rows] )
df.rename(columns={0: 'Month', 1: 'Post', 2: 'Comment', 3: 'Reply', 4: 'DM', 5: 'Review'}, inplace=True);
print(df.head(20))
df=df.set_index('Month')
df=df.astype(float)
df.plot(subplots=True)
plt.show()
Traceback (most recent call last):
File "random-exmaple.py", line 7, in <module>
plt.plot(x, y, "o")
File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3307, in plot
ax = gca()
File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 950, in gca
return gcf().gca(**kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 586, in gcf
return figure()
File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 535, in figure
**kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 81, in new_figure_manager
return new_figure_manager_given_figure(num, figure)
File "/usr/local/lib/python2.7/site-
packages/matplotlib/backends/backend_tkagg.py", line 89, in new_figure_manager_given_figure
window = Tk.Tk()
File "/usr/local/lib/python2.7/lib-tk/Tkinter.py", line 1745, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
如何解决这个问题?
答案 0 :(得分:0)
当我们尝试在未连接显示设备的远程计算机上运行GUI应用程序或绘制内容时,会出现此类错误。在这种情况下,您可以将图表保存在远程计算机上,并通过scp将它们复制到本地计算机上。你可以这样做:
保存地块:
ax = df.plot(subplots=True)
fig = ax.get_figure()
fig.savefig('plots_name.png')
将图像从远程计算机复制到本地目录:
scp {remote_username}@{remote_host}:{path_to_image} {path_to_local_directory}
其中{remote_host}
是您尝试连接的IP地址或域名,{remote_user}
是您在远程计算机上的用户名,{path_to_image}
是远程计算机上您想要的映像的路径复制(使用pwd
命令查找)和{path_to_local_directory}
是本地目录的路径,您希望在那里显示您的情节。
编辑:
对于新人。这是一个更复杂的解决方案。这个问题的作者提供了解决这个问题的简单解决方案。检查一下:Issue with tkinter, python and seaborn: _tkinter.TclError: no display name and no $DISPLAY environment variable