はじめに
この実験では、Matplotlib Span Selector を使用して軸上の範囲を選択し、選択された範囲の詳細なビューを別の軸にプロットする方法を学びます。
VM のヒント
VM の起動が完了したら、左上隅をクリックして ノートブック タブに切り替え、Jupyter Notebook を使用して練習します。
場合によっては、Jupyter Notebook が読み込み完了するまで数秒待つ必要があります。Jupyter Notebook の制限により、操作の検証は自動化できません。
学習中に問題が発生した場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。
必要なライブラリをインポートする
まず、必要なライブラリ - numpy と matplotlib をインポートする必要があります。
import numpy as np
import matplotlib.pyplot as plt
サンプルデータを作成する
ここでは、numpy を使ってプロットするためのサンプルデータを作成します。
## Fixing random state for reproducibility
np.random.seed(19680801)
x = np.arange(0.0, 5.0, 0.01)
y = np.sin(2 * np.pi * x) + 0.5 * np.random.randn(len(x))
グラフとサブプロットを作成する
ここでは、matplotlib を使って 2 つのサブプロット付きのグラフを作成します。
fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 6))
最初のサブプロットにデータをプロットする
最初のサブプロットにサンプルデータをプロットします。
ax1.plot(x, y)
ax1.set_ylim(-2, 2)
ax1.set_title('Press left mouse button and drag '
'to select a region in the top graph')
コールバック関数を定義する
Span Selector を使用して範囲が選択されたときに呼び出されるコールバック関数を定義します。
def onselect(xmin, xmax):
indmin, indmax = np.searchsorted(x, (xmin, xmax))
indmax = min(len(x) - 1, indmax)
region_x = x[indmin:indmax]
region_y = y[indmin:indmax]
if len(region_x) >= 2:
line2.set_data(region_x, region_y)
ax2.set_xlim(region_x[0], region_x[-1])
ax2.set_ylim(region_y.min(), region_y.max())
fig.canvas.draw_idle()
Span Selector を作成する
matplotlib.widgets.SpanSelector を使用して Span Selector オブジェクトを作成します。
span = SpanSelector(
ax1,
onselect,
"horizontal",
useblit=True,
props=dict(alpha=0.5, facecolor="tab:blue"),
interactive=True,
drag_from_anywhere=True
)
2 番目のサブプロットにデータをプロットする
選択された範囲の詳細なビューを 2 番目のサブプロットにプロットします。
line2, = ax2.plot([], [])
グラフを表示する
ここでは、matplotlib.pyplot.show() を使用してグラフを表示します。
plt.show()
まとめ
この実験では、Matplotlib の Span Selector を使用して軸上の範囲を選択し、選択された範囲の詳細なビューを別の軸にプロットする方法を学びました。また、Span Selector オブジェクトを作成し、選択された範囲を処理するためのコールバック関数を定義する方法も学びました。