Python Seaborn因子绘图自定义错误条
我想在seaborn中绘制一个factorplot,但是手动提供错误条,而不是让seaborn计算它们 我有一个大致如下的熊猫数据框:Python Seaborn因子绘图自定义错误条,python,pandas,matplotlib,plot,seaborn,Python,Pandas,Matplotlib,Plot,Seaborn,我想在seaborn中绘制一个factorplot,但是手动提供错误条,而不是让seaborn计算它们 我有一个大致如下的熊猫数据框: model output feature mean std 0 first two a 9.00 2.00 1 first one b 0.00 0.00 2 first one c 0.00 0.00 3 first two d 0.6
model output feature mean std
0 first two a 9.00 2.00
1 first one b 0.00 0.00
2 first one c 0.00 0.00
3 first two d 0.60 0.05
...
77 third four a 0.30 0.02
78 third four b 0.30 0.02
79 third four c 0.10 0.01
我将输出一个大致如下的图:
我正在使用seaborn命令生成绘图:
g = sns.factorplot(data=pltdf, x='feature', y='mean', kind='bar',
col='output', col_wrap=2, sharey=False, hue='model')
g.set_xticklabels(rotation=90)
然而,我不知道如何让seaborn使用“std”列作为错误条。不幸的是,重新计算相关数据帧的输出将非常耗时
这有点类似于这个问题:
只是我不知道如何让它与matplotlib.pyplot.bar函数一起工作
有没有办法使用seabornfactorplot
或FaceGrid
与matplotlib相结合来实现这一点
谢谢 你可以这样做
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import sem
tips = sns.load_dataset("tips")
tip_sumstats = (tips.groupby(["day", "sex", "smoker"])
.total_bill
.agg(["mean", sem])
.reset_index())
def errplot(x, y, yerr, **kwargs):
ax = plt.gca()
data = kwargs.pop("data")
data.plot(x=x, y=y, yerr=yerr, kind="bar", ax=ax, **kwargs)
g = sns.FacetGrid(tip_sumstats, col="sex", row="smoker")
g.map_dataframe(errplot, "day", "mean", "sem")
这里是另一种方法:
导入matplotlib.pyplot作为plt
将numpy作为np导入
plt.绘图(np.asarray([[0,0],[1,1]]).T,np.asarray([[0.3,0.4],[0.01,0.02]]).T)
plt.show()
x值对应于条形图的分类值(0是第一个分类,依此类推)。y值显示误差条的上限和下限。两个数组都必须转置才能正确显示matplotlib。我只是觉得这样更可读
我认为链接问题将是最好的方式
plt.bar
有一个yerr
参数,应该会有帮助。谢谢@mwaskom,关于如何使用它有什么提示吗?目前,以下代码阻塞:g=sns.FacetGrid(data=pltdf,col='output',col_wrap=6,sharey=False,hue='model')g.map(plt.bar,'feature','mean',yerr='std')
为混乱的代码道歉,似乎无法在注释部分很好地格式化。我认为问题在于bar中的yerr参数不是位置参数,这是一个kwarg。有关可映射函数,请参见。您需要在plt.bar
周围编写一个薄薄的包装,接受yerr
作为位置参数.Stellar,非常感谢@mwaskom的帮助,以及您编写的可爱的包。它真的非常有用。它不起作用:TypeError:numpy.float64类型的对象没有len()