要想用python写出能生成图表的程序,首先需要安装画图模块matplotlib及依赖的库numpy 和scipy,安装步骤:
1.yum安装numpy 和scipy(中包含关于numpy的内容)
2.yum安装matplotlib
【注意:前提条件是系统中安装及用的是python2.6.6,如果同时存在python2.6.6和python2.7.6且用的是python2.7.6,则会出现问题,yum默认安装的模块会安装到python2.6.6下面的site-package下(/usr/lib64/python2.6/site-packages)而不是python2.7.6下(/usr/local/python2.7.6/lib/python2.7/site-packages),往上查资料说可以安装virtualenv虚拟环境,在里面切换不同的python版本分别处理,看着挺麻烦还没尝试,如果有朋友尝试了可以给我分享下尝试的情况】
如果一切顺利,全安装完成后,执行python buildGraph.py,一直提示如下错误,这个错误困扰了我老长时间,没有解决的思路,问了下开发的同事给了我提示顿时间豁然开朗,说可能是画图程序执行需要有展示图表的界面,而我是在xshell中执行的,不能显示图表,让我在有界面的linux系统上执行这个python程序,试了下果然成功了,生成的图表在界面上显示出来了(注意:即便你不显示图表把生成的图表保存下来也要在有界面的linux系统上执行)
附上错误提示:
[root@localhost test-python]# python buildGraph.py
Traceback (most recent call last):
File "buildGraph.py", line 5, in
from matplotlib import pyplot as plt
File "/usr/lib64/python2.6/site-packages/matplotlib/pyplot.py", line 78, in
new_figure_manager, draw_if_interactive, show = pylab_setup()
File "/usr/lib64/python2.6/site-packages/matplotlib/backends/__init__.py", line 25, in pylab_setup
globals(),locals(),[backend_name])
File "/usr/lib64/python2.6/site-packages/matplotlib/backends/backend_gtkagg.py", line 10, in
from matplotlib.backends.backend_gtk import gtk, FigureManagerGTK, FigureCanvasGTK,\
File "/usr/lib64/python2.6/site-packages/matplotlib/backends/backend_gtk.py", line 8, in
import gtk; gdk = gtk.gdk
File "/usr/lib64/python2.6/site-packages/gtk-2.0/gtk/__init__.py", line 64, in
_init()
File "/usr/lib64/python2.6/site-packages/gtk-2.0/gtk/__init__.py", line 52, in _init
_gtk.init_check()
RuntimeError: could not open display
附上基本的画图程序:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
def main():
# 颜色列表
colorList = ['b','g','r','c','m','y','k']
# 共用的横坐标
threadList = [1,2,4,8,10]
# 设置横坐标和纵坐标的名称
plt.xlabel('userNum')
plt.ylabel('responseTime')
# 图的标题
plt.title('concurrent test')
# 要绘制的线的列表
lines = []
# 对应的线的名称
titles = []
# 第一根线的纵坐标
dataList1 = [2,5,7,15,30]
# 根据横坐标和纵坐标画第一根线
line1 = plt.plot(threadList, dataList1)
# 设置线的颜色宽度等
plt.setp(line1, color=colorList[0], linewidth=2.0)
# 线的名称
titles.append('Linux')
lines.append(line1)
# 同理画第二根线
dataList2 = [2,4,6,18,35]
line2 = plt.plot(threadList, dataList2)
plt.setp(line2, color=colorList[1], linewidth=2.0)
titles.append('FreeBSD')
lines.append(line2)
plt.legend(lines, titles)
plt.show()
plt.savefig('/home/test-python/http_request/log/test.png', dpi=120)
if __name__ == '__main__':
main()
阅读(7242) | 评论(0) | 转发(0) |