工作中经常要分析数据,比如网络并发量,DC响应时间等,借用matplotlib将数据生成曲线图,可以直观地分析数据的变化情况。
下面是生成曲线图的脚本,实际使用时修改某些值定制一下即可。
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
"""
4
File Function: 读取数据文件,生成曲线图
5
data source format:
6
51 07:27:46
7
106 07:27:47
8
139 07:27:48
9
326 07:27:49
10
185 07:27:50
11
..
12
Author: Kevin Hou
13
Date: 2013/01/22
14
"""
15
16
import matplotlib.pyplot as pl
17
from matplotlib.ticker import MultipleLocator, FuncFormatter
18
import numpy as np
19
20
MultipleLocator.MAXTICKS = 100000
21
22
fig = pl.figure(figsize=(10,6))
23
24
#77为文件数据个数
25
x = np.arange(0, 77, 1)
26
y = []
27
z = []
28
t = []
29
30
f = open("yr_nr.txt","r")
31
num=0
32
for l in f:
33
y.append(int(l.strip().split(" ")[0]))
34
#隔两个点显示一个label,否则x轴显示不下
35
if num%3==0:
36
t.append(l.strip().split(" ")[1])
37
num += 1
38
f.close()
39
pl.plot(x, y, label='YR', color='red')
40
41
f = open("kk_nr.txt","r")
42
for l in f:
43
z.append(int(l.strip().split(" ")[0]))
44
f.close()
45
pl.plot(x, z, label='KK')
46
47
ax = pl.gca()
48
49
# 设置两个坐标轴的范围
50
pl.ylim(0,800)
51
pl.xlim(0, np.max(x))
52
53
# 设置图的底边距
54
pl.subplots_adjust(bottom = 0.15)
55
56
pl.grid() #开启网格
57
58
# 主刻度
59
ax.xaxis.set_major_locator( MultipleLocator(3) )
60
ax.yaxis.set_major_locator( MultipleLocator(50) )
61
62
# 主刻度文本用time_formatter函数计算
63
#ax.xaxis.set_major_formatter( FuncFormatter( time_formatter ) )
64
65
# 副刻度为
66
#ax.xaxis.set_minor_locator( MultipleLocator(np.pi/20) )
67
68
#获取当前x轴的label
69
locs,labels = pl.xticks()
70
#重新设置新的label,用时间t设置
71
pl.xticks(locs, t)
72
73
pl.ylabel("Number")
74
pl.title("WCG => Samba")
75
76
# 设置刻度文本的大小
77
#for tick in ax.xaxis.get_major_ticks():
78
# tick.label1.set_fontsize(5)
79
#pl.show()
80
pl.legend()
81
82
#自动调整label显示方式,如果太挤则倾斜显示
83
fig.autofmt_xdate()
84
85
#保存曲线为图片格式
86
pl.savefig("wcg.png") 生成的曲线图: