はじめに
この実験では、Matplotlib の ContourSet を使って独自の等高線と多角形を表示する方法を学びます。各レベルの等高線は、多角形のリスト/タプルです。2 つのレベル間の塗りつぶされた等高線も、多角形のリスト/タプルです。点は時計回りまたは反時計回りに順序付けることができます。
VM のヒント
VM の起動が完了したら、左上隅をクリックして ノートブック タブに切り替え、Jupyter Notebook を使って練習しましょう。
時々、Jupyter Notebook が読み込み完了するまで数秒待つ必要がある場合があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。
学習中に問題に遭遇した場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。
必要なライブラリをインポートする
最初のステップは、必要なライブラリをインポートすることです。この実験では、Matplotlib を使用します。
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.contour import ContourSet
from matplotlib.path import Path
等高線と多角形を定義する
次のステップは、等高線と多角形を定義することです。この例では、2 つのレベル間に線と塗りつぶされた等高線があります。
## Contour lines for each level are a list/tuple of polygons.
lines0 = [[[0, 0], [0, 4]]]
lines1 = [[[2, 0], [1, 2], [1, 3]]]
lines2 = [[[3, 0], [3, 2]], [[3, 3], [3, 4]]] ## Note two lines.
## Filled contours between two levels are also a list/tuple of polygons.
## Points can be ordered clockwise or anticlockwise.
filled01 = [[[0, 0], [0, 4], [1, 3], [1, 2], [2, 0]]]
filled12 = [[[2, 0], [3, 0], [3, 2], [1, 3], [1, 2]], ## Note two polygons.
[[1, 4], [3, 4], [3, 3]]]
グラフを作成する
次のステップは、グラフを作成することです。これは、ContourSet 関数を使用して行うことができます。
fig, ax = plt.subplots()
## Filled contours using filled=True.
cs = ContourSet(ax, [0, 1, 2], [filled01, filled12], filled=True, cmap=cm.bone)
cbar = fig.colorbar(cs)
## Contour lines (non-filled).
lines = ContourSet(
ax, [0, 1, 2], [lines0, lines1, lines2], cmap=cm.cool, linewidths=3)
cbar.add_lines(lines)
ax.set(xlim=(-0.5, 3.5), ylim=(-0.5, 4.5),
title='User-specified contours')
穴のある塗りつぶされた等高線を作成する
Path クラスで説明されているように、多角形の頂点の単一のリストと頂点の種類(コードタイプ)のリストとともに、複数の塗りつぶされた等高線を指定することができます。これは、穴のある多角形に特に役立ちます。
fig, ax = plt.subplots()
filled01 = [[[0, 0], [3, 0], [3, 3], [0, 3], [1, 1], [1, 2], [2, 2], [2, 1]]]
M = Path.MOVETO
L = Path.LINETO
kinds01 = [[M, L, L, L, M, L, L, L]]
cs = ContourSet(ax, [0, 1], [filled01], [kinds01], filled=True)
cbar = fig.colorbar(cs)
ax.set(xlim=(-0.5, 3.5), ylim=(-0.5, 3.5),
title='User specified filled contours with holes')
まとめ
この実験では、Matplotlib の ContourSet を使って独自の等高線と多角形を表示する方法を学びました。等高線と多角形を定義し、グラフを作成し、穴のある塗りつぶされた等高線を作成しました。