Matplotlib の fill_between と alpha

PythonPythonBeginner
今すぐ練習

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

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

はじめに

データ可視化では、グラフ上の特定の領域や範囲を強調する必要がある場合があります。Matplotlib のfill_between関数は、最小値と最大値の境界の間に陰影付き領域を生成するための便利なツールです。また、グラフの視覚的外観を向上させるためにも使用できます。alpha引数を使用すると、陰影付き領域の透明度を調整できます。この実験では、Matplotlib でfill_betweenalphaを使用して、より視覚的に魅力的で情報に富んだグラフを作成するいくつかの例を紹介します。

VM のヒント

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

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

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

fill_betweenを使った折れ線グラフの強化

最初の例では、fill_betweenを使って折れ線グラフをどのように強化するかを示します。Google の金融データを使って 2 つのサブプロットを作成します。1 つは単純な折れ線グラフで、もう 1 つは塗りつぶされた折れ線グラフです。

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

## load up some sample financial data
r = cbook.get_sample_data('goog.npz')['price_data'].view(np.recarray)

## create two subplots with the shared x and y axes
fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)

pricemin = r.close.min()

ax1.plot(r.date, r.close, lw=2)
ax2.fill_between(r.date, pricemin, r.close, alpha=0.7)

for ax in ax1, ax2:
    ax.grid(True)
    ax.label_outer()

ax1.set_ylabel('price')
fig.suptitle('Google (GOOG) daily closing price')
fig.autofmt_xdate()

fill_betweenを使って折れ線グラフを強化する方法の最初の例を示します。Google の金融データを使って 2 つのサブプロットを作成します。1 つは単純な折れ線グラフで、もう 1 つは塗りつぶされた折れ線グラフです。

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

## いくつかのサンプルの金融データを読み込む
r = cbook.get_sample_data('goog.npz')['price_data'].view(np.recarray)

## 共有の x 軸と y 軸を持つ 2 つのサブプロットを作成する
fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)

pricemin = r.close.min()

ax1.plot(r.date, r.close, lw=2)
ax2.fill_between(r.date, pricemin, r.close, alpha=0.7)

for ax in ax1, ax2:
    ax.grid(True)
    ax.label_outer()

ax1.set_ylabel('価格')
fig.suptitle('Google (GOOG) の日次終値')
fig.autofmt_xdate()

各サブプロットに対して、グリッドを表示し、外部のラベルを設定します。最初のサブプロットには y 軸のラベルを設定し、グラフ全体のタイトルを設定し、x 軸の日付を自動的に整形します。

alphaを使って色を柔らかくする

alpha引数は、視覚的に魅力的なプロットを作成するために色を柔らかくするためにも使用できます。次の例では、歩幅が抽出される正規分布の平均と標準偏差が異なる 2 つのランダムウォーカーの集団を計算します。集団の平均位置の標準偏差のプラスマイナス 1 をプロットするために塗りつぶされた領域を使用します。

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

Nsteps, Nwalkers = 100, 250
t = np.arange(Nsteps)

## an (Nsteps x Nwalkers) array of random walk steps
S1 = 0.004 + 0.02*np.random.randn(Nsteps, Nwalkers)
S2 = 0.002 + 0.01*np.random.randn(Nsteps, Nwalkers)

## an (Nsteps x Nwalkers) array of random walker positions
X1 = S1.cumsum(axis=0)
X2 = S2.cumsum(axis=0)

## Nsteps length arrays empirical means and standard deviations of both
## populations over time
mu1 = X1.mean(axis=1)
sigma1 = X1.std(axis=1)
mu2 = X2.mean(axis=1)
sigma2 = X2.std(axis=1)

## plot it!
fig, ax = plt.subplots(1)
ax.plot(t, mu1, lw=2, label='mean population 1')
ax.plot(t, mu2, lw=2, label='mean population 2')
ax.fill_between(t, mu1+sigma1, mu1-sigma1, facecolor='C0', alpha=0.4)
ax.fill_between(t, mu2+sigma2, mu2-sigma2, facecolor='C1', alpha=0.4)
ax.set_title(r'random walkers empirical $\mu$ and $\pm \sigma$ interval')
ax.legend(loc='upper left')
ax.set_xlabel('num steps')
ax.set_ylabel('position')
ax.grid()

alpha引数を使って色を柔らかくすることもできます。次の例では、歩幅が抽出される正規分布の平均と標準偏差が異なる 2 つのランダムウォーカーの集団を計算します。集団の平均位置の標準偏差のプラスマイナス 1 をプロットするために塗りつぶされた領域を使用します。

## 再現性のために乱数シードを固定する
np.random.seed(19680801)

Nsteps, Nwalkers = 100, 250
t = np.arange(Nsteps)

## ランダムウォークの歩幅の (Nsteps x Nwalkers) 配列
S1 = 0.004 + 0.02*np.random.randn(Nsteps, Nwalkers)
S2 = 0.002 + 0.01*np.random.randn(Nsteps, Nwalkers)

## ランダムウォーカーの位置の (Nsteps x Nwalkers) 配列
X1 = S1.cumsum(axis=0)
X2 = S2.cumsum(axis=0)

## 両方の集団の経験的な平均と標準偏差の Nsteps 長さの配列
## 時間経過とともに
mu1 = X1.mean(axis=1)
sigma1 = X1.std(axis=1)
mu2 = X2.mean(axis=1)
sigma2 = X2.std(axis=1)

