背景:
自動擷取缺陷管理系統中的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檔案格式示意圖: