Python の Matplotlib を使ったインタラクティブなデータ可視化

PythonPythonBeginner
オンラインで実践に進む

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、複数のキャンバスとデータをどのようにやり取りするかを学びます。1 つの軸上の点を選択して強調表示することで、もう一方の軸上のその点のデータを生成します。この実験では Python Matplotlib を使用します。

VM のヒント

VM の起動が完了したら、左上隅をクリックしてノートブックタブに切り替え、Jupyter Notebook を使って練習しましょう。

時々、Jupyter Notebook が読み込み終わるまで数秒待つ必要がある場合があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。

学習中に問題に遭遇した場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。

ライブラリのインポート

必要なライブラリをインポートして始めましょう。

import numpy as np
import matplotlib.pyplot as plt

データの生成

NumPy を使ってランダムなデータを生成します。

np.random.seed(19680801)
X = np.random.rand(100, 200)
xs = np.mean(X, axis=1)
ys = np.std(X, axis=1)

グラフと軸の作成

2 つの軸を持つグラフを作成します。

fig, (ax, ax2) = plt.subplots(2, 1)

データのプロット

生成したデータを最初の軸にプロットします。

line, = ax.plot(xs, ys, 'o', picker=True, pickradius=5)

ポイントブラウザクラスの作成

ポイントブラウザの機能を処理するクラスを作成します。

class PointBrowser:
    def __init__(self):
        self.lastind = 0

        self.text = ax.text(0.05, 0.95, 'selected: none',
                            transform=ax.transAxes, va='top')
        self.selected, = ax.plot([xs[0]], [ys[0]], 'o', ms=12, alpha=0.4,
                                 color='yellow', visible=False)

    def on_press(self, event):
        if self.lastind is None:
            return
        if event.key not in ('n', 'p'):
            return
        if event.key == 'n':
            inc = 1
        else:
            inc = -1

        self.lastind += inc
        self.lastind = np.clip(self.lastind, 0, len(xs) - 1)
        self.update()

    def on_pick(self, event):

        if event.artist!= line:
            return True

        N = len(event.ind)
        if not N:
            return True

        ## the click locations
        x = event.mouseevent.xdata
        y = event.mouseevent.ydata

        distances = np.hypot(x - xs[event.ind], y - ys[event.ind])
        indmin = distances.argmin()
        dataind = event.ind[indmin]

        self.lastind = dataind
        self.update()

    def update(self):
        if self.lastind is None:
            return

        dataind = self.lastind

        ax2.clear()
        ax2.plot(X[dataind])

        ax2.text(0.05, 0.9, f'mu={xs[dataind]:1.3f}\nsigma={ys[dataind]:1.3f}',
                 transform=ax2.transAxes, va='top')
        ax2.set_ylim(-0.5, 1.5)
        self.selected.set_visible(True)
        self.selected.set_data(xs[dataind], ys[dataind])

        self.text.set_text('selected: %d' % dataind)
        fig.canvas.draw()

イベントハンドラの接続

イベントハンドラをグラフキャンバスに接続します。

browser = PointBrowser()

fig.canvas.mpl_connect('pick_event', browser.on_pick)
fig.canvas.mpl_connect('key_press_event', browser.on_press)

グラフの表示

グラフを表示します。

plt.show()

まとめ

この実験では、Python の Matplotlib を使って複数のキャンバスとデータを相互作用させる方法を学びました。ポイントブラウザの機能を処理するクラスを作成し、インタラクティビティを可能にするためにイベントハンドラをグラフキャンバスに接続しました。