I'm trying to superimpose some experimental data over some simulated data in a seaborn.barplot
. The issue is that I cannot figure out how to extract the bar locations on the x axis. Here's a minimal example:
simulated_data = pandas.DataFrame({
'condition': ['A']*4 + ['B']*4,
'Protein': ['w', 'x', 'y', 'z']*2,
'data': numpy.random.uniform(10, 11, 8)
})
experimental_data = pandas.DataFrame({
'condition': ['A']*4 + ['B']*4,
'Protein': ['w', 'x', 'y', 'z']*2,
'data': numpy.random.uniform(10, 11, 8)
})
errors = pandas.DataFrame({
'condition': ['A']*4 + ['B']*4,
'Protein': ['w', 'x', 'y', 'z']*2,
'data': numpy.random.uniform(0, 1, 8)
})
plt.figure()
seaborn.barplot(data=simulated_data, y='data', x='Protein', hue='condition')
plt.errorbar(range(simulated_data.shape[0]), experimental_data['data'], yerr=errors['data'],
marker='_', mec='blue', zorder=1, elinewidth=1, capsize=2, ecolor='blue',
linestyle="None", markersize=10
)
plt.show()
Then gives
How can I modify this code to get the errors in line with the bars?
You can get the x and y position of the bar patches using get_xy()
on the rectangle patches which will return a tuple of (x, y) coordinates. In order to get the coordinates in the centre of the bar you need to add on half of the bar width.
Note that you may have to increase the zorder in plt.errorbar
if you want them to appear on top of the bar plot
import seaborn as sns
plt.figure()
abar = sns.barplot(data=simulated_data, y='data', x='Protein', hue='condition')
x_list = []
for patch in abar.patches:
x_list.append(patch.get_xy()[0]+(patch._width/2))
plt.errorbar(x_list, experimental_data['data'], yerr=errors['data'],
marker='_', mec='blue', zorder=10, elinewidth=1, capsize=2, ecolor='blue',
linestyle="None", markersize=10)
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