如果类别中的数据点少于 3 个,如何隐藏错误栏

fix*_*mal 3 python matplotlib bar-chart seaborn errorbar

当有超过 3 个数据点可用时(条件 A),我希望在条形图中显示误差线,但当该特定条件的数据点少于 3 个时(条件 B),则忽略误差线。

我只找到了显示或隐藏所有条的错误条的选项,而不是针对特定条件的选项。

import pandas as pd
import seaborn as sns
import numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(15)), columns=["Value"])
df["Label"]="Condition A"
df.Label[13:]="Condition B"
sns.barplot(data=df, x="Label", y="Value", errorbar="sd")
Run Code Online (Sandbox Code Playgroud)

实际结果:所有条上的误差条:

实际结果,所有条形图上的误差条

期望的结果:仅条件 A 的误差线:

期望的结果,条件 B 中没有误差线

moz*_*way 5

您可以在sns.barplot. 它应该返回一个 [y1, y2] 可迭代对象,其中包含最小/最大误差的位置:

# defining a custom function to only compute
# the error if more than 3 values
def cust_error(s):
    if len(s)<3:
        return [None, None]
    else:
        avg = s.mean()
        std = s.std()
        return [avg-std, avg+std]

sns.barplot(data=df, x="Label", y="Value", errorbar=cust_error)
Run Code Online (Sandbox Code Playgroud)

另一种选择是手动绘制误差线:

ax = sns.barplot(data=df, x="Label", y="Value", errorbar=None)

g = df.groupby('Label', sort=False)
error = g['Value'].std().where(g.size()>=3)

plt.errorbar(range(len(s)), g['Value'].mean(), error,
             ls='', color='#5F5F5F', lw=3)
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述