失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python实战二:使用CSV数据绘制带数据标志的折线图(matplotlib)

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

时间:2020-05-30 00:10:55

相关推荐

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

背景:

自动获取缺陷管理系统中的bug趋势统计数据,并保存到CSV中,读取CSV数据并绘制带数据标志的折线图,并保存为png图片

下面代码仅实现“读取CSV数据并绘制带数据标志的折线图,并保存为png图片”的功能

#导入需要的模块import numpy as npimport matplotlib.pyplot as pltimport matplotlib.mlab as mlabimport 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文件格式示意图:

如果觉得《python实战二:使用CSV数据绘制带数据标志的折线图(matplotlib)》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。