## プロットする!
fig, ax = plt.subplots(1)
ax.plot(t, mu1, lw=2, label='平均集団 1')
ax.plot(t, mu2, lw=2, label='平均集団 2')
ax.fill_between(t, mu1+sigma1, mu1-sigma1, facecolor='C0', alpha=0.4)
ax.fill_between(t, mu2+sigma2, mu2-sigma2, facecolor='C1', alpha=0.4)
ax.set_title(r'ランダムウォーカーの経験的な$\mu$と$\pm \sigma$区間')
ax.legend(loc='左上')
ax.set_xlabel('ステップ数')
ax.set_ylabel('位置')
ax.grid()

whereを使った特定の領域の強調表示

whereキーワード引数は、グラフの特定の領域を強調表示する際に非常に便利です。whereは、x、ymin、および ymax 引数と同じ長さのブールマスクを取り、ブールマスクが True の領域のみを塗りつぶします。以下の例では、単一のランダムウォーカーをシミュレートし、集団位置の解析的な平均と標準偏差を計算します。集団平均は破線で表示され、平均からのプラス/マイナス 1 シグマの偏差は塗りつぶされた領域として表示されます。X > upper_boundの where マスクを使用して、ウォーカーが 1 シグマ境界外にある領域を見つけ、その領域を赤色で塗りつぶします。

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

Nsteps = 500
t = np.arange(Nsteps)

mu = 0.002
sigma = 0.01

## the steps and position
S = mu + sigma*np.random.randn(Nsteps)
X = S.cumsum()

## the 1 sigma upper and lower analytic population bounds
lower_bound = mu*t - sigma*np.sqrt(t)
upper_bound = mu*t + sigma*np.sqrt(t)

fig, ax = plt.subplots(1)
ax.plot(t, X, lw=2, label='walker position')
ax.plot(t, mu*t, lw=1, label='population mean', color='C0', ls='--')
ax.fill_between(t, lower_bound, upper_bound, facecolor='C0', alpha=0.4,
                label='1 sigma range')
ax.legend(loc='upper left')

## here we use the where argument to only fill the region where the
## walker is above the population 1 sigma boundary
ax.fill_between(t, upper_bound, X, where=X > upper_bound, fc='red', alpha=0.4)
ax.fill_between(t, lower_bound, X, where=X < lower_bound, fc='red', alpha=0.4)
ax.set_xlabel('num steps')
ax.set_ylabel('position')
ax.grid()

whereを使った特定の領域の強調表示

whereキーワード引数は、グラフの特定の領域を強調表示する際に非常に便利です。whereは、x、ymin、および ymax 引数と同じ長さのブールマスクを取り、ブールマスクが True の領域のみを塗りつぶします。以下の例では、単一のランダムウォーカーをシミュレートし、集団位置の解析的な平均と標準偏差を計算します。集団平均は破線で表示され、平均からのプラス/マイナス 1 シグマの偏差は塗りつぶされた領域として表示されます。X > upper_boundの where マスクを使用して、ウォーカーが 1 シグマ境界外にある領域を見つけ、その領域を赤色で塗りつぶします。

## 再現性のために乱数シードを固定する
np.random.seed(1)

Nsteps = 500
t = np.arange(Nsteps)

mu = 0.002
sigma = 0.01

## ステップと位置
S = mu + sigma*np.random.randn(Nsteps)
X = S.cumsum()

## 1 シグマの解析的な集団の上限と下限
lower_bound = mu*t - sigma*np.sqrt(t)
upper_bound = mu*t + sigma*np.sqrt(t)

fig, ax = plt.subplots(1)
ax.plot(t, X, lw=2, label='ウォーカーの位置')
ax.plot(t, mu*t, lw=1, label='集団平均', color='C0', ls='--')
ax.fill_between(t, lower_bound, upper_bound, facecolor='C0', alpha=0.4,
                label='1 シグマ範囲')
ax.legend(loc='左上')

## ここでは、where 引数を使用して、ウォーカーが集団の 1 シグマ境界を超えている領域のみを塗りつぶします
ax.fill_between(t, upper_bound, X, where=X > upper_bound, fc='red', alpha=0.4)
ax.fill_between(t, lower_bound, X, where=X < lower_bound, fc='red', alpha=0.4)
ax.set_xlabel('ステップ数')
ax.set_ylabel('位置')
ax.grid()

axhspanaxvspanを使った Axes の範囲の強調表示

塗りつぶされた領域のもう一つの便利な使い方は、Axes の水平または垂直の範囲を強調表示することです。そのために Matplotlib にはヘルパー関数axhspanaxvspanがあります。詳細については、axhspan_demoギャラリーを参照してください。

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.axhspan(0.25, 0.75, facecolor='0.5', alpha=0.5)
ax.axvspan(6, 7, facecolor='r', alpha=0.5)

plt.show()

まとめ

この実験では、Matplotlib のfill_between関数とalpha引数を使って、視覚的に魅力的で情報が豊富なグラフを作成する方法を学びました。fill_betweenalphaを使ってグラフの特定の領域や範囲を強調表示するいくつかの例を示しました。また、Axes の範囲を強調表示するためのaxhspan関数とaxvspan関数についても簡単に紹介しました。