如何调整 matplotlib 堆积条形图中的误差线位置?

问题描述 投票:0回答:0

我试图在 matplotlib 中绘制堆叠条形图,包括堆栈中每个切片的误差条。问题是,目前,误差条位于切片平均值的 y 方向上,导致它们聚集在图的底部。

如何调整误差条位置以将它们固定到堆叠条形图中的相应切片?

示例数据

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')

我用来绘图的代码:

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

python-3.x matplotlib plot stacked-chart stacked-bar-chart
© www.soinside.com 2019 - 2024. All rights reserved.