在数据挖掘、数据分析领域里面,常常须要对处理后获得的数据进行可视化的呈现,这是一种更为直观、更为清晰的表达方式,让接受者能够更加直观的把握总体数据的分布或者走向等信息。在linux系统下使用python的matplotlib模块来画图出现一个问题以下:python
>>> import matplotlib.pyplot as plt
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib64/python2.7/site-packages/matplotlib/pyplot.py", line 97, in
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/__init__.py", line 25, in pylab_setup
globals(),locals(),[backend_name])
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_gtkagg.py", line 10, in
from matplotlib.backends.backend_gtk import gtk, FigureManagerGTK, FigureCanvasGTK,\
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_gtk.py", line 13, in
import gtk; gdk = gtk.gdk
File "/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py", line 64, in
_init()
File "/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py", line 52, in _init
_gtk.init_check()
RuntimeError: could not open display
linux
这是display错误,以前的解决办法是在网上查资料获得的,使用的是Xmanger这个小软件,成功了链接了本地和虚拟机,能够在虚拟机终端的形式下输出图片,也能够保存、展现,可是不知道为何,最近再次使用这个matplotlib模块画图的时候出现一样的错误,Xmanger也很差使了,暂时仍是不知道怎么回事,没有办法只好另寻出路了python2.7
记得以前查资料的时候有一个解决方案使用的是添加一行代码的形式,忘记了添加的是什么了索性直接查一下资料,获得以下的解决方法:spa
>>> import matplotlib as mpl
>>> mpl.use('Agg')
>>> import matplotlib.pyplot as plt 试验一下,果真奏效,简单来画一幅图片:
#!/usr/bin/env python
#coding:utf-8
import matplotlib as mpl
mpl.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(-1, 2, .01)
s = np.sin(2 * np.pi * t)
plt.plot(t,s)
# draw a thick red hline at y=0 that spans the xrange
l = plt.axhline(linewidth=4, color='r')
plt.axis([-1, 2, -1, 2])
plt.show()
plt.close()
# draw a default hline at y=1 that spans the xrange
plt.plot(t,s)
l = plt.axhline(y=1, color='b')
plt.axis([-1, 2, -1, 2])
plt.show()
plt.close()
# draw a thick blue vline at x=0 that spans the upper quadrant of the yrange
plt.plot(t,s)
l = plt.axvline(x=0, ymin=0, linewidth=4, color='b')
plt.axis([-1, 2, -1, 2])
plt.show()
plt.close()
# draw a default hline at y=.5 that spans the the middle half of the axes
plt.plot(t,s)
l = plt.axhline(y=.5, xmin=0.25, xmax=0.75)
plt.axis([-1, 2, -1, 2])
plt.show()
plt.close()
plt.plot(t,s)
p = plt.axhspan(0.25, 0.75, facecolor='0.5', alpha=0.5)
p = plt.axvspan(1.25, 1.55, facecolor='g', alpha=0.5)
plt.axis([-1, 2, -1, 2])
plt.savefig('a.png')
plt.show()
代码来源于:http://blog.csdn.net/pipisorry/article/details/40005163.net