向 Seaborn 因子图添加简单的误差条 [英] Adding simple error bars to Seaborn factorplot
问题描述
我有一个从汇总表生成的 factorplot
,而不是原始数据:
I have a factorplot
that I have generated from a summary table, rather than raw data:
使用以下代码:
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)})
此处绘制的是汇总表中的平均值,但我还想绘制可信区间,其上限和下限在另外两列中指定.该表如下所示:
Plotted here are the mean values from the summary table, but I would also like to plot the credible interval, whose upper and lower bounds are specified in two other columns. The table looks like this:
有没有办法,也许使用 factorplot
返回的 FacetGrid
将误差线附加到点上?
Is there a way, perhaps using the FacetGrid
returned by factorplot
of tacking on the error bars to the points?
推荐答案
您可以将 plt.errorbar
传递给 FacetGrid.map
但它需要一个小的包装函数来重新格式化参数正确(并明确传递类别顺序):
You can pass plt.errorbar
to FacetGrid.map
but it requires a small wrapper function to reformat the arguments properly (and explicitly passing the category order):
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)
这篇关于向 Seaborn 因子图添加简单的误差条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!