はじめに
この実験では、可視化を作成するための Python ライブラリである Matplotlib を使用して、グラフを作成し、その構造に注釈を付ける方法を学びます。グラフを作成し、データをプロットし、軸の範囲を設定し、ラベルとタイトルを追加し、グラフにテキストとマーカーで注釈を付ける方法を学びます。
VM のヒント
VM の起動が完了したら、左上隅をクリックしてノートブックタブに切り替え、Jupyter Notebook を使用して練習します。
場合によっては、Jupyter Notebook が読み込み終了するまで数秒待つ必要があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。
学習中に問題に遭遇した場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。
ライブラリのインポートとデータの設定
まず、必要なライブラリをインポートし、プロットするためのいくつかのデータを設定する必要があります。この例では、いくつかのランダムノイズが加えられた 3 つのサイン波をプロットします。
import matplotlib.pyplot as plt
import numpy as np
## Set up data
np.random.seed(19680801)
X = np.linspace(0.5, 3.5, 100)
Y1 = 3+np.cos(X)
Y2 = 1+np.cos(1+X/0.75)/2
Y3 = np.random.uniform(Y1, Y2, len(X))
グラフの作成と軸の設定
次に、グラフを作成して軸を設定します。add_axes() メソッドを使用して、グラフ内に新しい軸のセットを作成します。また、x 軸と y 軸の範囲を設定し、グリッド線を追加します。
## Create figure and axes
fig = plt.figure(figsize=(7.5, 7.5))
ax = fig.add_axes([0.2, 0.17, 0.68, 0.7], aspect=1)
## Set limits and gridlines
ax.set_xlim(0, 4)
ax.set_ylim(0, 4)
ax.grid(linestyle="--", linewidth=0.5, color='.25', zorder=-10)
データのプロット
次に、先ほど作成した軸にデータをプロットします。異なる色と線幅で 3 つのサイン波をプロットするには、plot() メソッドを使用します。
## Plot data
ax.plot(X, Y1, c='C0', lw=2.5, label="Blue signal", zorder=10)
ax.plot(X, Y2, c='C1', lw=2.5, label="Orange signal")
ax.plot(X[::3], Y3[::3], linewidth=0, markersize=9,
marker='s', markerfacecolor='none', markeredgecolor='C4',
markeredgewidth=2.5)
ラベルとタイトルの追加
次に、set_xlabel()、set_ylabel()、および set_title() メソッドを使用して、x 軸と y 軸にラベルを追加し、グラフにタイトルを追加します。
## Add labels and title
ax.set_xlabel("x Axis label", fontsize=14)
ax.set_ylabel("y Axis label", fontsize=14)
ax.set_title("Anatomy of a figure", fontsize=20, verticalalignment='bottom')
凡例の追加
legend() メソッドを使用して、グラフに凡例を追加します。また、凡例の位置とフォントサイズを指定します。
## Add legend
ax.legend(loc="upper right", fontsize=14)
グラフに注釈を付ける
最後に、text() と Circle() メソッドを使って、様々な Matplotlib 要素の名前を示すためにグラフに注釈を付けます。また、注釈のテキストとマーカーに白い輪郭を追加して、視認性を向上させるために withStroke() メソッドを使います。
## Annotate the figure
from matplotlib.patches import Circle
from matplotlib.patheffects import withStroke
royal_blue = [0, 20/256, 82/256]
def annotate(x, y, text, code):
## Circle marker
c = Circle((x, y), radius=0.15, clip_on=False, zorder=10, linewidth=2.5,
edgecolor=royal_blue + [0.6], facecolor='none',
path_effects=[withStroke(linewidth=7, foreground='white')])
ax.add_artist(c)
## use path_effects as a background for the texts
## draw the path_effects and the colored text separately so that the
## path_effects cannot clip other texts
for path_effects in [[withStroke(linewidth=7, foreground='white')], []]:
color = 'white' if path_effects else royal_blue
ax.text(x, y-0.2, text, zorder=100,
ha='center', va='top', weight='bold', color=color,
style='italic', fontfamily='Courier New',
path_effects=path_effects)
color = 'white' if path_effects else 'black'
ax.text(x, y-0.33, code, zorder=100,
ha='center', va='top', weight='normal', color=color,
fontfamily='monospace', fontsize='medium',
path_effects=path_effects)
annotate(3.5, -0.13, "Minor tick label", "ax.xaxis.set_minor_formatter")
annotate(-0.03, 1.0, "Major tick", "ax.yaxis.set_major_locator")
annotate(0.00, 3.75, "Minor tick", "ax.yaxis.set_minor_locator")
annotate(-0.15, 3.00, "Major tick label", "ax.yaxis.set_major_formatter")
annotate(1.68, -0.39, "xlabel", "ax.set_xlabel")
annotate(-0.38, 1.67, "ylabel", "ax.set_ylabel")
annotate(1.52, 4.15, "Title", "ax.set_title")
annotate(1.75, 2.80, "Line", "ax.plot")
annotate(2.25, 1.54, "Markers", "ax.scatter")
annotate(3.00, 3.00, "Grid", "ax.grid")
annotate(3.60, 3.58, "Legend", "ax.legend")
annotate(2.5, 0.55, "Axes", "fig.subplots")
annotate(4, 4.5, "Figure", "plt.figure")
annotate(0.65, 0.01, "x Axis", "ax.xaxis")
annotate(0, 0.36, "y Axis", "ax.yaxis")
annotate(4.0, 0.7, "Spine", "ax.spines")
まとめ
この実験では、Matplotlib を使ってグラフを作成し、その構成要素に注釈を付ける方法を学びました。グラフを作成し、データをプロットし、軸の範囲を設定し、ラベルとタイトルを追加し、テキストとマーカーでグラフに注釈を付ける方法を学びました。この実験の手順に従うことで、Python で Matplotlib を使ってグラフを作成し注釈を付ける方法を十分に理解したはずです。