Matplotlib の目盛りフォーマッタチュートリアル

Beginner

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

はじめに

Matplotlib は、高品質の 2 次元および 3 次元グラフを生成する、広く使用される Python のグラフ作成ライブラリです。この実験では、Matplotlib で目盛りフォーマッタを使用する方法を学びます。

VM のヒント

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

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

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

Matplotlib のインポートとグラフの設定

まず、Matplotlib ライブラリをインポートしてグラフを設定します。1 つの y 軸と 1 つの x 軸を持つ空のグラフを作成します。また、軸を設定して下側の目盛り線のみを表示し、目盛りの位置を設定し、目盛りの長さを定義します。

import matplotlib.pyplot as plt
from matplotlib import ticker

def setup(ax, title):
    """Set up common parameters for the Axes in the example."""
    ## only show the bottom spine
    ax.yaxis.set_major_locator(ticker.NullLocator())
    ax.spines[['left', 'right', 'top']].set_visible(False)

    ## define tick positions
    ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
    ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))

    ax.xaxis.set_ticks_position('bottom')
    ax.tick_params(which='major', width=1.00, length=5)
    ax.tick_params(which='minor', width=0.75, length=2.5, labelsize=10)
    ax.set_xlim(0, 5)
    ax.set_ylim(0, 1)
    ax.text(0.0, 0.2, title, transform=ax.transAxes,
            fontsize=14, fontname='Monospace', color='tab:blue')


fig, ax = plt.subplots(figsize=(8, 2))
setup(ax, "Tick Formatters")

Matplotlib をインポートしてグラフを設定する

まず、Matplotlib ライブラリをインポートしてグラフを設定します。1 つの y 軸と 1 つの x 軸を持つ空のグラフを作成します。また、軸を設定して下側の目盛り線のみを表示し、目盛りの位置を設定し、目盛りの長さを定義します。

import matplotlib.pyplot as plt
from matplotlib import ticker

def setup(ax, title):
    """この例での Axes の共通パラメータを設定します。"""
    ## 下側の目盛り線のみを表示
    ax.yaxis.set_major_locator(ticker.NullLocator())
    ax.spines[['left', 'right', 'top']].set_visible(False)

    ## 目盛りの位置を定義
    ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
    ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))

    ax.xaxis.set_ticks_position('bottom')
    ax.tick_params(which='major', width=1.00, length=5)
    ax.tick_params(which='minor', width=0.75, length=2.5, labelsize=10)
    ax.set_xlim(0, 5)
    ax.set_ylim(0, 1)
    ax.text(0.0, 0.2, title, transform=ax.transAxes,
            fontsize=14, fontname='Monospace', color='tab:blue')


fig, ax = plt.subplots(figsize=(8, 2))
setup(ax, "Tick Formatters")

単純なフォーマット

このステップでは、文字列を渡すか関数を ~.Axis.set_major_formatter または ~.Axis.set_minor_formatter に渡すことで、単純なフォーマッタをどのように使用するかを示します。2 つのグラフを作成し、1 つは文字列フォーマッタを使用し、もう 1 つは関数フォーマッタを使用します。

fig0, axs0 = plt.subplots(2, 1, figsize=(8, 2))
fig0.suptitle('Simple Formatting')

## ``str`` は、フォーマット文字列関数構文を使用して、直接フォーマッタとして使用できます。
## 変数 ``x`` は目盛り値で、変数 ``pos`` は目盛り位置です。
## これにより、自動的に StrMethodFormatter が作成されます。
setup(axs0[0], title="'{x} km'")
axs0[0].xaxis.set_major_formatter('{x} km')

## 関数も直接フォーマッタとして使用できます。
## この関数は 2 つの引数を取る必要があります。
## 目盛り値用の ``x`` と目盛り位置用の ``pos`` で、
## そして ``str`` を返す必要があります。
## これにより、自動的に FuncFormatter が作成されます。
setup(axs0[1], title="lambda x, pos: str(x-5)")
axs0[1].xaxis.set_major_formatter(lambda x, pos: str(x-5))

fig0.tight_layout()

単純なフォーマット

このステップでは、文字列を渡すか関数を ~.Axis.set_major_formatter または ~.Axis.set_minor_formatter に渡すことで、単純なフォーマッタをどのように使用するかを示します。2 つのグラフを作成し、1 つは文字列フォーマッタを使用し、もう 1 つは関数フォーマッタを使用します。

fig0, axs0 = plt.subplots(2, 1, figsize=(8, 2))
fig0.suptitle('Simple Formatting')

## 「str」は、フォーマット文字列関数構文を使用して、直接フォーマッタとして使用できます。
## 変数「x」は目盛り値で、変数「pos」は目盛り位置です。
## これにより、自動的に StrMethodFormatter が作成されます。
setup(axs0[0], title="'{x} km'")
axs0[0].xaxis.set_major_formatter('{x} km')

