はじめに
Matplotlib は、Python プログラミング言語とその数値数学拡張 NumPy 用のグラフ描画ライブラリです。このチュートリアルでは、Matplotlib におけるテキストの配置に焦点を当てます。
VM のヒント
VM の起動が完了したら、左上隅をクリックしてノートブックタブに切り替え、Jupyter Notebook を使って練習しましょう。
時々、Jupyter Notebook が読み込み終わるまで数秒待つ必要がある場合があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。
学習中に問題に遭遇した場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。
四角形の作成
matplotlib.patches モジュールの Rectangle() 関数を使って、グラフに四角形を作成します。四角形を作成した後、set_xlim() と set_ylim() 関数を使って、その水平および垂直の範囲を設定します。最後に、四角形をグラフに追加します。
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
fig, ax = plt.subplots()
## 軸座標に四角形を作成する
left, width =.25,.5
bottom, height =.25,.5
right = left + width
top = bottom + height
p = Rectangle((left, bottom), width, height, fill=False)
ax.add_patch(p)
## 水平および垂直の範囲を設定する
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.show()
四角形にテキストを追加する
このステップでは、text() 関数を使って四角形にテキストを追加します。テキストの水平および垂直の配置は、それぞれ horizontalalignment および verticalalignment パラメータを使って設定します。
## 四角形にテキストを追加する
ax.text(left, bottom, 'left top',
horizontalalignment='left',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, bottom, 'left bottom',
horizontalalignment='left',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right bottom',
horizontalalignment='right',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right top',
horizontalalignment='right',
verticalalignment='top',
transform=ax.transAxes)
ax.text(right, bottom, 'center top',
horizontalalignment='center',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, 0.5 * (bottom + top), 'right center',
horizontalalignment='right',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, 0.5 * (bottom + top), 'left center',
horizontalalignment='left',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(0.5 * (left + right), 0.5 * (bottom + top),'middle',
horizontalalignment='center',
verticalalignment='center',
transform=ax.transAxes)
ax.text(right, 0.5 * (bottom + top), 'centered',
horizontalalignment='center',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, top, 'rotated\nwith newlines',
horizontalalignment='center',
verticalalignment='center',
rotation=45,
transform=ax.transAxes)
plt.show()
グラフのカスタマイズ
このステップでは、軸のラベルを追加して軸の線を削除することでグラフをカスタマイズします。
## グラフをカスタマイズする
ax.set_axis_off()
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_title('Text Alignment in Matplotlib')
plt.show()
まとめ
このチュートリアルでは、Matplotlib におけるテキストの配置方法を学びました。text() 関数を使って四角形にテキストを追加し、それぞれ horizontalalignment および verticalalignment パラメータを使って水平および垂直の配置を設定しました。また、軸のラベルを追加して軸の線を削除することでグラフをカスタマイズしました。