Python堆积直方图

时间:2015-09-03 07:31:04

标签: python pandas plot histogram stacked

假设我有这个pandas数据帧,

    pC  Truth
0   0.601972    0
1   0.583300    0
2   0.595181    1
3   0.418910    1
4   0.691974    1

'pC'是'Truth'为1的概率。'Truth'是二进制值。 我想创建概率的直方图,每个bin的内部将是0比例1的比例。

我尝试了以下内容,

df[['pC','Truth']].plot(kind='hist',stacked=True)

它只是将'真实'值置于0和1之间。

可重复性:

shape = 1000
df_t = pd.DataFrame({'pC': np.random.rand(shape),
                     'Truth':np.random.choice([0,1],size=shape)})
df_t['factor'] = pd.cut(df_t.pC,5)

我该怎么做?感谢

2 个答案:

答案 0 :(得分:0)

根据我对你的意思的解释:

  • 创建传统的直方图计数,其概率为binned(水平,如常),对于某些binsize。仅适用于Truth==0
  • 的数据框架
  • 现在使(1-pC)
  • 的广告素材的补充概率值Truth==1增加该数据框
  • 现在将增强的df绘制为堆积条形图(可能为补充的Truth==1条形段设置白色填充颜色)

如果您发布可重现的代码(使用dput)并确认这是您想要的,我将发布代码。否则,请发布指向某个图像的链接,以显示您想要的内容。

答案 1 :(得分:0)

解决了这个问题,

shape = 1000
df_t = pd.DataFrame({'pC': np.random.rand(shape),
                     'Truth':np.random.choice([0,1],size=shape)})
df_t['factor'] = pd.cut(df_t.pC,5)
df_p = (df_t[['factor','Truth']]
        .pivot_table(columns='Truth',index='factor',aggfunc=len,fill_value=0)
        .reset_index())
df_p[['factor',0,1]].plot(kind='bar',stacked=True,x='factor');
相关问题