海域因子图自定义误差棒

2024-04-25 19:22:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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.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 bar plots

我用这个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”列作为错误栏。不幸的是,重新计算有关数据帧的输出将非常耗时。

这有点像这个问题: Plotting errors bars from dataframe using Seaborn FacetGrid

但我不知道如何让它与matplotlib.pyplot.bar函数一起工作。

有没有办法使用seabornfactorplot或结合matplotlib的FacetGrid来实现这一点?

谢谢!


Tags: 数据outputmodel错误barseabornmeanone
1条回答
网友
1楼 · 发布于 2024-04-25 19:22:40

你可以这样做

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

enter image description here

相关问题 更多 >