Adding simple error bars to Seaborn factorplot

怎甘沉沦 提交于 2021-01-29 03:07:20

问题


I have a factorplot that I have generated from a summary table, rather than raw data:

Using the following code:

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:

Is there a way, perhaps using the FacetGrid returned by factorplot of tacking on the error bars to the points?


回答1:


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)



来源:https://stackoverflow.com/questions/38385099/adding-simple-error-bars-to-seaborn-factorplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!