HBoxDivider と VBoxDivider を使った Matplotlib のサブプロットの配置

Beginner

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

はじめに

この実験では、HBoxDividerVBoxDivider クラスを使って Matplotlib でサブプロットを作成する方法を学びます。複数のサブプロットを配置するためにこれらのクラスをどのように使用できるかを、簡単な例を使って示します。

VM のヒント

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

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

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

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

まず、必要なライブラリである matplotlibnumpy をインポートします。

import matplotlib.pyplot as plt
import numpy as np

データを作成する

サブプロットのデータとして使用する 2 つの NumPy 配列を作成します。

arr1 = np.arange(20).reshape((4, 5))
arr2 = np.arange(20).reshape((5, 4))

HBoxDivider を使ってサブプロットを作成する

HBoxDivider クラスを使って横並びに 2 つのサブプロットを作成します。また、アスペクト比を維持したまま、軸の高さが等しくなるように軸の位置を調整します。

fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(arr1)
ax2.imshow(arr2)

pad = 0.5  ## pad in inches
divider = HBoxDivider(
    fig, 111,
    horizontal=[Size.AxesX(ax1), Size.Fixed(pad), Size.AxesX(ax2)],
    vertical=[Size.AxesY(ax1), Size.Scaled(1), Size.AxesY(ax2)])
ax1.set_axes_locator(divider.new_locator(0))
ax2.set_axes_locator(divider.new_locator(2))

plt.show()

VBoxDivider を使ってサブプロットを作成する

VBoxDivider クラスを使って上下に 2 つのサブプロットを作成します。また、アスペクト比を維持したまま、軸の幅が等しくなるように軸の位置を調整します。

fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.imshow(arr1)
ax2.imshow(arr2)

divider = VBoxDivider(
    fig, 111,
    horizontal=[Size.AxesX(ax1), Size.Scaled(1), Size.AxesX(ax2)],
    vertical=[Size.AxesY(ax1), Size.Fixed(pad), Size.AxesY(ax2)])

ax1.set_axes_locator(divider.new_locator(0))
ax2.set_axes_locator(divider.new_locator(2))

plt.show()

まとめ

この実験では、Matplotlib の HBoxDividerVBoxDivider クラスを使ってサブプロットを作成する方法を学びました。また、アスペクト比を維持したまま、軸の高さや幅が等しくなるように軸の位置を調整する方法を見ました。これらのクラスは、単一のグラフに複数のサブプロットを配置する必要がある場合に便利です。