How do I offset error bars on the X axis when my X variable is categorical (matplotlib)

Viewed 467

I'm building a barplot in python using matplotlib and seaborn.barplot, the X-axis data is categorical with two paired bars for each category. I wish to show an error bar for only one of the two paired bars for each category. errorevery=2 allows me to apply the error bar for every other bar, but the error bar is positioned between the two bars, instead of in the middle of the first bar (see photo below).

Here's an example of my current code:

sns.barplot(y='val', x='category', data=df, ax=ax, hue='hue')
plt.errorbar('category','val',data=df, yerr=df.yerr, fmt='none', errorevery=2, color='black', capsize=5)

Current Plot

Current Plot

1 Answers

If your categories are coded as numbers, you can hack it like this: Add a new column to your DataFrame, containing the categories reduced by half a bar width:

df['category_shifted'] = df['category'] - 0.2

Then pass these adjusted values in the errorbar function call:

plt.errorbar('category_shifted', 'val', data=df, yerr=df.yerr, fmt='none', 
             errorevery=2, color='black', capsize=5)
Related