python实战二:使用CSV数据绘制带数据标志的折线图(matplotlib)

该博客介绍自动获取缺陷管理系统中bug趋势统计数据,保存到CSV,重点展示读取CSV数据绘制带数据标志的折线图并保存为png图片的代码。使用Python的numpy、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
#读取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)
        return r.create_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文件格式示意图:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值