簡體   English   中英

硬編碼置信區間為條形圖中的胡須

[英]Hard coding confidence interval as whiskers in bar plot

因此,我計算了一組具有正態分布的數據的置信區間,我想將其繪制為數據均值條形圖上的胡須。 我嘗試對plt.bar使用yerr參數,但是它計算標准偏差而不是自信區間。我想在條形圖上看到相同的胡須可視化。 我有自信的時間間隔:

[(29600.87,39367.28),(37101.74,42849.60),(33661.12,41470.25),(46019.20,49577.80)]

這是我的代碼,我嘗試用自信的水平提供yerr參數,但效果不是很好。

means=[np.mean(df.iloc[x]) for x in range(len(df.index))]

CI=[st.t.interval(0.95, len(df.iloc[x])-1, loc=np.mean(df.iloc[x]), scale=st.sem(df.iloc[x])) for x in range(len(df.index))]

plt.figure()

plt.bar(x_axis, means, color='r',yerr=np.reshape(CI,(2,4))

plt.xticks(np.arange(1992,1996,1))

這是我得到的情節:

在此輸入圖像描述

以下應該做你想要的(假設你的錯誤是對稱的;如果沒有,那么你應該使用@ImportanceOfBeingErnest的回答); 情節看起來像這樣:

在此輸入圖像描述

使用一些內聯注釋生成它的代碼:

import matplotlib.pyplot as plt

# rough estimates of your means; replace by your actual values
means = [34500, 40000, 37500, 47800]

# the confidence intervals you provided
ci = [(29600.87, 39367.28), (37101.74, 42849.60), (33661.12, 41470.25), (46019.20, 49577.80)]

# get the range of the confidence interval
y_r = [means[i] - ci[i][1] for i in range(len(ci))]
plt.bar(range(len(means)), means, yerr=y_r, alpha=0.2, align='center')
plt.xticks(range(len(means)), [str(year) for year in range(1992, 1996)])
plt.show()

baryerr參數可用於將錯誤繪制為錯誤欄。 誤差定義為與某個值的偏差,即通常以y ± err的形式給出量。 這意味着置信區間為(y-err, y+err)
這可以倒置; 給定置信區間(a, b)和值y ,誤差將是yaby

在matplotlib條形圖中,錯誤格式可以是scalar | N, Nx1 or 2xN array-like scalar | N, Nx1 or 2xN array-like 由於我們無法知道prehands是否y值在區間內是對稱的,並且因為它對於不同的實現(條形)可能是不同的,所以我們需要在這里選擇2 x N -format。

下面的代碼顯示了如何做到這一點。

import numpy as np
import matplotlib.pyplot as plt

# given some mean values and their confidence intervals,
means = np.array([30, 100, 60, 80])
conf  = np.array([[24, 35],[90, 110], [52, 67], [71, 88]])

# calculate the error
yerr = np.c_[means-conf[:,0],conf[:,1]-means ].T
print (yerr) # prints [[ 6 10  8  9]
             #         [ 5 10  7  8]]

# and plot it on a bar chart
plt.bar(range(len(means)), means, yerr=yerr)
plt.xticks(range(len(means)))
plt.show()

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM