python实战⼆:使⽤CSV数据绘制带数据标志的折线图
(matplotlib)
背景:
⾃动获取缺陷管理系统中的bug趋势统计数据,并保存到CSV中,读取CSV数据并绘制带数据标志的折线图,并保存为png图⽚下⾯代码仅实现“读取CSV数据并绘制带数据标志的折线图,并保存为png图⽚”的功能
#导⼊需要的模块
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.ticker as ticker
matplotlib中subplot#读取CSV数据为numpy record array记录
r = mlab.csv2rec('D:/python/pj4/data/bug_trend.csv')
r.sort()
#形成Y轴坐标数组
N = len(r)
ind = np.arange(N)  # the evenly spaced plot indices
#ind1这⾥是为了把图撑⼤⼀点
ind1 = np.arange(N+3)
#将X轴格式化为⽇期形式,X轴默认为0.5步进,
#这⾥将整数X轴坐标格式化为⽇期,.5的不对应⽇期,
#因为扩展了3格坐标,所以N+的坐标点也不显⽰⽇期
def format_date(x, pos=None):
if not x%1 and  x<N:
thisind = np.clip(int(x), 0, N-1)
ate_date[thisind].strftime('%Y-%m-%d')
else:
return ''
#绘图
fig = plt.figure()
ax = fig.add_subplot(111)
#下⾏为了将图扩⼤⼀点,⽤⽩⾊线隐藏显⽰
ax.plot(ind1,ind1,'-',color='white')
#正常要显⽰的bug总数折线
ax.plot(ind, r['all'], 'o-',label='All of BUGs')
#正常要显⽰的bug已解决总数折线
ax.plot(ind, r['resolved'], 'o-',label='Resolved BUGs')
#正常要显⽰的bug已关闭总数折线
ax.plot(ind, r['closed'], 'o-',label='Closed BUGs')
#图标的标题
ax.set_title(u"BUG Trend Chart")
#线型⽰意说明
ax.legend(loc='upper left')
#在折线图上标记数据,-+0.1是为了错开⼀点显⽰数据
datadotxy=tuple(zip(ind-0.1,r['all']+0.1))
for dotxy in datadotxy:
ax.annotate(str(int(dotxy[1]-0.1)),xy=dotxy)
#将X轴格式化为⽇期形式
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date)) fig.autofmt_xdate()
#显⽰图⽚
plt.show()
#将图⽚保存到指定⽬录
plt.savefig("D:/python/pj4/img/bug_trend.png")
效果图:
CSV⽂件格式⽰意图:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。