在一个图上绘制几个密度

时间:2014-11-11 17:07:12

标签: python matplotlib pandas

我有一个带MultiIndex(支出,groupid)的数据框:

                        coef    stderr    N
expenditure groupid                         
TOTEXPCQ    176      3745.124  858.1998   81
            358     -1926.703  1036.636   75
            109      239.3678   639.373  280
            769      6406.512  1823.979   96
            775      2364.655  1392.187  220

我可以使用df['coef'].plot(kind='density')获取密度。我想将这些密度分组到MultiIndex(支出)的外层,并将不同支出水平的不同密度划分到同一个图中。

我将如何实现这一目标?奖金:使用“支出”值标记不同的支出图表

回答

我最初的方法是通过生成一个ax对象并将其传递来合并不同的kdes,但是接受的答案激发了我生成一个df,其中组标识符为列:

n = 25
df = pd.DataFrame({'expenditure' : np.random.choice(['foo','bar'], n),
                   'groupid' : np.random.choice(['one','two'], n),
                  'coef' : np.random.randn(n)})
df2 = df[['expenditure', 'coef']].pivot_table(index=df.index, columns='expenditure', values='coef')
df2.plot(kind='kde')

enter image description here

1 个答案:

答案 0 :(得分:2)

哇,结果比我想象的要困难得多。看似简单的概念,但(又一次)概念和实践确实不同。

设置一些玩具数据:

n = 25
df = pd.DataFrame({'expenditure' : np.random.choice(['foo','bar'], n),
                   'groupid' : np.random.choice(['one','two'], n),
                  'coef' : randn(n)})

然后按expenditure分组,遍历每个支出,转动数据,并绘制kde:

gExp = df.groupby('expenditure')
for exp in gExp:
    print exp[0]
    gGroupid = exp[1].groupby('groupid')
    g = exp[1][['groupid','coef']].reset_index(drop=True)
    gpt = g.pivot_table(index = g.index, columns='groupid', values='coef')
    gpt.plot(kind='kde').set_title(exp[0])
    show()

结果:

enter image description here enter image description here

在绘图之前需要进行一些反复试验才能确定数据是否必须转动。

相关问题