上次用 python 腳本中定期查詢數據庫,監視訂單變化,將時間與處理完成訂單的數量進行輸入寫入日志,雖然省掉了人為定時查看數據庫並記錄的操作,但是數據不進行分析只是數據,要讓數據活起來!
為了方便看出已完成訂單的趨勢,又不想想到使用Excel, 想到手動繪制表格填入數據就充滿了抵觸,哈哈,能用代碼完成的事絕不手操,不能愧對python!
先確保python環境和pip已經安裝好
這個過程分為3步: 安裝 jupyter-notebook ——> 安裝matplotlib ——> 寫代碼唄
1. 為什么用 jupyter-notebook ,jupyter安裝方便,功能強大,基於瀏覽器編輯運行,數據可視化支持友好 ....
安裝: pip install jupyter notebook
運行: 在cmd 中輸入: jupyter-notebook
你將看到如下信息界面:

瀏覽器會默認打開127.0.0.1:8888,如果沒有,手動復制紅框地址在瀏覽器打開,然后你就可以愉快地使用jupyter了!
在右上角有個NEW按鈕,可以看到jupyter支持創建的類型,python3: 一個交互式的python環境,支持tab 提示補全, Text File:普通文本文件, Folder: 文件夾, Terminal: 比系統cmd更舒服的控制台


還可以用ls ,pwd等linux命令 是不是很強大!
2. 安裝matplotlib, Matplotlib 是 Python 的繪圖庫。 它可與 NumPy 一起使用,提供了一種有效的 MatLab 開源替代方案。 它也可以和圖形工具包一起使用,如 PyQt 和 wxPython。
pip install matplotlib
3. 如果有log文件內容如下:
------------------current time: 2019-09-11 11:33:55, finished order count: 0 --------------------
------------------current time: 2019-09-11 11:43:55, finished order count: 63 --------------------
------------------current time: 2019-09-11 11:53:55, finished order count: 117 --------------------
------------------current time: 2019-09-11 12:03:55, finished order count: 135 --------------------
------------------current time: 2019-09-11 12:13:55, finished order count: 185 --------------------
------------------current time: 2019-09-11 12:23:55, finished order count: 218 --------------------
要將時分秒數據作為x軸數據,0,63,117等訂單數據作為y軸數據,看代碼:
# -*- coding=utf-8 -*- import re import pandas from matplotlib import pyplot as plt with open('../log.log','r') as f: lines = f.readlines() x = [] y = [] for line in lines: date = re.search(r' (\d+:\d+:\d+)',line).group(1) x.append(date) finishOrder = re.search(r'count: (\d+)', line).group(1) y.append(int(finishOrder)) plt.figure(figsize=(20,10)) #創建繪圖對象 指定figure的寬和高,單位為英寸 plt.plot(x,y,"o--",linewidth=1) #在當前繪圖對象繪圖(X軸,Y軸,藍色虛線,線寬度) plt.xticks(rotation=25) # 旋轉角度,避免x軸間距不足導致重疊 plt.tick_params(labelsize=14) for x,y in zip(x,y): plt.text(x,y + 5,'%.0f' %y,ha = 'center',fontsize = 14) # 使折現節點顯示具體的值 , +5 表示節點的值位於節點的上下距離高度 plt.xlabel("時間段",fontproperties="SimSun",fontsize = 18) #X軸標簽 fontproperties設置字體,不然會中文亂碼 plt.ylabel("已完成訂單數",fontproperties="SimSun",fontsize = 18) plt.title("趨勢圖",fontproperties="SimSun",color='red',fontsize = 24) #圖標題 plt.savefig('趨勢圖.png') # 保存生成的趨勢圖到本地 必須寫在show前面,不然保存的圖片是空白的 plt.show() #顯示圖
看效果:

