首页 > 解决方案 > 如何为 Seaborn 条形图指定不确定性条?

问题描述

可以通过以下方式创建 Seaborn 条形图:

import pandas as pd
import seaborn as sns

df = pd.DataFrame(
         [
             ['variable_a', 0.656536, 0.054560],
             ['variable_b', 0.425124, 0.056104],
             ['variable_c', 0.391201, 0.049393],
             ['variable_d', 0.331990, 0.032777],
             ['variable_e', 0.309588, 0.027449],
         ],
         columns = [
             'index',
             'mean',
             'statistical_uncertainty'
         ]
    )
df.index = df['index']
del df['index']
df

p = sns.barplot(df["mean"], df.index);
plt.show;

如何将不确定性条添加到条形图中?这似乎是一种很有前途的方法,但我不确定如何继续:https ://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.errorbar.html

标签: matplotlibbar-chartseaborn

解决方案


plt.errorbar您可以在绘图顶部使用以下方法绘制误差线:

p = sns.barplot(df["mean"], df.index)

# to enhance visibility of error bars, 
# you can draw them twice with different widths and colors:
p.errorbar(y=range(len(df)), 
           x=df['mean'], 
           xerr=df.statistical_uncertainty, 
           fmt='none',
           linewidth=3, c='w')

p.errorbar(y=range(len(df)), 
           x=df['mean'], 
           xerr=df.statistical_uncertainty, 
           fmt='none',
           c='r')
plt.show;

在此处输入图像描述


推荐阅读