標籤:import 建圖 bsp 系統 自己 圖表 app htm 表示
先上一張:
以是一段時間內黃金價格的波動圖。
代碼如下:
import datetime as DTfrom matplotlib import pyplot as pltfrom matplotlib.dates import date2numdata = []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:[email protected]2017-07-29 03:00:[email protected]2017-07-29 06:00:[email protected]2017-07-29 09:00:[email protected]2017-07-29 12:00:[email protected]2017-07-29 15:00:[email protected]2017-07-29 18:00:[email protected]2017-07-29 21:00:[email protected]
相關知識點介紹:
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軸labelplt.ylabel(‘Gold price/RMB cents‘)#設定x軸labelplt.xlabel(‘Date time‘)#顯示映像plt.show()
這麼下來一個簡單的圖表就畫好了,很快很實用吧。
參考連結:
1190000006158803
https://matplotlib.org/users/pyplot_tutorial.html
http://bbs.csdn.net/topics/390705164?page=1
Python簡單做二維統計圖