【问题标题】:Hard coding confidence interval as whiskers in bar plot硬编码置信区间作为条形图中的胡须
【发布时间】:2017-03-21 06:31:39
【问题描述】:

因此,我计算了一组具有正态分布的数据的置信区间,我想将其绘制为数据均值条形图上的须线。我尝试对 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))

这是我得到的情节:

【问题讨论】:

    标签: python matplotlib scipy


    【解决方案1】:

    以下应该做你想做的(假设你的错误是对称的;如果不是,那么你应该使用@ImportanceOfBeingErnest 的答案);情节如下所示:

    使用一些内联 cmets 生成它的代码:

    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()
    

    【讨论】:

    • 谢谢!!这就是我最终做的事情
    【解决方案2】:

    baryerr 参数可用于将错误绘制为错误栏。误差被定义为与某个值的偏差,即通常以y ± err 的形式给出数量。这意味着置信区间将为(y-err, y+err)
    这可以倒置;给定置信区间(a, b) 和值y,错误将是y-ab-y

    在 matplotlib 条形图中,错误格式可以是 scalar | N, Nx1 or 2xN array-like。由于我们无法事先知道y 值是否在区间内对称,并且由于不同的实现(条形)可能不同,因此我们需要在此处选择2 x N 格式。

    下面的代码展示了如何做到这一点。

    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()
    

    【讨论】:

    • 像往常一样,如果有人投了反对票,他们应该解释原因,以便改进答案。
    • 对我来说似乎很好。我赞成它,首先是因为它回答了问题,其次它比我发布的更笼统。我假设对称错误,然后它变得有点简单......
    • 谢谢!正如 Cleb 指出的那样,我将错误修改为对称的。
    猜你喜欢
    • 2022-11-18
    • 2020-02-27
    • 2019-11-08
    • 2021-04-08
    • 2012-11-17
    • 2016-02-24
    • 1970-01-01
    • 2018-08-06
    • 2012-12-04
    相关资源
    最近更新 更多