1
4

More than 3 years have passed since last update.

Pythonのpyqtgraphを使う

Posted at

経緯

グラフを描画するにはmatplotlibを使えばいいが、リアルタイムでグラフを更新する際はより高速なpyqtgraphを使った方が良さそう.
matplotlibも工夫次第では、高速処理ができるみたいだが、よく分からない.

環境

python 3.7

ソースコード

三つのデータをそれぞれ表示し、1秒後にデータの先頭要素が消えていき、その流れを描画する.

from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import sys

R = [255,   0,   0]
G = [  0, 255, 255]
B = [  0,   0, 255]

win = None
plt = None
data = [[1,-1,2,-2,3,-3,4,-4],[10,-10,9,-9,8,-8,7,-7],[0,1,0,2,0,3,0,4]]
curve = list()
app = QtGui.QApplication([])


def init():
    global curve
    global plt
    global win
    win = pg.GraphicsWindow()
    #windowのタイトル
    win.setWindowTitle('Window Title')
    #windowの大きさ
    win.resize(1280,800)
    #アンチエイリアスをOn
    pg.setConfigOptions(antialias=True)

    plt = win.addPlot()
    #グラフのタイトル
    plt.setTitle('<font size=\'4\' color=\'#FFFFFF\'>'+ 'plot Title' +'</font>')
    #目盛り線の設定
    plt.showGrid( True, True, 1 )

    #表示する際にグラフをどのぐらい拡大するか設定
    plt.setXRange( -20, 20 )
    plt.setYRange( -20, 20 )

    #左側に軸ラベルを設定
    label = '<font color=\'#' + 'FFFFFF'+'\'>'+ 'y' +'</font>'
    unit = '<font color=\'#' + 'FFFFFF'+'\'>' + 'cm' +'</font>'
    plt.setLabel('left', label, unit)
    #凡例を表示する
    plt.addLegend()

    tmp = 0
    #グラフを追加する
    while tmp < len(data):
        #penとnameは凡例に適応される
        curve.append(plt.plot(pen = (R[tmp],G[tmp],B[tmp]), name = ('data' + str(tmp+1)) ))
        tmp += 1


def update():
    global data
    i = 0
    if(len(data[0]) > 0):
        while i < len(data):
            curve[i].setData(data[i])
            del data[i][0]#頭から要素を消す
            i += 1


if __name__ == '__main__':
    init()

    timer = QtCore.QTimer()
    timer.timeout.connect(update)
    timer.start(1000)#ミリ秒単位

    # Start Qt event loop unless running in interactive mode or using pyside.
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

結果

スクリーンショット 2020-01-16 12.47.44.png

文字のフォントなどはhtmlみたいにタグで書けるのいいですね

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4