Python Code Notes

Information by python engineer

【matplotlib.pyplot】エラーバー付きグラフを描画する方法【Python】

f:id:vigilantPotato:20190714135053p:plain
errorbarメソッドのyerrオプション及びxerrオプションを用いて、エラーバー付きのグラフを表示することができる。


【スポンサーリンク】


データの準備

モジュールのインポート及び使用するデータは以下の通り。

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)
y = 2.5 * np.sin(x / 20 * np.pi)

以下、subplotsメソッドを用いてグラフを描画する。subplotsの使い方は以下の記事を参照。

[↑ 目次へ]


エラー値が一定の場合

エラー値が一定の場合は、yerrオプションやxerrオプションに値を渡すだけでエラーバーの表示が可能。以下、例を示す。

y軸にエラーバーを表示

fig, ax = plt.subplots()
ax.errorbar(x, y, yerr=0.5)
f:id:vigilantPotato:20190714134909p:plain

x軸にエラーバーを表示

fig, ax = plt.subplots()
ax.errorbar(x, y, xerr=0.5)
f:id:vigilantPotato:20190714134921p:plain

[↑ 目次へ]


【スポンサーリンク】


ポイントごとに設定する場合

プロットのポイントごとにエラー値を個別設定する場合は、プロットデータと同じ長さのエラー値をyerrまたはxerrオプションに渡す。

yerr = np.linspace(0.05, 0.2, 10)
fig, ax = plt.subplots()
ax.errorbar(x, y, yerr=yerr)
f:id:vigilantPotato:20190714134934p:plain

[↑ 目次へ]


片側だけエラーバーを表示

uplimsオプション、またはlolimsオプションをTrueに設定すると、エラーバーを片側だけ表示することができる。uplimsをTrueにするとエラーバーの下側のみが表示され、lolimsをTrueにすると上側のみが表示される。また、これらのオプションを使用すると、エラーバーの先端に^が追加される。

yerr = np.linspace(0.05, 0.2, 10)
fig, ax = plt.subplots()
ax.errorbar(x, y+2, yerr=yerr, label="uplims", uplims=True)
ax.errorbar(x, y+1, yerr=yerr, label="lolims", lolims=True)
ax.errorbar(x, y, yerr=yerr, label="both", uplims=True, lolims=True)
ax.legend()
f:id:vigilantPotato:20190714135004p:plain

[↑ 目次へ]


エラーバーにキャップを表示

capsizeオプションを用いて、エラーバーに対して垂直方向にキャップを表示することができる。capsizeオプションに渡す値が、キャップの長さとなる。

yerr = np.linspace(0.05, 0.2, 10)
fig, ax = plt.subplots()
ax.errorbar(x, y, yerr=yerr, capsize=3)
f:id:vigilantPotato:20190714135053p:plain

[↑ 目次へ]


【スポンサーリンク】