python實戰二:使用CSV資料繪製帶資料標誌的折線圖(matplotlib)

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.