问题
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