2

Im trying to plot a stacked bar plot in matplotlib including error bars for each slice in the stack. The problem is, that at the moment, the error bars are positioned in y-orientation at the mean value of the slice, causing them to clump at the bottom of the plot.

How to adjust the error bar position to fixate them to their corresponding slice in the stacked bar plot?

Example Data

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data = {
    'class': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C'],
    1: [0.329705, 0.671022, 0.668366, 0.065326, 0.169130, 0.211676, 0.064732, 0.927455, 0.203308, 0.002299, 0.322461, 0.092376],
    2: [0.582468, 0.969697, 0.729358, 0.565941, 0.886812, 0.246542, 0.272845, 0.267764, 0.218754, 0.296160, 0.289441, 0.491691],
    3: [0.760131, 0.175007, 0.625848, 0.544123, 0.199601, 0.804688, 0.019928, 0.863459, 0.173769, 0.379593, 0.137946, 0.534573],
    4: [0.240984, 0.564373, 0.810989, 0.554100, 0.151519, 0.237268, 0.991679, 0.899854, 0.998449, 0.896210, 0.698002, 0.695594],
    5: [0.768396, 0.937719, 0.634198, 0.551964, 0.895280, 0.988008, 0.783552, 0.098560, 0.921954, 0.007269, 0.040120, 0.364231],
    6: [0.469820, 0.570865, 0.559299, 0.024383, 0.985258, 0.580174, 0.371842, 0.143537, 0.162110, 0.452698, 0.354060, 0.853589],
    7: [0.368209, 0.673083, 0.555111, 0.520188, 0.612360, 0.957880, 0.806270, 0.763971, 0.330368, 0.210543, 0.401879, 0.952164],
    8: [0.099985, 0.727631, 0.723997, 0.401070, 0.684621, 0.699878, 0.595760, 0.945066, 0.485593, 0.213349, 0.751918, 0.180683]
}

df = pd.DataFrame(data)

df_grouped = df.groupby('class')

The code I used for plotting:

fig, ax = plt.subplots()
for i,col in enumerate(df_grouped.mean().columns):
    ax.bar(df_grouped.mean().index, height=df_grouped.mean()[col], bottom=df_grouped.mean().iloc[:,:i].sum(axis=1), width=0.85)

    ax.errorbar(df_grouped.mean().index, df_grouped.mean()[col], yerr=df_grouped.std()[col], fmt='none', ecolor='black', capsize=3, capthick=2)

Example Stacked Plot with Error Bars

yhgsag
  • 39
  • 5

0 Answers0