python生成统计图_用python Linux(无GUI)中生成统计图

我有这样一个需求:在我的raspberry pi 3中运行着一个爬虫程序,根据爬到的数据,使用matplotlib自动生成统计图(图片格式),然后发送到我的邮箱.

但是我ssh远程登录树莓派,运行如下脚本生成test.png图片时

import matplotlib.pyplot as plt

import numpy as np

import matplotlib

t = np.arange(0.0, 10.0, 0.001)

s = np.sin(2*np.pi*t)

plt.plot(t, s)

plt.xlabel('time (s)')

plt.ylabel('voltage (mV)')

plt.title('About as simple as it gets, folks')

plt.grid(True)

plt.savefig("test.png")

出现如下错误:

(process:2818): Gtk-WARNING **: Locale not supported by C library.

Using the fallback 'C' locale.

Unable to init server: Could not connect: Connection refused

Unable to init server: Could not connect: Connection refused

(simple_plot.py:2818): Gdk-CRITICAL **: gdk_cursor_new_for_display: assertion 'GDK_IS_DISPLAY (display)' failed

Traceback (most recent call last):

File "simple_plot.py", line 1, in <module>

import matplotlib.pyplot as plt

File "/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 114, in <module>

_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()

File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup

globals(),locals(),[backend_name],0)

File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3agg.py", line 11, in <module>

from . import backend_gtk3

File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3.py", line 58, in <module>

cursors.MOVE          : Gdk.Cursor.new(Gdk.CursorType.FLEUR),

TypeError: constructor returned NULL

而我在树莓派gui系统中运行上述脚本是可以生成test.png文件的。

所以上述错误只是出现在无gui的情况下,google了多个结果都没有解决方法。

使用python绘制统计图库(类似matplotlib)可以在无gui的情况下根据所给数据生成统计图(png,jpeg等等)。

或者有别的方法实现我上述需求。

import matplotlib

#matplotlib.use("Agg")

matplotlib.use("Pdf")

import matplotlib.pyplot as plt

import numpy as np

原因我在官网找到了下面这句话,解释了

matplotlib.use("Agg")

放在

import matplotlib.pyplot as plt

之前的原因。感谢@sPeng.使用

matplotlib.use("Pdf")

同样可以解决这个错误.

If you use the use() function, this must be done before importing matplotlib.pyplot. Calling use() after pyplot has been imported will have no effect. Using use() will require changes in your code if users want to use a different backend. Therefore, you should avoid explicitly calling use() unless absolutely necessary.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值