向 Seaborn 因子图添加简单的误差线

Adding simple error bars to Seaborn factorplot

我有一个 factorplot 是我从摘要 table 而不是原始数据生成的:

使用以下代码:

sns.factorplot(col="followup", y="probability", hue="next intervention", x="age", 
               data=table_flat[table_flat['next intervention']!='none'], 
               facet_kws={'ylim':(0,0.6)})

此处绘制的是摘要 table 的平均值,但我还想绘制可信区间,其上限和下限在另外两列中指定。 table 看起来像这样:

有没有办法,也许使用 factorplot 返回的 FacetGrid 将误差线添加到点?

您可以将 plt.errorbar 传递给 FacetGrid.map,但它需要一个小的包装函数来正确地重新格式化参数(并显式传递类别顺序):

import numpy as np
from scipy import stats
import seaborn as sns
import matplotlib.pyplot as plt

# Reformat the tips dataset to your style
tips = sns.load_dataset("tips")
tips_agg = (tips.groupby(["day", "smoker"])
                .total_bill.agg([np.mean, stats.sem])
                .reset_index())
tips_agg["low"] = tips_agg["mean"] - tips_agg["sem"]
tips_agg["high"] = tips_agg["mean"] + tips_agg["sem"]

# Define a wrapper function for plt.errorbar
def errorbar(x, y, low, high, order, color, **kws):
    xnum = [order.index(x_i) for x_i in x]
    plt.errorbar(xnum, y, (y - low, high - y), color=color)

# Draw the plot
g = sns.factorplot(x="day", y="mean", col="smoker", data=tips_agg)
order = sns.utils.categorical_order(tips_agg["day"])
g.map(errorbar, "day", "mean", "low", "high", order=order)