Matplotlib による段階的なヒストグラムのチュートリアル

Beginner

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

はじめに

Matplotlib は、Python におけるデータ可視化ライブラリです。折れ線グラフ、散布図、棒グラフ、ヒストグラムなど、幅広い種類の可視化を作成するために広く使用されています。このチュートリアルでは、Matplotlib を使って段階的なヒストグラムを作成することに焦点を当てます。

VM のヒント

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

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

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

必要なライブラリとモジュールをインポートする

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.patches import StepPatch

データを準備する

np.random.seed(0)
h, edges = np.histogram(np.random.normal(5, 3, 5000),
                        bins=np.linspace(0, 10, 20))

シンプルな段階ヒストグラムを作成する

plt.stairs(h, edges, label='Simple histogram')
plt.legend()
plt.show()

段階ヒストグラムのベースラインを変更する

plt.stairs(h, edges + 5, baseline=50, label='Modified baseline')
plt.legend()
plt.show()

エッジなしの段階ヒストグラムを作成する

plt.stairs(h, edges + 10, baseline=None, label='No edges')
plt.legend()
plt.show()

塗りつぶしたヒストグラムを作成する

plt.stairs(np.arange(1, 6, 1), fill=True,
              label='Filled histogram\nw/ automatic edges')
plt.legend()
plt.show()

ハッチ付きのヒストグラムを作成する

plt.stairs(np.arange(1, 6, 1)*0.3, np.arange(2, 8, 1),
              orientation='horizontal', hatch='//',
              label='Hatched histogram\nw/ horizontal orientation')
plt.legend()
plt.show()

StepPatch アーティストを作成する

patch = StepPatch(values=[1, 2, 3, 2, 1],
                  edges=range(1, 7),
                  label=('Patch derived underlying object\n'
                         'with default edge/facecolor behaviour'))
plt.gca().add_patch(patch)
plt.xlim(0, 7)
plt.ylim(-1, 5)
plt.legend()
plt.show()

積み重ねたヒストグラムを作成する

A = [[0, 0, 0],
     [1, 2, 3],
     [2, 4, 6],
     [3, 6, 9]]

for i in range(len(A) - 1):
    plt.stairs(A[i+1], baseline=A[i], fill=True)
plt.show()

.pyplot.step.pyplot.stairs を比較する

bins = np.arange(14)
centers = bins[:-1] + np.diff(bins) / 2
y = np.sin(centers / 2)

plt.step(bins[:-1], y, where='post', label='step(where="post")')
plt.plot(bins[:-1], y, 'o--', color='grey', alpha=0.3)

plt.stairs(y - 1, bins, baseline=None, label='stairs()')
plt.plot(centers, y - 1, 'o--', color='grey', alpha=0.3)
plt.plot(np.repeat(bins, 2), np.hstack([y[0], np.repeat(y, 2), y[-1]]) - 1,
         'o', color='red', alpha=0.2)

plt.legend()
plt.title('step() vs. stairs()')
plt.show()

まとめ

このチュートリアルでは、Matplotlib を使って段階的なヒストグラムを作成する基本方法について説明しました。シンプルな段階ヒストグラムを作成する方法、ヒストグラムのベースラインを変更する方法、塗りつぶしやハッチ付きのヒストグラムを作成する方法、積み重ねたヒストグラムを作成する方法を学びました。また、.pyplot.step.pyplot.stairs の違いを比較しました。