Seaborn 因子图自定义误差线
Seaborn factor plot custom error bars
我想在 seaborn 中绘制因子图,但手动提供误差线而不是让 seaborn 计算它们。
我有一个 pandas 数据框,大致如下所示:
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' 列作为错误栏。不幸的是,重新计算相关数据框的输出将非常耗时。
这和这个问题有点相似:
Plotting errors bars from dataframe using Seaborn FacetGrid
除了我不知道如何让它与 matplotlib.pyplot.bar 函数一起工作。
有没有办法将 seaborn factorplot
或 FacetGrid
与 matplotlib 结合使用?
谢谢!
测试于 python 3.8.12
、pandas 1.3.4
、matplotlib 3.4.3
、seaborn 0.11.2
你可以这样做
import seaborn as sns
import matplotlib.pyplot as plt
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")
这是另一种方法:
import matplotlib.pyplot as plt
import numpy as np
plt.plot(np.asarray([[0, 0], [1, 1]]).T, np.asarray([[0.3, 0.4], [0.01 , 0.02]]).T)
plt.show()
x 值对应条形图的分类值(0 是第一个类别,依此类推)。 y 值显示误差条的上限和下限。必须对两个数组进行转置,matplotlib 才能正确显示它们。我只是觉得这样更易读。
我想在 seaborn 中绘制因子图,但手动提供误差线而不是让 seaborn 计算它们。
我有一个 pandas 数据框,大致如下所示:
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' 列作为错误栏。不幸的是,重新计算相关数据框的输出将非常耗时。
这和这个问题有点相似: Plotting errors bars from dataframe using Seaborn FacetGrid
除了我不知道如何让它与 matplotlib.pyplot.bar 函数一起工作。
有没有办法将 seaborn factorplot
或 FacetGrid
与 matplotlib 结合使用?
谢谢!
测试于 python 3.8.12
、pandas 1.3.4
、matplotlib 3.4.3
、seaborn 0.11.2
你可以这样做
import seaborn as sns
import matplotlib.pyplot as plt
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")
这是另一种方法:
import matplotlib.pyplot as plt
import numpy as np
plt.plot(np.asarray([[0, 0], [1, 1]]).T, np.asarray([[0.3, 0.4], [0.01 , 0.02]]).T)
plt.show()
x 值对应条形图的分类值(0 是第一个类别,依此类推)。 y 值显示误差条的上限和下限。必须对两个数组进行转置,matplotlib 才能正确显示它们。我只是觉得这样更易读。