先上一張效果圖:
以上圖是一段時間內黃金價格的波動圖。
代碼如下:
import datetime as DT from matplotlib import pyplot as plt from matplotlib.dates import date2num data = [] with open("data.txt") as my_file: for line in my_file: date, price = line.partition("@")[::2] data.append((DT.datetime.strptime(date, "%Y-%m-%d %H:%M:%S"), price)) d = [date for (date, value) in data[::8]] x = [date2num(date) for (date, value) in data] y = [value for (date, value) in data] fig = plt.figure() graph = fig.add_subplot(111) # Plot the data as a red line with round markers # graph.plot(x, y, 'r-o') graph.plot(x, y) # Set the xtick locations to correspond to just the dates you entered. graph.set_xticks(x) # Set the xtick labels to correspond to just the dates you entered. graph.set_xticklabels( [date.strftime("%Y-%m-%d %H:%M:%S") for date in d], rotation=30 ) # plt.grid(True) plt.xticks(x[::8]) # print [x[f_value] for f_value in range(0, len(x), 8)] plt.show()
data.txt數據格式如下:
2017-07-29 00:00:02@27567 2017-07-29 03:00:02@27575 2017-07-29 06:00:01@27575 2017-07-29 09:00:01@27575 2017-07-29 12:00:02@27575 2017-07-29 15:00:01@27575 2017-07-29 18:00:01@27575 2017-07-29 21:00:01@27575
相關知識點介紹:
matplotlib中整個圖像是一個Figure對象,在Figure對象中可以包含一個,或者多個Axes對象。每個Axes對象都是一個擁有自己坐標系統的繪圖區域,多個Axes對象可以繪成一個比較復雜的圖,比如共用x-axis的圖。其邏輯關系如下:
一個具體的圖如下:
Title為標題。Axis為坐標軸,Label為坐標軸標注。Tick為刻度線,Tick Label為刻度注釋,需要注意的是x-axis的ticks(刻度)和x-axis的ticklabels是分開的,ticks就代表x軸的數據,ticklabels表示數據對應的字符串。並不是每個刻度都有字符串對應,ticklabels的密度是可以控制的。往往很密集的刻度會對應合理的字符串便以閱讀。
第一個圖的x-axis軸對應的是日期,但是x軸必須有數據,因此matplotlib.dates提供了將日期轉化為數據的方法date2num, 這個例子中數據是每3小時有一條,但是顯示的時候只到天,具體是如下兩行代碼:
#每8個取一個日期,其實就是一天 d = [date for (date, value) in data[::8]] #每個日期對應一個值,這樣才能定位日期的位置,因此值也是每8個取一個 plt.xticks(x[::8])
獲取x軸和y軸的刻度值
x = [date2num(date) for (date, value) in data] y = [value for (date, value) in data]
創建圖像並設置圖像位置
fig = plt.figure()
graph = fig.add_subplot(111)
111的意思是把figure也就是圖像分成1行1列,放在第一個格子,也就是獨占整個圖像
#把數據畫到圖上,r是red的意思,線是紅色的,o表示對各個值畫一個點。 # graph.plot(x, y, 'r-o') #默認藍線不畫點 graph.plot(x, y)
# Set the xtick labels to correspond to just the dates you entered. #設置x軸label,其實就是上面算好的d日期字符串數組,rotation是label的角度 graph.set_xticklabels( [date.strftime("%Y-%m-%d %H:%M:%S") for date in d], rotation=20 )
#圖表顯示網格 plt.grid(True) #設置圖標的標題 plt.title("Gold price trends") plt.xticks(x[::8]) #設置y軸label plt.ylabel('Gold price/RMB cents') #設置x軸label plt.xlabel('Date time') #顯示圖像 plt.show()
這么下來一個簡單的圖表就畫好了,很快很實用吧。
參考鏈接:
https://segmentfault.com/a/1190000006158803