使用Seaborn FacetGrid从dataframe绘制错误条

2024-06-28 11:06:28 发布

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

我想从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');

enter image description here

但是我不能用数据框中的值来实现它

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解决方案

#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”列中的类别着色。(注意随机数据与上述不同)

如果有人有什么想法的话,我还是想要一个熊猫/海生的解决方案?

enter image description here


Tags: 数据importdffoobarpltcolone
2条回答

使用FacetGrid.map时,任何引用data数据帧的内容都必须作为位置参数传递。这在您的情况下是可行的,因为yerrplt.errorbar的第三个位置参数,不过为了演示我将使用tips数据集:

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绘制:

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

enter image description here

但是,请记住,有seaborn绘图函数用于从完整数据集到带有错误条的绘图(使用引导),因此对于许多应用程序,这可能不是必需的。例如,可以使用factorplot

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

enter image description here

lmplot

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

enter image description here

你没有显示df['E']实际上是什么,如果它是与df['C']df['D']长度相同的列表。

关键字参数(kwarg)接受一个值,该值将应用于数据帧中键C和D的列表中的每个元素,或者需要一个与这些列表长度相同的值列表。

所以,C、D和E都必须与相同长度的列表相关联,或者C和D必须是相同长度的列表,并且E必须与单个floatint相关联。如果单个floatint在列表中,则必须提取它,如df['E'][0]

示例matplotlib代码与yerrhttp://matplotlib.org/1.2.1/examples/pylab_examples/errorbar_demo.html

描述yerr的条形图API文档: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar

相关问题 更多 >