12

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」のカテゴリで色付けされています。(ランダムデータは上記のものとは異なることに注意してください)

誰かアイデアがあれば、パンダ/シーボーンのソリューションが欲しいですか?

ここに画像の説明を入力

4

2 に答える 2

10

を使用する場合FacetGrid.mapdataDataFrame を参照するものはすべて位置引数として渡す必要があります。yerrの 3 番目の位置引数であるため、これはあなたのケースで機能します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次に、 andを使用してプロットできます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")

ここに画像の説明を入力

またはlmplot:

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

ここに画像の説明を入力

于 2014-07-22T14:47:13.470 に答える
1

実際に何であるかを示していません。また、それがand とdf['E'] 同じ長さのリストである場合。df['C']df['D']

キーワード引数 (kwarg) は、データフレームのyerrキー C および D のリスト内のすべての要素に適用される単一の値を取るか、それらのリストと同じ長さの値のリストを必要とします。

したがって、C、D、および E はすべて同じ長さのリストに関連付けられている必要があります。または、C と D が同じ長さのリストであり、E が単一のfloatorに関連付けられている必要がありますint。その単一のfloatorintがリスト内にある場合は、 のように抽出する必要がありますdf['E'][0]

matplotlibコード例yerr: http://matplotlib.org/1.2.1/examples/pylab_examples/errorbar_demo.html

説明するバー プロット API ドキュメントyerr: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar

于 2014-07-22T03:13:42.423 に答える