物理のバス停 by salt22g

とある物理学見習いの備忘録。

matplotlibで統計・系統誤差付きの図を作る(python)

かなり久々の更新。

matplotlibとpythonで統計誤差、系統誤差を描写する簡単なスクリプト
こんな感じの図が書けます(今回は横軸Event No、縦軸が測定値や誤差など)

統計誤差を棒、系統誤差をboxで描写


Eventごとに統計誤差、系統誤差が異なる場合の絵ですね。
同じ研究対象に対するいくつかの実験結果をまとめる際などに使われがちです。

他にいい方法をご存知の方がいましたらご教授ください。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import random

if __name__ == '__main__':

    mean_values = np.random.normal(100, 20, 10)  # 平均100、標準偏差20、event数10
    stat_errors = np.random.normal(20, 5, 10)  # 測定誤差の平均が20、ばらつきが5

    # 正負に非対称な誤差がつくことを想定
    syst_errors = []
    for i in range(len(mean_values)):
        syst_high = random.uniform(5, 10)
        syst_low = random.uniform(5, 10)
        syst_errors.append([syst_high, syst_low])


    fig, ax = plt.subplots()

    #Eventに番号付け
    events = list(range(len(mean_values)))

    # 誤差棒ありのplot
    plt.errorbar(events, mean_values, stat_errors, capsize=5, fmt='o', markersize=5, ecolor='black', markeredgecolor="black", color='k')

    # 各Eventで系統誤差を示すboxを描写
    event_counter = 0
    for meam, syst in zip(mean_values, syst_errors):
        r = patches.Rectangle(xy=(event_counter-0.2, meam-syst[1]), width=0.4, height=sum(syst), ec='k', fill=False)
        ax.add_patch(r)
        event_counter += 1

    ax.set_xticks(range(10))
    plt.show()


ポイントはmatplotlib.patchesです。
note.nkmk.me

matplotlibにはeventplotという関数があって名前がそれっぽいと思ったのですが全然違いました…