1. 程式人生 > >python實戰二:使用CSV資料繪製帶資料標誌的折線圖(matplotlib)

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
#讀取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檔案格式示意圖:
這裡寫圖片描述