Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly superimpose a matplotlib.errorbar onto a seaborn.barplot?

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

enter image description here

How can I modify this code to get the errors in line with the bars?

like image 464
CiaranWelsh Avatar asked Oct 18 '25 02:10

CiaranWelsh


1 Answers

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)

enter image description here

like image 137
DavidG Avatar answered Oct 20 '25 17:10

DavidG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!