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

qoefvg9y  于 2023-06-20  发布在  Python
关注(0)|答案(2)|浏览(102)

当有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")

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

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

a1o7rhls

a1o7rhls1#

您可以在sns.barplot中使用自定义错误条函数。它应该返回一个[y1,y2] iterable,其中包含最小/最大误差的位置:

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

另一个选项可以是手动绘制误差线:

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)

输出:

sg24os4d

sg24os4d2#

找到this answer后,我想到了一个可能的解决方案,循环遍历ax.lines,并将那些不想显示线宽的宽度设置为0。这要求show_errorsdf.Label.unique()的顺序相同。

注意:这假设图中没有其他线,所以简单的条形图就可以了,但是如果图中有任何额外的线,那么这将返回错误,因为ax.lines的长度将不等于show_errors

df = pd.DataFrame(np.random.randint(0,100,size=(15)), columns=["Value"])
df["Label"]="Condition A"
df.Label[13:]="Condition B"
show_errors = [True, False]
ax = sns.barplot(data=df, x="Label", y="Value", errorbar="sd")
for p, err in zip(ax.lines, show_errors):
    if not err:
        p.set_linewidth(0)
plt.show()

正如@mozway在他的回答中所示,它可以通过一个条件创建show_errorsshow_errors = df.groupby("Label", sort=False).Value.count().ge(3).tolist()

相关问题