Search code examples
pythonmatplotlibbar-chartanalysis

matplotlib bar chart with different error bars for each bar


I am trying to create a bar chart that shows the 95% confidence intervals for each group. Obviously as they are 95% confidence intervals they are asymmetrical. However, the problem I am having is that I can't work out how to make each 95%CI bar different for each group (ie. each bar) as obviously they are different for each.

My code is as follows:

meanPassivePSE = np.mean(PSE_PASSIVE)
stdPassivePSE = np.std(PSE_PASSIVE)
meanActivePSE= np.mean(PSE_ACTIVE_HUMAN)
stdActivePSE = np.std(PSE_ACTIVE_HUMAN)
meanRoboticPSE=np.mean(PSE_ACTIVE_ROBOT)
stdRoboticPSE = np.std(PSE_ACTIVE_ROBOT)


#95%conf intervals

confInterval95Passive = stats.norm.interval(0.95, loc=meanPassivePSE, scale=stdPassivePSE/np.sqrt(len(PSE_PASSIVE)))
confInterval95Active = stats.norm.interval(0.95, loc=meanActivePSE, scale=stdActivePSE/np.sqrt(len(PSE_ACTIVE_HUMAN)))
confInterval95Robot = stats.norm.interval(0.95, loc=meanRoboticPSE, scale=stdRoboticPSE/np.sqrt(len(PSE_ACTIVE_ROBOT)))


conditions = 'Passive', 'Active Human', 'Active Robot'
yPos = np.arange(len(conditions))
PSE = [meanPassivePSE, meanActivePSE, meanRoboticPSE]


plt.bar(yPos, PSE, align='center', alpha=0.5, color=('g','b','r'), yerr = (????) )
#plt.errorbar(confInterval95Passive[0], confInterval95Passive[1])

plt.xticks(yPos,conditions)
plt.ylabel('Point of Subject Equality (ms)')
plt.title('Average Point of Subjective Equality in each Condition')
plt.show()

So, for example:

`confInterval95Passive[0],confInterval95Passive[1] = 2.71596442574 4.13221200188`

But for each of the three groups (passive, active and robotic) these stats are different. So how do I make he bar chart have three different bars, with three different and asymmetrical error bars? I assume it should be dealt with in the 'yerr=' argument?

Thanks for any help!!


Solution

  • I resolved the issue like that:

    yerrs = [[meanPassivePSE-confInterval95Passive[0], confInterval95Active-confInterval95Active[0], confInterval95Robot-confInterval95Robot[0]],
    [[confInterval95Passive[1]-meanPassivePSE, confInterval95Active[1]-confInterval95Active, confInterval95Robot[1]-confInterval95Robot]]
    
    • ax.errorbars uses values to add/substract from mean values
    • Therefore the computed confidence intervals need to be normed by the mean-values
    • Later on ax.errorbars adds/substracts those values again.

    Now the parameter can be put into the bar()-method

    plt.bar(yPos, PSE, align='center', alpha=0.5, color=('g','b','r'), yerr = yerrs )