## 関数も直接フォーマッタとして使用できます。
## この関数は 2 つの引数を取る必要があります。
## 目盛り値用の「x」と目盛り位置用の「pos」で、
## そして「str」を返す必要があります。
## これにより、自動的に FuncFormatter が作成されます。
setup(axs0[1], title="lambda x, pos: str(x-5)")
axs0[1].xaxis.set_major_formatter(lambda x, pos: str(x-5))

fig0.tight_layout()

フォーマッタオブジェクトによるフォーマット

このステップでは、.Formatter オブジェクトを使って目盛りをフォーマットします。7 つのグラフを作成し、それぞれ異なるフォーマッタを使用します。

fig1, axs1 = plt.subplots(7, 1, figsize=(8, 6))
fig1.suptitle('Formatter Object Formatting')

## Null フォーマッタ
setup(axs1[0], title="NullFormatter()")
axs1[0].xaxis.set_major_formatter(ticker.NullFormatter())

## StrMethod フォーマッタ
setup(axs1[1], title="StrMethodFormatter('{x:.3f}')")
axs1[1].xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.3f}"))

## FuncFormatter はデコレータとして使用できます
@ticker.FuncFormatter
def major_formatter(x, pos):
    return f'[{x:.2f}]'

setup(axs1[2], title='FuncFormatter("[{:.2f}]".format)')
axs1[2].xaxis.set_major_formatter(major_formatter)

## Fixed フォーマッタ
setup(axs1[3], title="FixedFormatter(['A', 'B', 'C',...])")
## FixedFormatter は FixedLocator と一緒にのみ使用する必要があります。
## そうでない場合、ラベルがどこに表示されるかを確認できません。
positions = [0, 1, 2, 3, 4, 5]
labels = ['A', 'B', 'C', 'D', 'E', 'F']
axs1[3].xaxis.set_major_locator(ticker.FixedLocator(positions))
axs1[3].xaxis.set_major_formatter(ticker.FixedFormatter(labels))

## スカラーフォーマッタ
setup(axs1[4], title="ScalarFormatter()")
axs1[4].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))

## FormatStr フォーマッタ
setup(axs1[5], title="FormatStrFormatter('#%d')")
axs1[5].xaxis.set_major_formatter(ticker.FormatStrFormatter("#%d"))

## パーセントフォーマッタ
setup(axs1[6], title="PercentFormatter(xmax=5)")
axs1[6].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5))

fig1.tight_layout()

フォーマッタオブジェクトによるフォーマット

このステップでは、.Formatter オブジェクトを使って目盛りをフォーマットします。7 つのグラフを作成し、それぞれ異なるフォーマッタを使用します。

fig1, axs1 = plt.subplots(7, 1, figsize=(8, 6))
fig1.suptitle('Formatter Object Formatting')

## Null フォーマッタ
setup(axs1[0], title="NullFormatter()")
axs1[0].xaxis.set_major_formatter(ticker.NullFormatter())

## StrMethod フォーマッタ
setup(axs1[1], title="StrMethodFormatter('{x:.3f}')")
axs1[1].xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.3f}"))

## FuncFormatter はデコレータとして使用できます
@ticker.FuncFormatter
def major_formatter(x, pos):
    return f'[{x:.2f}]'

setup(axs1[2], title='FuncFormatter("[{:.2f}]".format)')
axs1[2].xaxis.set_major_formatter(major_formatter)

## Fixed フォーマッタ
setup(axs1[3], title="FixedFormatter(['A', 'B', 'C',...])")
## FixedFormatter は FixedLocator と一緒にのみ使用する必要があります。
## そうでない場合、ラベルがどこに表示されるかを確認できません。
positions = [0, 1, 2, 3, 4, 5]
labels = ['A', 'B', 'C', 'D', 'E', 'F']
axs1[3].xaxis.set_major_locator(ticker.FixedLocator(positions))
axs1[3].xaxis.set_major_formatter(ticker.FixedFormatter(labels))

## スカラーフォーマッタ
setup(axs1[4], title="ScalarFormatter()")
axs1[4].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))

## FormatStr フォーマッタ
setup(axs1[5], title="FormatStrFormatter('#%d')")
axs1[5].xaxis.set_major_formatter(ticker.FormatStrFormatter("#%d"))

## パーセントフォーマッタ
setup(axs1[6], title="PercentFormatter(xmax=5)")
axs1[6].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5))

fig1.tight_layout()

グラフの表示

最後に、plt.show() を使ってグラフを表示します。

plt.show()

まとめ

この実験では、文字列を渡すか関数を ~.Axis.set_major_formatter または ~.Axis.set_minor_formatter に渡すことで、あるいはさまざまな ~.ticker.Formatter クラスのインスタンスを作成して ~.Axis.set_major_formatter または ~.Axis.set_minor_formatter に渡すことで、Matplotlib における目盛りフォーマッタをどのように使用するかを学びました。また、目盛りの位置、目盛りの長さ、タイトルを設定してグラフを作成する方法も学びました。