I want to plot confidence intervals on a Seaborn barplot, but I already have the confidence intervals computed. How can I get Seaborn to plot my confidence intervals instead of trying to compute them itself?
For instance, suppose I have the following pandas DataFrame:
x = pd.DataFrame([
['Group 1', 0.5, 0.05],
['Group 1', 0.6, 0.07],
], columns=['Group', 'Mean', 'SD'])
How do I plot a bar chart with those means and standard deviations?
You could use seaborn to draw a bar chart without error bars. And then use matplotlib's errorbar
to add the error bars. The code below assumes the 'Group'
column contains two different values:
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
x = pd.DataFrame([
['Group 1', 0.5, 0.05],
['Group 2', 0.6, 0.07],
], columns=['Group', 'Mean', 'SD'])
ax = sns.barplot(data=x, x='Group', y='Mean', color='dodgerblue')
ax.errorbar(data=x, x='Group', y='Mean', yerr='SD', ls='', lw=3, color='black')
plt.show()
Here is an attempt with nested bars. The errorbars are first drawn to get their standard positions and the x-coordinates are extracted. Then the bars get removed and created again with a new position. I am not sure whether it will work under all circumstances.
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
x = pd.DataFrame([
['Group 1', 'A', 0.4, 0.08],
['Group 1', 'B', 0.5, 0.05],
['Group 1', 'C', 0.5, 0.02],
['Group 2', 'A', 0.6, 0.07],
['Group 2', 'B', 0.7, 0.09],
['Group 2', 'C', 0.7, 0.02],
['Group 3', 'A', 0.6, 0.07],
['Group 3', 'B', 0.2, 0.09],
['Group 3', 'C', 0.4, 0.11],
], columns=['Group', 'Subgroup', 'Mean', 'SD'])
num_hues = len(np.unique(x['Subgroup']))
ax = sns.barplot(data=x, x='Group', y='Mean', hue='Subgroup')
for (hue, df_hue), dogde_dist in zip(x.groupby('Subgroup'), np.linspace(-0.4, 0.4, 2 * num_hues + 1)[1::2]):
bars = ax.errorbar(data=df_hue, x='Group', y='Mean', yerr='SD', ls='', lw=3, color='black')
xys = bars.lines[0].get_xydata()
bars.remove()
ax.errorbar(data=df_hue, x=xys[:, 0] + dogde_dist, y='Mean', yerr='SD', ls='', lw=3, color='black')
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With