Matplotlib のカスタム単位

Beginner

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

はじめに

Matplotlib は、Python プログラミング言語用のグラフ描画ライブラリです。Tkinter、wxPython、Qt、または GTK などの汎用 GUI ツールキットを使って、アプリケーションにグラフを埋め込むためのオブジェクト指向 API を提供します。Matplotlib を使うと、開発者は Python で幅広い種類の静的、アニメーション、およびインタラクティブなビジュアライゼーションを作成できます。

この実験では、Matplotlib でカスタム単位を作成し、これらのカスタム単位を使ってデータをプロットする方法を学びます。

VM のヒント

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

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

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

ライブラリのインポート

最初のステップでは、必要なライブラリ - matplotlib.pyplotnumpymatplotlib.ticker、およびmatplotlib.units をインポートする必要があります。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as ticker
import matplotlib.units as units

カスタム単位クラスの作成

このステップでは、カスタム単位クラス - Foo を作成します。このクラスは、「単位」に応じて変換と異なる目盛りの書式設定をサポートします。ここでの「単位」は、単なるスカラー変換係数です。

class Foo:
    def __init__(self, val, unit=1.0):
        self.unit = unit
        self._val = val * unit

    def value(self, unit):
        if unit is None:
            unit = self.unit
        return self._val / unit

コンバータークラスの作成

このステップでは、コンバータークラス - FooConverter を作成します。このクラスは、3 つの静的メソッド - axisinfoconvert、および default_units を定義します。

class FooConverter(units.ConversionInterface):
    @staticmethod
    def axisinfo(unit, axis):
        """Return the Foo AxisInfo."""
        if unit == 1.0 or unit == 2.0:
            return units.AxisInfo(
                majloc=ticker.IndexLocator(8, 0),
                majfmt=ticker.FormatStrFormatter("VAL: %s"),
                label='foo',
                )

        else:
            return None

    @staticmethod
    def convert(obj, unit, axis):
        """
        Convert *obj* using *unit*.

        If *obj* is a sequence, return the converted sequence.
        """
        if np.iterable(obj):
            return [o.value(unit) for o in obj]
        else:
            return obj.value(unit)

    @staticmethod
    def default_units(x, axis):
        """Return the default unit for *x* or None."""
        if np.iterable(x):
            for thisx in x:
                return thisx.unit
        else:
            return x.unit

カスタム単位クラスの登録

このステップでは、カスタム単位クラス - Foo をコンバータークラス - FooConverter に登録します。

units.registry[Foo] = FooConverter()

データポイントの作成

このステップでは、カスタム単位クラス - Foo を使用していくつかのデータポイントを作成します。

## create some Foos
x = [Foo(val, 1.0) for val in range(0, 50, 2)]
## and some arbitrary y data
y = [i for i in range(len(x))]

グラフの作成

このステップでは、2 つのグラフを作成します。1 つはカスタム単位を使用して、もう 1 つは既定の単位を使用して作成します。

fig, (ax1, ax2) = plt.subplots(1, 2)
fig.suptitle("Custom units")
fig.subplots_adjust(bottom=0.2)

## plot specifying units
ax2.plot(x, y, 'o', xunits=2.0)
ax2.set_title("xunits = 2.0")
plt.setp(ax2.get_xticklabels(), rotation=30, ha='right')

## plot without specifying units; will use the None branch for axisinfo
ax1.plot(x, y)  ## uses default units
ax1.set_title('default units')
plt.setp(ax1.get_xticklabels(), rotation=30, ha='right')

plt.show()

コードを実行する

最後のステップでは、カスタム単位のグラフを作成するためにコードを実行します。

まとめ

この実験では、Matplotlib でカスタム単位クラスとコンバータークラスを使用してカスタム単位を作成する方法を学びました。その後、カスタム単位を使用したグラフと既定の単位を使用したグラフの 2 つを作成して、これらのカスタム単位の使い方を示しました。カスタム単位は、カスタムスケーリングや目盛りの書式設定が必要な複雑なデータを扱う際に役立つ場合があります。