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 にお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。

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

まず、必要なライブラリをインポートする必要があります。それは NumPy と Matplotlib です。NumPy は数値計算に使用されるライブラリであり、Matplotlib はデータ可視化に使用されるライブラリです。

import matplotlib.pyplot as plt
import numpy as np

乱数シードを設定する

コードを実行するたびに同じ乱数が得られるようにするため、乱数シードを設定します。これはnp.random.seed()関数を使用して行います。

np.random.seed(19680801)

グラデーション画像関数を定義する

カラーマップに基づいてグラデーション画像を作成する関数を定義する必要があります。この関数は、軸オブジェクト、グラデーションの方向、および使用するカラーマップの範囲を受け取ります。その後、関数はグラデーション画像を生成して返します。

def gradient_image(ax, direction=0.3, cmap_range=(0, 1), **kwargs):
    """
    Draw a gradient image based on a colormap.

    Parameters
    ----------
    ax : Axes
        The axes to draw on.
    direction : float
        The direction of the gradient. This is a number in
        range 0 (=vertical) to 1 (=horizontal).
    cmap_range : float, float
        The fraction (cmin, cmax) of the colormap that should be
        used for the gradient, where the complete colormap is (0, 1).
    **kwargs
        Other parameters are passed on to `.Axes.imshow()`.
        In particular, *cmap*, *extent*, and *transform* may be useful.
    """
    phi = direction * np.pi / 2
    v = np.array([np.cos(phi), np.sin(phi)])
    X = np.array([[v @ [1, 0], v @ [1, 1]],
                  [v @ [0, 0], v @ [0, 1]]])
    a, b = cmap_range
    X = a + (b - a) / X.max() * X
    im = ax.imshow(X, interpolation='bicubic', clim=(0, 1),
                   aspect='auto', **kwargs)
    return im

グラデーションバー関数を定義する

次に、グラデーションバーを作成する関数を定義する必要があります。この関数は、軸オブジェクト、バーの x 座標と y 座標、バーの幅、およびバーの下端位置を受け取ります。その後、関数は各バーに対してグラデーション画像を作成して返します。

def gradient_bar(ax, x, y, width=0.5, bottom=0):
    for left, top in zip(x, y):
        right = left + width
        gradient_image(ax, extent=(left, right, bottom, top),
                       cmap=plt.cm.Blues_r, cmap_range=(0, 0.8))

グラフを作成する

これで、グラフを作成することができます。まず、グラフィックオブジェクトと軸オブジェクトを作成します。その後、軸の x 軸と y 軸の範囲を設定します。gradient_image()関数を使用してグラデーション背景を作成します。最後に、ランダムなデータセットを作成し、gradient_bar()関数を使用して棒グラフを作成します。

fig, ax = plt.subplots()
ax.set(xlim=(0, 10), ylim=(0, 1))

## background image
gradient_image(ax, direction=1, extent=(0, 1, 0, 1), transform=ax.transAxes,
               cmap=plt.cm.RdYlGn, cmap_range=(0.2, 0.8), alpha=0.5)

N = 10
x = np.arange(N) + 0.15
y = np.random.rand(N)
gradient_bar(ax, x, y, width=0.7)
plt.show()

まとめ

このチュートリアルでは、Matplotlib を使ってグラデーション付きの棒グラフを作成する方法を学びました。グラデーション画像関数とグラデーションバー関数を定義する方法、およびこれらの関数を使ってグラフを作成する方法を学びました。また、乱数シードを設定する方法と必要なライブラリをインポートする方法も学びました。