工学表記を使った目盛りのラベリング

Beginner

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

はじめに

データ可視化において、軸の目盛りに正確にラベルを付けることは不可欠です。Matplotlib の EngFormatter は、工学表記を使って軸の目盛りにラベルを付けることができるクラスです。工学表記は、10 の累乗を 3 の倍数で用いた数の数学的表現です。これは、標準表記で読み書きが難しい大きな数や小さな数を表現するための簡潔な方法です。この実験では、工学表記を使って軸の目盛りにラベルを付ける方法を学びます。

VM のヒント

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

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

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

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

最初のステップは、必要なライブラリをインポートすることです。この実験では、MatplotlibNumPy、および EngFormatter を使用します。

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import EngFormatter

人工データを作成する

描画するためにいくつかの人工データを作成する必要があります。この実験では、周波数(Hz)の対数に対して電力(ワット)の対数をプロットします。データの生成には numpy ライブラリを使用します。

## Fixing random state for reproducibility
prng = np.random.RandomState(19680801)

## Create artificial data to plot.
## The x data span over several decades to demonstrate several SI prefixes.
xs = np.logspace(1, 9, 100)
ys = (0.8 + 0.4 * prng.uniform(size=100)) * np.log10(xs)**2

グラフとサブプロットを作成する

データを表示するためにグラフとサブプロットを作成する必要があります。この実験では、横並びに 2 つのサブプロットを作成します。

## Figure width is doubled (2*6.4) to display nicely 2 subplots side by side.
fig, (ax0, ax1) = plt.subplots(nrows=2, figsize=(7, 9.6))
for ax in (ax0, ax1):
    ax.set_xscale('log')

工学表記を使って目盛りにラベルを付ける

次に、x 軸の目盛りに工学表記を使ってラベルを付けます。最初のサブプロットではデフォルト設定を使用し、2 番目のサブプロットでは placessep オプションを使って小数点以下の桁数と数値と接頭辞/単位の間の区切り文字を指定します。

## Demo of the default settings, with a user-defined unit label.
ax0.set_title('Full unit ticklabels, w/ default precision & space separator')
formatter0 = EngFormatter(unit='Hz')
ax0.xaxis.set_major_formatter(formatter0)
ax0.plot(xs, ys)
ax0.set_xlabel('Frequency')

## Demo of the options `places` (number of digit after decimal point) and
## `sep` (separator between the number and the prefix/unit).
ax1.set_title('SI-prefix only ticklabels, 1-digit precision & '
              'thin space separator')
formatter1 = EngFormatter(places=1, sep="\N{THIN SPACE}")  ## U+2009
ax1.xaxis.set_major_formatter(formatter1)
ax1.plot(xs, ys)
ax1.set_xlabel('Frequency [Hz]')

グラフを表示する

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

plt.tight_layout()
plt.show()

まとめ

この実験では、工学表記を使って軸の目盛りにラベルを付ける方法を学びました。Matplotlib の EngFormatter クラスを使って、グラフの x 軸の目盛りにラベルを付けました。また、サブプロットを作成し、EngFormatterplacessep オプションを使って目盛りのラベルをカスタマイズする方法も学びました。工学表記は、標準表記で読み書きが難しい大きな数や小さな数を表現するための簡潔で明確な方法です。