Matplotlib による時系列ヒストグラム

PythonPythonBeginner
今すぐ練習

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

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、大量の時系列データを効率的に可視化する方法を示します。これにより、目には直ぐには見えない潜在的な隠れたサブ構造やパターンを明らかにし、視覚的に魅力的な方法で表示することができます。

VMのヒント

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

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

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

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

このステップでは、この実験に必要なライブラリをインポートします。

import time
import matplotlib.pyplot as plt
import numpy as np

データを生成する

このステップでは、多数のランダムウォーク「ノイズ/バックグラウンド」系列の下に埋もれた複数の正弦波「信号」系列を生成します。バイアスのないガウス分布に従うランダムウォークと正弦波信号を生成します。

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

## Make some data; a 1D random walk + small fraction of sine waves
num_series = 1000
num_points = 100
SNR = 0.10  ## Signal to Noise Ratio
x = np.linspace(0, 4 * np.pi, num_points)

## Generate unbiased Gaussian random walks
Y = np.cumsum(np.random.randn(num_series, num_points), axis=-1)

## Generate sinusoidal signals
num_signal = round(SNR * num_series)
phi = (np.pi / 8) * np.random.randn(num_signal, 1)  ## small random offset
Y[-num_signal:] = (
    np.sqrt(np.arange(num_points))  ## random walk RMS scaling factor
    * (np.sin(x - phi)
       + 0.05 * np.random.randn(num_signal, num_points))  ## small random noise
)

折れ線グラフでデータを可視化する

このステップでは、生成したデータを折れ線グラフで可視化します。

## Plot series using `plot` and a small value of `alpha`.
## With this view, it is very difficult to observe the sinusoidal behavior because of how many overlapping series there are.
## It also takes a bit of time to run because so many individual artists need to be generated.
tic = time.time()
plt.plot(x, Y.T, color="C0", alpha=0.1)
toc = time.time()
plt.title("Line plot with alpha")
plt.show()
print(f"{toc-tic:.3f} sec. elapsed")

2次元ヒストグラム - 対数カラースケールでデータを可視化する

このステップでは、複数の時系列をヒストグラムに変換します。隠された信号がより明瞭になるだけでなく、はるかに高速な手順でもあります。対数カラースケールを使って2次元ヒストグラムに (x, y) の点をプロットします。

tic = time.time()

## Linearly interpolate between the points in each time series
num_fine = 800
x_fine = np.linspace(x.min(), x.max(), num_fine)
y_fine = np.concatenate([np.interp(x_fine, x, y_row) for y_row in Y])
x_fine = np.broadcast_to(x_fine, (num_series, num_fine)).ravel()

## Plot (x, y) points in 2d histogram with log colorscale
## It is pretty evident that there is some kind of structure under the noise
## You can tune vmax to make signal more visible
cmap = plt.colormaps["plasma"]
cmap = cmap.with_extremes(bad=cmap(0))
h, xedges, yedges = np.histogram2d(x_fine, y_fine, bins=[400, 100])
pcm = plt.pcolormesh(xedges, yedges, h.T, cmap=cmap,
                         norm="log", vmax=1.5e2, rasterized=True)
plt.colorbar(pcm, label="## points", pad=0)
plt.title("2D Histogram and Log Color Scale")
plt.show()

toc = time.time()
print(f"{toc-tic:.3f} sec. elapsed")

2次元ヒストグラム - 線形カラースケールでデータを可視化する

このステップでは、線形カラースケールを使ってデータを可視化します。

## Same data but on linear color scale
pcm = plt.pcolormesh(xedges, yedges, h.T, cmap=cmap,
                         vmax=1.5e2, rasterized=True)
plt.colorbar(pcm, label="## points", pad=0)
plt.title("2D Histogram and Linear Color Scale")
plt.show()

まとめ

この実験では、潜在的に隠された部分構造やパターンを明確にすることができ、視覚的に魅力的な方法で表示するために、多数の時系列を効率的に可視化する方法を学びました。多数のランダムウォーク「ノイズ/バックグラウンド」系列の下に埋もれた複数の正弦波「信号」系列を生成し、折れ線グラフと対数および線形カラースケールを持つ2次元ヒストグラムでデータを可視化しました。