在 seaborn 条形图上将百分位值绘制为误差线

Plotting percentile values as errorbars on seaborn barplot

我想在 seaborn 上绘制条形图并包含自定义误差条。我的 MWE 是

import pandas as pd
import seaborn as sns

w = pd.DataFrame(data={'length': [40,35,34,40,38,39,38,44,40,39,35,46],
                       'species': ['A','A','A','A','B','B','B','B','C','C','C','C'],
                       'type': ['today','avg','10pc','90pc','today','avg','10pc','90pc','today','avg','10pc','90pc']
                      },
                )
w['Date'] = pd.to_datetime('2021-09-20')
w.set_index('Date',inplace=True)

w0 = w.loc[(w.type=='today') | (w.type=='avg')] # average length and today's length
w1 = w.loc[(w.type=='10pc') | (w.type=='90pc')] # 10th and 90th percentile

fig, ax = plt.subplots(figsize=(8,5))
y = sns.barplot(x=w0['species'], y=w0['length'], hue=w0['type'], yerr=w1['10pc','90pc'], capsize=.2) 
y.set_title(w0.index[0].strftime('%d %b %Y'), fontsize=16)
y.set_xlabel('species', fontsize=14)
y.set_ylabel('length (cm)', fontsize=14)
y.grid(axis='y', lw=0.5)

plt.show()

其中 today 是今天的长度测量值,avg 是平均测量值,10pc90pc 是第 10 个和第 90 个百分位值。我尝试在 barplot 命令中设置 yerr,但这不起作用。我不确定如何配置 seaborn 以接受百分位值。

我想为每个 speciesavg 条绘制 10pc90pc。这就是我的目标(我自己画的黑条):

这是我的看法,使用 pandas' 绘图功能,基于 :

errors = w1.pivot_table(columns=[w1.index,'species'],index='type',values=['length']).values
avgs = w0.length[w0.type=='avg'].values
bars = np.stack((np.absolute(errors-avgs), np.zeros([2,w1.species.unique().size])), axis=0)

fig, ax = plt.subplots(figsize=(8,5))
w0.pivot(index='species', columns='type', values='length').plot(kind='bar', yerr=bars, ax=ax)
ax.set_title(w0.index[0].strftime('%d %b %Y'), fontsize=16)
ax.set_xlabel('species', fontsize=14)
ax.set_ylabel('length (cm)', fontsize=14)
ax.grid(axis='y', lw=0.5)

结果图如下所示: