Matplotlib で軸の方向を変更する

Beginner

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

はじめに

この実験では、set_axis_direction() メソッドを使用して Matplotlib のプロットの軸の方向を変更する方法を学びます。このメソッドを使用すると、軸の方向を上、下、左、右の 4 つの基本方向のいずれかに変更できます。

VM のヒント

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

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

学習中に問題が発生した場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。

ライブラリのインポート

まず、この実験に必要なライブラリをインポートする必要があります。numpymatplotlib を使用します。

import matplotlib.pyplot as plt
import numpy as np

プロットの設定

次に、矩形ボックス内で極座標投影を設定する setup_axes() 関数を定義します。この関数は、GridHelperCurveLinear を使用して矩形ボックスで極座標投影を作成します。

from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
import mpl_toolkits.axisartist as axisartist
import mpl_toolkits.axisartist.angle_helper as angle_helper
import mpl_toolkits.axisartist.grid_finder as grid_finder
from mpl_toolkits.axisartist.grid_helper_curvelinear import \
    GridHelperCurveLinear

def setup_axes(fig, rect):
    """Polar projection, but in a rectangular box."""
    grid_helper = GridHelperCurveLinear(
        Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform(),
        extreme_finder=angle_helper.ExtremeFinderCycle(
            20, 20,
            lon_cycle=360, lat_cycle=None,
            lon_minmax=None, lat_minmax=(0, np.inf),
        ),
        grid_locator1=angle_helper.LocatorDMS(12),
        grid_locator2=grid_finder.MaxNLocator(5),
        tick_formatter1=angle_helper.FormatterDMS(),
    )
    ax = fig.add_subplot(
        rect, axes_class=axisartist.Axes, grid_helper=grid_helper,
        aspect=1, xlim=(-5, 12), ylim=(-5, 10))
    ax.axis[:].toggle(ticklabels=False)
    ax.grid(color=".9")
    return ax

浮動軸の追加

浮動軸をプロットに追加する 2 つの関数を定義します。最初の関数 add_floating_axis1() は、theta = 30 のラベル付きで浮動軸をプロットに追加します。2 番目の関数 add_floating_axis2() は、r = 6 のラベル付きで浮動軸をプロットに追加します。

def add_floating_axis1(ax):
    ax.axis["lat"] = axis = ax.new_floating_axis(0, 30)
    axis.label.set_text(r"$\theta = 30^{\circ}$")
    axis.label.set_visible(True)
    return axis

def add_floating_axis2(ax):
    ax.axis["lon"] = axis = ax.new_floating_axis(1, 6)
    axis.label.set_text(r"$r = 6$")
    axis.label.set_visible(True)
    return axis

軸の方向の変更

次に、4 つの基本方向それぞれに浮動軸を持つ 4 つの異なるプロットを設定するためのループを作成します。ループ内では、浮動軸を追加するために add_floating_axis1()add_floating_axis2() を使用し、軸の方向を設定するために set_axis_direction() を使用します。

fig = plt.figure(figsize=(8, 4), layout="constrained")

for i, d in enumerate(["bottom", "left", "top", "right"]):
    ax = setup_axes(fig, rect=241+i)
    axis = add_floating_axis1(ax)
    axis.set_axis_direction(d)
    ax.set(title=d)

for i, d in enumerate(["bottom", "left", "top", "right"]):
    ax = setup_axes(fig, rect=245+i)
    axis = add_floating_axis2(ax)
    axis.set_axis_direction(d)
    ax.set(title=d)

plt.show()

プロットの表示

最後に、プロットを表示します。4 つの基本方向それぞれに浮動軸を持つ同じプロットが表示されます。

まとめ

この実験では、set_axis_direction() メソッドを使用して Matplotlib のプロットで軸の方向を変更する方法を学びました。このメソッドを使用することで、軸の方向を上、下、左、右の 4 つの基本方向のいずれかに簡単に変更できます。