python生成统计图_用python Linux(无GUI)中生成统计图
我有這樣一個需求:在我的raspberry pi 3中運行著一個爬蟲程序,根據(jù)爬到的數(shù)據(jù),使用matplotlib自動生成統(tǒng)計圖(圖片格式),然后發(fā)送到我的郵箱.
但是我ssh遠(yuǎn)程登錄樹莓派,運行如下腳本生成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")
出現(xiàn)如下錯誤:
(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系統(tǒng)中運行上述腳本是可以生成test.png文件的。
所以上述錯誤只是出現(xiàn)在無gui的情況下,google了多個結(jié)果都沒有解決方法。
使用python繪制統(tǒng)計圖庫(類似matplotlib)可以在無gui的情況下根據(jù)所給數(shù)據(jù)生成統(tǒng)計圖(png,jpeg等等)。
或者有別的方法實現(xiàn)我上述需求。
import matplotlib
#matplotlib.use("Agg")
matplotlib.use("Pdf")
import matplotlib.pyplot as plt
import numpy as np
原因我在官網(wǎng)找到了下面這句話,解釋了
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.
總結(jié)
以上是生活随笔為你收集整理的python生成统计图_用python Linux(无GUI)中生成统计图的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bp神经网络权值调整公式,bp神经网络算
- 下一篇: Linux FFmpeg依赖库编译