Matplotlib で多角形を作成する

PythonPythonBeginner
今すぐ練習

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

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

はじめに

Matplotlibは、データ可視化に使用されるPythonライブラリです。この実験では、Matplotlibを使ってプログラム的または対話的に多角形を作成します。多角形は、関心のある領域を強調するため、またはプロットの特定の領域をマスクするために使用できます。

VMのヒント

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

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

学習中に問題に直面した場合は、Labbyにお問い合わせください。セッション後にフィードバックを提供してください。そうすれば、迅速に問題を解決します。

必要なライブラリをインポートする

Matplotlibを使い始める前に、必要なライブラリをインポートする必要があります。この実験では、matplotlib.pyplotmatplotlib.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 上に描画する方法も学びました。この知識は、関心のある領域を強調したり、プロット内の特定の領域をマスクする際に役立つ可能性があります。