PyQtの基礎 - グラフ
ナビゲーションに移動
検索に移動
概要
ここでは、PyQtとMatplotlibを使用して、グラフを表示する方法を記載する。
Matplotlibとは
Matplotlibとは、PythonやNumPyで使用するためのグラフ描画用ライブラリである。
Matplotlibは、豊富な種類のグラフを生成することができる。
MatplotlibはPythonの標準ライブラリではないので、別途インストールする必要がある。
以下のコマンドを実行して、Matplotlibをインストールする。
pip3 install matplotlib
実務上において、NumPyやSciPyと合わせて使用することが多い。
その時は、必要に応じてNumPy等もpipコマンドを使用してインストールすること。
(このページでは、NumPyやSciPyは使用しない)
また、Matplotlibをさらに詳しく知りたい場合は、公式Webサイトにアクセスして確認すること。
Matplotlibで作成するグラフ (1)
このセクションでは、PyQtとMatplotlibを使用してグラフを表示する。
こちらのWebサイトのチュートリアルにあるPyQt5 Matplotlibという箇所とサンプルコードを参考にする。
下図のグラフは、Matplotlibによって描画されたグラフである。
この画面とグラフを表示するためのサンプルコードを以下に示す。(このサンプルコードは、上記のチュートリアルから引用している)
# - * - coding: utf8 - *
import sys
import random
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
class App(QMainWindow):
def __init__(self):
super().__init__()
self.left = 10
self.top = 10
self.title = "PyQt5 matplotlib example - pythonspot.com"
self.width = 640
self.height = 400
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
m = PlotCanvas(self, width=5, height=4)
m.move(0,0)
button = QPushButton('PyQt5 button', self)
button.setToolTip('This s an example button')
button.move(500,0)
button.resize(140,100)
self.show()
class PlotCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.plot()
def plot(self):
data = [random.random() for i in range(25)]
ax = self.figure.add_subplot(111)
ax.plot(data, 'r-')
ax.set_title('PyQt Matplotlib Example')
self.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
上記のサンプルコードを実行すると、コンソール上に次のような警告が出力される。(挙動自体に影響はないと思われる)
MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance. warnings.warn(message, mplDeprecation, stacklevel=1)
次のセクションでは、上記の警告も出力されないように修正を加えながら、動的な画面とグラフを作成する。