Matplotlib图未显示

时间:2017-06-13 09:19:49

标签: python matplotlib

我的项目要求我在我的Windows系统上使用putty和Connectify热点打开Raspberry Pi的终端来绘制和显示图形。但是,图表只能在我的Raspberry Pi显示器上显示,而不能在我的Window显示器上显示。这是我使用的代码:

import pymysql
import matplotlib
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd

conn = pymysql.connect(host="localhost", user="root", passwd="123456", db="XXX")

cur = conn.cursor()

query = """
SELECT data,time
FROM sensordata
WHERE time >= "2017-05-21"
  AND time < "2017-05-23"
"""


cur.execute(query)

data = cur.fetchall()

cur.close()
conn.close()

time,data= zip(*data)
plt.plot(data,time)

plt.title("XXX ")
plt.xlabel("Time & Date ")
plt.ylabel("Strength")
fig = plt.gcf()

fig.set_size_inches (55,27.5)
plt.grid(True)
plt.draw()
fig.savefig('test.png' ,dpi=100)
plt.show()

我尝试在putty终端上运行时收到的错误是:

Traceback (most recent call last):
  File "matplot2.py", line 27, in <module>
    plt.plot(data,time)
  File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 3092, in plot
    ax = gca()
  File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 828, in gca
    ax =  gcf().gca(**kwargs)
  File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 462, in gcf
    return figure()
  File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 435, in figure
    **kwargs)
  File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 81, in new_figure_manager
    return new_figure_manager_given_figure(num, figure)
  File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 89, in new_figure_manager_given_figure
    window = Tk.Tk()
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1813, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

我尝试过从我阅读的一些解决方案中使用matplotlib.use('Agg')matplotlib.use('TKAgg'),但它并没有解决我的问题。希望有人能够解决我的问题,以便我可以在我的Window监视器上显示图表...提前致谢

1 个答案:

答案 0 :(得分:2)

错误'_tkinter.TclError:没有显示名称且没有$ DISPLAY环境变量'表示您的X11服务器出现问题。

我不知道你在Raspberry上使用哪个主机,但你必须在Windows上运行X-Server(例如VcXsrv)。然后确保允许X11转发,例如ssh -X甚至是ssh -Y。使用putty时,请务必在Connection -> SSH -> X11下设置启用X11转发

如果全部设置完毕,运行matplotlib条形图演示(请参阅注释)应如下所示:

enter image description here (没有任何形象,因为有人因为某种原因低估了答案)

如果您的问题仍然存在,您可以尝试使用随X服务器一起提供的MobaXTerm(在Windows上),并且应该可以开箱即用。

如果您正在运行VcXSrv,对我来说,我必须通过在shell中运行以下代码来导出我的$ DISPLAY变量:export DISPLAY=localhost:0.0