向Seaborn factorplot添加简单的错误栏

时间:2016-07-14 22:16:21

标签: python plot seaborn

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

http://dsh.re/db165

使用以下代码:

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

此处绘制的是汇总表中的平均值,但我还想绘制可信区间,其上限和下限在另外两列中指定。该表如下所示:

http://dsh.re/0bf74

有没有办法,可能使用FacetGrid返回的factorplot在错误栏上添加点数?

1 个答案:

答案 0 :(得分:1)

您可以将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)

enter image description here