1. 程式人生 > >python Matplotlib 系列教程(九)——如何繪製動態圖(類似實時股票圖=走勢圖)

python Matplotlib 系列教程(九)——如何繪製動態圖(類似實時股票圖=走勢圖)

本章我們討論的是如何繪製實時圖表,用到的知識是Matplotlib的動畫功能。

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf", size=14)  

# 這個是style的內建風格 
style.use('fivethirtyeight') # 多次使用figure函式可以繪製產生多個圖,其中,圖片號按順序增加。 # 這裡,要注意一個概念當前圖和當前座標。所有繪圖操作僅對當前圖和當前座標有效. # 你可以嘗試下面這段程式碼,就可以理解figure的含義 # plt.figure(1) # 第一張圖 # plt.subplot(211) # 第一張圖中的第一張子圖 # plt.plot([1,2,3]) # plt.subplot(212) # 第一張圖中的第二張子圖 # plt.plot([4,5,6]) # plt.figure(2) # 第二張圖
# plt.plot([4,5,6]) # 預設建立子圖subplot(111) # plt.figure(1) # 切換到figure 1 ; 子圖subplot(212)仍舊是當前圖 # plt.subplot(211) # 令子圖subplot(211)成為figure1的當前圖 # plt.title('Easy as 1,2,3') # 新增subplot 211 的標題 fig = plt.figure() ax1 = fig.add_subplot(1,1,1) def animate(i): graph_data = open('example.txt'
, 'r').read() lines = graph_data.split('\n') xs = [] ys = [] for line in lines: if len(line) > 1: x, y = line.split(',') xs.append(x) ys.append(y) ax1.clear() ax1.plot(xs, ys) ani = animation.FuncAnimation(fig, animate, interval = 1000) plt.show()