Python独習!

習得したPython知識をペイフォワード

Pythonでデータロガーのような動的グラフを表示する

実験で使うデータロガーや、株価の推移など、データを動的なグラフにしてモニタリングしたいシーンはたくさんあると思う。使いどころが多いともうので勉強してみた。

結果

RC回路の過渡現象をシミュレーションしてみた。
参考:https://www.kairo-nyumon.com/rc_circuit.html
⇒時間経過とともにX軸(時間軸)、Y軸(電圧)ともに動的に表示できている。
f:id:greenhornprofessional:20200316232910g:plain

プログラム

#16_animationPlot_001.py
# python 3.8.1
# coding: utf-8

from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.animation import PillowWriter
import math

fig = plt.figure()
 
xlim = [0,50]           #グラフ横軸の範囲を決める
X, Y = [], []           #空リスト。XYデータを格納していく。

#RC回路パラメーター
Cap = 0.5 / 1000000     #静電容量 uF
Res = 33 * 1000         #抵抗 kΩ
Tau = -1 * (1/Cap/Res)  #時定数
Va  = 5                 #振幅 V

def transient(t):
    t = t / 1000        #時間 msec
    v = Va * (1-(math.exp(Tau * t)))        #電圧推移の計算
    return(v)

def plot(i):                                #引数iは使わないけど、消すとエラーになる。
    plt.cla()                               #前のグラフを削除
    Y.append(transient(len(Y)))             #Yの大きさ=データの数=時間
    X.append(len(Y))
    
    if len(X) > 50:                         #データが50を超えたら、表示範囲を1-51 -> 2-52 -> とずらしていく
        xlim[0]+=1
        xlim[1]+=1
    
    plt.plot(X, Y)                          #次のグラフを作成
    plt.title("Transient in RC-circuit")
    plt.xlim(xlim[0],xlim[1])               #X軸の表示範囲を更新する
    plt.xlabel("msec")
    plt.ylabel("V")
    plt.grid(which = "major", axis = "y", color = "gray",
             alpha = 0.8, linestyle = "--", linewidth = 0.5)
    plt.grid(which = "major", axis = "x", color = "gray",
             alpha = 0.8, linestyle = "--", linewidth = 0.5)

#100msec(これは現実の時間で、RC過渡シミュレーションの時間ではない)ごとにplot関数を呼び出す。
ani = animation.FuncAnimation(fig, plot, interval=100)

#グラフ表示をGIFで保存する。よく分かってないが4MBこえると勝手に保存が終了する、挙動を示す。
#ani.save('sample3.gif', writer='pillow')

plt.show()

参考サイト

Samurai Blogさんにドンピシャのコードがあったので参考にさせていただいた。丸コピでは動かない(Blilt = True が不要)ので注意。
matplotlib.animationで動くグラフに挑戦! | 侍エンジニア塾ブログ(Samurai Blog) - プログラミング入門者向けサイト

Matplotlib.animationの解説
Python: matplotlib で動的にグラフを生成する - CUBE SUGAR CONTAINER
matplotlib.animation — Matplotlib 3.2.0 documentation

グラフ表示について
[Matplotlib] 目盛と目盛ラベル、目盛線

GIF保存について
matplotlibでimagemagickを使わずにアニメGIFを保存する - Qiita

/* -----codeの行番号----- */