使用Seaborn FacetGrid从数据框中绘制误差线 [英] Plotting errors bars from dataframe using Seaborn FacetGrid

查看:164
本文介绍了使用Seaborn FacetGrid从数据框中绘制误差线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Seaborn FacetGrid上的熊猫数据框中的列绘制误差线

I want to plot error bars from a column in a pandas dataframe on a Seaborn FacetGrid

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar']*2,
                   'B' : ['one', 'one', 'two', 'three',
                         'two', 'two', 'one', 'three'],
                  'C' : np.random.randn(8),
                  'D' : np.random.randn(8)})
df

示例数据框

    A       B        C           D
0   foo     one      0.445827   -0.311863
1   bar     one      0.862154   -0.229065
2   foo     two      0.290981   -0.835301
3   bar     three    0.995732    0.356807
4   foo     two      0.029311    0.631812
5   bar     two      0.023164   -0.468248
6   foo     one     -1.568248    2.508461
7   bar     three   -0.407807    0.319404

此代码适用于固定大小的误差线:

This code works for fixed size error bars:

g = sns.FacetGrid(df, col="A", hue="B", size =5)
g.map(plt.errorbar, "C", "D",yerr=0.5, fmt='o');

但是我无法使用数据框中的值来使它工作

But I can't get it to work using values from the dataframe

df['E'] = abs(df['D']*0.5)
g = sns.FacetGrid(df, col="A", hue="B", size =5)
g.map(plt.errorbar, "C", "D", yerr=df['E']);

g = sns.FacetGrid(df, col="A", hue="B", size =5)
g.map(plt.errorbar, "C", "D", yerr='E');

两者都会产生错误提示

经过大量matplotlib文档阅读和各种stackoverflow答案后, 这是一个纯matplotlib解决方案

After lots of matplotlib doc reading, and assorted stackoverflow answers, here is a pure matplotlib solution

#define a color palette index based on column 'B'
df['cind'] = pd.Categorical(df['B']).labels

#how many categories in column 'A'
cats = df['A'].unique()
cats.sort()

#get the seaborn colour palette and convert to array
cp = sns.color_palette()
cpa = np.array(cp)

#draw a subplot for each category in column "A"
fig, axs = plt.subplots(nrows=1, ncols=len(cats), sharey=True)
for i,ax in enumerate(axs):
    df_sub = df[df['A'] == cats[i]]
    col = cpa[df_sub['cind']]
    ax.scatter(df_sub['C'], df_sub['D'], c=col)
    eb = ax.errorbar(df_sub['C'], df_sub['D'], yerr=df_sub['E'], fmt=None)
    a, (b, c), (d,) = eb.lines
    d.set_color(col)

除标签外,轴限制其确定.它为"A"列中的每个类别绘制了一个单独的子图,并由"B"列中的类别进行了着色. (请注意,随机数据与上面的数据不同)

Other than the labels, and axis limits its OK. Its plotted a separate subplot for each category in column 'A', colored by the category in column 'B'. (Note the random data is different to that above)

如果有人有任何想法,我还是希望获得熊猫/季节性解决方案?

I'd still like a pandas/seaborn solution if anyone has any ideas?

推荐答案

使用FacetGrid.map时,任何引用data DataFrame的内容都必须作为位置参数传递.这将对您有用,因为yerrplt.errorbar的第三个位置参数,尽管为了说明我将使用技巧数据集:

When using FacetGrid.map, anything that refers to the data DataFrame must be passed as a positional argument. This will work in your case because yerr is the third positional argument for plt.errorbar, though to demonstrate I'm going to use the tips dataset:

from scipy import stats
tips_all = sns.load_dataset("tips")
tips_grouped = tips_all.groupby(["smoker", "size"])
tips = tips_grouped.mean()
tips["CI"] = tips_grouped.total_bill.apply(stats.sem) * 1.96
tips.reset_index(inplace=True)

然后我可以使用FacetGriderrorbar进行绘图:

I can then plot using FacetGrid and errorbar:

g = sns.FacetGrid(tips, col="smoker", size=5)
g.map(plt.errorbar, "size", "total_bill", "CI", marker="o")

但是,请记住,存在从原始数据集到带有误差条的图(使用自举)的最原始的绘图功能,因此对于许多应用程序来说,这可能不是必需的.例如,您可以使用factorplot:

However, keep in mind that the there are seaborn plotting functions for going from a full dataset to plots with errorbars (using bootstrapping), so for a lot of applications this may not be necessary. For example, you could use factorplot:

sns.factorplot("size", "total_bill", col="smoker",
               data=tips_all, kind="point")

lmplot:

sns.lmplot("size", "total_bill", col="smoker",
           data=tips_all, fit_reg=False, x_estimator=np.mean)

这篇关于使用Seaborn FacetGrid从数据框中绘制误差线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