Matplotlib によるデータ可視化

Beginner

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

はじめに

この実験では、Matplotlib を使ったデータ可視化の基本を紹介します。Matplotlib は、Python 用の人気のあるデータ可視化ライブラリで、グラフ、グラフ、チャートを作成するための幅広いオプションを提供します。

VM のヒント

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

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

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

セットアップ

始める前に、Matplotlib がインストールされていることを確認する必要があります。pip を使って、次のコマンドを実行することでインストールできます。

!pip install matplotlib

インストールが完了したら、ライブラリをインポートして環境をセットアップする必要があります。

import matplotlib.pyplot as plt
import numpy as np

## Fixing random state for reproducibility
np.random.seed(19680801)

## Create new Figure with black background
fig = plt.figure(figsize=(8, 8), facecolor='black')

## Add a subplot with no frame
ax = plt.subplot(frameon=False)

ランダムデータの生成

このステップでは、グラフを作成するために使用するランダムデータを生成します。

## Generate random data
data = np.random.uniform(0, 1, (64, 75))
X = np.linspace(-1, 1, data.shape[-1])
G = 1.5 * np.exp(-4 * X ** 2)

折れ線グラフの作成

前のステップで生成したランダムデータを使って折れ線グラフを作成します。

## Generate line plots
lines = []
for i in range(len(data)):
    ## Small reduction of the X extents to get a cheap perspective effect
    xscale = 1 - i / 200.
    ## Same for linewidth (thicker strokes on bottom)
    lw = 1.5 - i / 100.0
    line, = ax.plot(xscale * X, i + G * data[i], color="w", lw=lw)
    lines.append(line)

範囲の設定と目盛りの削除

このステップでは、y 軸の範囲を設定し、グラフから目盛りを削除します。

## Set y limit (or first line is cropped because of thickness)
ax.set_ylim(-1, 70)

## No ticks
ax.set_xticks([])
ax.set_yticks([])

タイトルの追加

グラフにタイトルを追加します。

## 2 part titles to get different font weights
ax.text(0.5, 1.0, "MATPLOTLIB ", transform=ax.transAxes,
        ha="right", va="bottom", color="w",
        family="sans-serif", fontweight="light", fontsize=16)
ax.text(0.5, 1.0, "UNCHAINED", transform=ax.transAxes,
        ha="left", va="bottom", color="w",
        family="sans-serif", fontweight="bold", fontsize=16)

グラフのアニメーション化

ここでは、データを右にシフトして新しい値を埋めることで、グラフをアニメーション化します。

import matplotlib.animation as animation

def update(*args):
    ## Shift all data to the right
    data[:, 1:] = data[:, :-1]

    ## Fill-in new values
    data[:, 0] = np.random.uniform(0, 1, len(data))

    ## Update data
    for i in range(len(data)):
        lines[i].set_ydata(i + G * data[i])

    ## Return modified artists
    return lines

## Construct the animation, using the update function as the animation director.
anim = animation.FuncAnimation(fig, update, interval=10, save_count=100)
plt.show()

まとめ

この実験では、Matplotlib を使ったデータ可視化の基礎を学びました。ランダムなデータを生成し、折れ線グラフを作成し、範囲を設定して目盛りを削除し、タイトルを追加し、グラフをアニメーション化しました。これらは基本的なものにすぎませんが、Matplotlib は可視化のカスタマイズと強化に関してさらに多くのオプションを提供しています。