ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

使用Seaborn FacetGrid从数据框中绘制错误条

2019-09-26 00:55:28  阅读:175  来源: 互联网

标签:python pandas matplotlib plot seaborn


我想在Seaborn FacetGrid上的pandas数据框中的列中绘制误差条

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

此代码适用于固定大小的错误栏:

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

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

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 doc阅读,以及各种stackoverflow的答案,
这是一个纯matplotlib解决方案

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

除了标签,轴限制其OK.它为“A”列中的每个类别绘制了一个单独的子图,由“B”列中的类别着色. (注意随机数据与上面的不同)

如果有人有任何想法,我仍然喜欢大熊猫/海豹的解决方案吗?

解决方法:

使用FacetGrid.map时,任何引用数据DataFrame的内容都必须作为位置参数传递.这将适用于您的情况,因为yerr是plt.errorbar的第三个位置参数,但为了证明我将使用提示数据集:

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)

然后我可以使用FacetGrid和errorbar进行绘图:

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

但是,请记住,有一个seaborn绘图功能,用于从完整数据集转到带有错误栏的图(使用自举),因此对于许多应用程序而言,这可能不是必需的.例如,您可以使用factorplot:

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

或者说:

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

标签:python,pandas,matplotlib,plot,seaborn
来源: https://codeday.me/bug/20190926/1817981.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有