はじめに
Matplotlib は、データ可視化に使用される Python ライブラリです。この実験では、Matplotlib を使ってプログラム的または対話的に多角形を作成します。多角形は、関心のある領域を強調するため、またはプロットの特定の領域をマスクするために使用できます。
VM のヒント
VM の起動が完了したら、左上隅をクリックしてノートブックタブに切り替え、Jupyter Notebook を使って練習しましょう。
時々、Jupyter Notebook が読み込み終了するまで数秒待つ必要がある場合があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。
学習中に問題に直面した場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。そうすれば、迅速に問題を解決します。
必要なライブラリをインポートする
Matplotlib を使い始める前に、必要なライブラリをインポートする必要があります。この実験では、matplotlib.pyplot と matplotlib.widgets を使用します。
import matplotlib.pyplot as plt
from matplotlib.widgets import PolygonSelector
プログラムで多角形を作成する
プログラムで多角形を作成するには、Figure オブジェクトと Axes オブジェクトを作成する必要があります。その後、PolygonSelector オブジェクトを作成してそれに頂点を追加できます。最後に、Axes 上に多角形を描画できます。
fig, ax = plt.subplots()
selector = PolygonSelector(ax, lambda *args: None)
## 3 つの頂点を追加する
selector.verts = [(0.1, 0.4), (0.5, 0.9), (0.3, 0.2)]
## 多角形を描画する
ax.add_patch(plt.Polygon(selector.verts, alpha=0.3))
plt.show()
対話的に多角形を作成する
対話的に多角形を作成するには、Figure オブジェクトと Axes オブジェクトを作成する必要があります。その後、PolygonSelector オブジェクトを作成し、プロット上をクリックすることでそれに頂点を追加できます。また、shift キーと ctrl キーを使って頂点を移動させることもできます。
fig, ax = plt.subplots()
selector = PolygonSelector(ax, lambda *args: None)
print("Click on the figure to create a polygon.")
print("Press the 'esc' key to start a new polygon.")
print("Try holding the 'shift' key to move all of the vertices.")
print("Try holding the 'ctrl' key to move a single vertex.")
plt.show()
すべてをまとめる
プログラムで多角形を作成することと対話的に多角形を作成することの両方を含む完全なサンプルを作成しましょう。
import matplotlib.pyplot as plt
from matplotlib.widgets import PolygonSelector
## グラフと軸を作成する
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5))
## PolygonSelector オブジェクトを作成して頂点を追加する
selector1 = PolygonSelector(ax1, lambda *args: None)
selector1.verts = [(0.1, 0.4), (0.5, 0.9), (0.3, 0.2)]
## 多角形を描画する
ax1.add_patch(plt.Polygon(selector1.verts, alpha=0.3))
## 対話的作成用の別の PolygonSelector オブジェクトを作成する
selector2 = PolygonSelector(ax2, lambda *args: None)
print("Click on the figure to create a polygon.")
print("Press the 'esc' key to start a new polygon.")
print("Try holding the 'shift' key to move all of the vertices.")
print("Try holding the 'ctrl' key to move a single vertex.")
plt.show()
まとめ
この実験では、Matplotlib を使ってプログラムで多角形を作成し、対話的に多角形を作成する方法を学びました。また、PolygonSelector オブジェクトに頂点を追加し、結果として得られる多角形を Axes 上に描画する方法も学びました。この知識は、関心のある領域を強調したり、プロット内の特定の領域をマスクする際に役立つ可能性があります。