You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Seaborn分组柱状图中指定自定义误差棒值?

问题解决:Seaborn Barplot添加误差棒报错及误差值转换

问题背景

现有如下DataFrame:

import pandas as pd
data = pd.DataFrame([
    ["A", "gelu", 0.896048951, 0.897377622, 0.893671329],
    ["A", "hard_tanh", 0.889965035, 0.891643357, 0.888566434],
    ["A", "leaky_relu", 0.89527972, 0.896818182, 0.89451049],
    ["A", "relu", 0.893811189, 0.896748252, 0.891853147],
    ["A", "tanh", 0.892272727, 0.894230769, 0.889685315],
    ["B", "gelu", 0.896048951, 0.897377622, 0.893671329],
    ["B", "hard_tanh", 0.889965035, 0.891643357, 0.888566434],
    ["B", "leaky_relu", 0.89527972, 0.896818182, 0.89451049],
    ["B", "relu", 0.893811189, 0.896748252, 0.891853147],
    ["B", "tanh", 0.892272727, 0.894230769, 0.889685315],
], columns=["mode", "act_fn", "accuracy", "y_err1", "y_err2"])

使用Seaborn绘制带误差棒的柱状图时,添加yerr参数报错:

'yerr' (shape: (2, 5)) must be a scalar or a 1D or (2, n) array-like whose shape matches 'y' (shape: (1,))

同时需要将y_err1(误差上限)、y_err2(误差下限)从绝对值转换为相对于accuracy的差值。

解决方案

1. 转换误差值为相对差值

y_err1和y_err2是误差的绝对上下限,需要计算相对于accuracy的差值:

  • 上限误差:upper_err = y_err1 - accuracy
  • 下限误差:lower_err = accuracy - y_err2

代码实现:

# 计算相对误差值
data['upper_err'] = data['y_err1'] - data['accuracy']
data['lower_err'] = data['accuracy'] - data['y_err2']

2. 准备符合要求的yerr格式

Seaborn的barplot中,当使用hue参数时,y轴数据长度等于DataFrame的总行数(此处为10),因此yerr需要是**(2, n)**形状的数组(n为数据行数),或者是每个元素包含上下误差的列表。

方法一:转换为(2, n)数组

# 转换为(2, 10)的数组,第一行是下限误差,第二行是上限误差
yerr = data[['lower_err', 'upper_err']].T.to_numpy()

方法二:使用上下误差对的列表

# 生成每个数据点的上下误差对列表
yerr = list(zip(data['lower_err'], data['upper_err']))

3. 绘制带误差棒的柱状图

调用seaborn.barplot并传入处理好的yerr:

import seaborn as sns
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
sns.barplot(
    data=data,
    x="act_fn",
    y="accuracy",
    hue="mode",
    yerr=yerr,
    ax=ax
)
plt.show()

报错原因说明

之前报错是因为yerr的形状与y轴数据不匹配:

  • 当使用hue="mode"时,每个act_fn对应2个柱子,总共有10个数据点(y轴数据长度为10)
  • 之前的yerr是(2,5)的形状,仅对应5个act_fn,无法匹配10个数据点,因此报错。

内容的提问来源于stack exchange,提问作者Liuka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 04:32:19