はじめに
この実験では、rotation_mode パラメータを使用して Matplotlib でテキストを回転させる方法を学びます。rotation_mode パラメータは、テキストの回転と配置の順序を決定します。利用可能なモードは 2 つあります。default と anchor です。
VM のヒント
VM の起動が完了したら、左上隅をクリックして ノートブック タブに切り替え、Jupyter Notebook を使って練習しましょう。
Jupyter Notebook の読み込みには数秒かかる場合があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。
学習中に問題が発生した場合は、Labby にお問い合わせください。セッション終了後にフィードバックを提供してください。すぐに問題を解決いたします。
必要なライブラリをインポートする
まず、必要なライブラリをインポートする必要があります。この実験では、Matplotlib を使ってグラフを作成します。
import matplotlib.pyplot as plt
test_rotation_mode 関数を定義する
異なる回転モードをテストするためのサブプロットを作成する test_rotation_mode という関数を作成します。この関数には fig と mode の 2 つのパラメータがあります。
def test_rotation_mode(fig, mode):
水平と垂直の配置リストを定義する
次に、サブプロットを作成する際に使用する水平と垂直の配置リストを定義します。各リストには 3 つの要素を作成します。水平配置には "left"、"center"、"right" を、垂直配置には "top"、"center"、"baseline"、"bottom" を使用します。
ha_list = ["left", "center", "right"]
va_list = ["top", "center", "baseline", "bottom"]
サブプロットを作成する
ここでは、subplots 関数を使ってサブプロットを作成します。同じアスペクト比のサブプロットのグリッドを作成し、x 軸と y 軸の目盛りを削除します。また、各サブプロットの中央に垂直と水平の線を追加して配置を視覚化しやすくします。
axs = fig.subplots(len(va_list), len(ha_list), sharex=True, sharey=True,
subplot_kw=dict(aspect=1),
gridspec_kw=dict(hspace=0, wspace=0))
for i, va in enumerate(va_list):
for j, ha in enumerate(ha_list):
ax = axs[i, j]
ax.set(xticks=[], yticks=[])
ax.axvline(0.5, color="skyblue", zorder=0)
ax.axhline(0.5, color="skyblue", zorder=0)
ax.plot(0.5, 0.5, color="C0", marker="o", zorder=1)
サブプロットにテキストを追加する
text 関数を使って各サブプロットにテキストを追加します。rotation、horizontalalignment、verticalalignment、rotation_mode の各パラメータを使ってテキストを回転させて配置します。また、bbox パラメータを使ってテキストの境界ボックスを強調します。
kw = (
{} if mode == "default" else
{"bbox": dict(boxstyle="square,pad=0.", ec="none", fc="C1", alpha=0.3)}
)
texts = {}
for i, va in enumerate(va_list):
for j, ha in enumerate(ha_list):
ax = axs[i, j]
tx = ax.text(0.5, 0.5, "Tpg",
size="x-large", rotation=40,
horizontalalignment=ha, verticalalignment=va,
rotation_mode=mode, **kw)
texts[ax] = tx
テキストの境界ボックスを強調する
rotation_mode が 'default' に設定されている場合、矩形を使ってテキストの境界ボックスを強調します。get_window_extent 関数を使って境界ボックスを取得し、transData 属性を使ってデータ座標に変換します。
if mode == "default":
fig.canvas.draw()
for ax, text in texts.items():
bb = text.get_window_extent().transformed(ax.transData.inverted())
rect = plt.Rectangle((bb.x0, bb.y0), bb.width, bb.height,
facecolor="C1", alpha=0.3, zorder=2)
ax.add_patch(rect)
サブフィギュアを作成して test_rotation_mode 関数を呼び出す
2 つのサブフィギュアを作成し、fig と mode のパラメータを使って test_rotation_mode 関数を呼び出します。
fig = plt.figure(figsize=(8, 5))
subfigs = fig.subfigures(1, 2)
test_rotation_mode(subfigs[0], "default")
test_rotation_mode(subfigs[1], "anchor")
plt.show()
まとめ
この実験では、Matplotlib で rotation_mode パラメータを使ってテキストを回転させる方法を学びました。異なる回転モードをテストするためのサブプロットを作成する test_rotation_mode という関数を作成しました。水平と垂直の配置リストを定義し、サブプロットを作成し、サブプロットにテキストを追加し、テキストの境界ボックスを強調しました。最後に、サブフィギュアを作成して test_rotation_mode 関数を呼び出しました。