2

我想这很容易,但我尝试了一段时间来获得答案,但没有取得多大成功。我想为两个类别生成堆积条形图,但我在两个单独的日期框架中有这样的信息:

这是代码:

first_babies = live[live.birthord == 1] # first dataframe
others = live[live.birthord != 1] # second dataframe

fig = figure()
ax1 = fig.add_subplot(1,1,1)

first_babies.groupby(by=['prglength']).size().plot(
                     kind='bar', ax=ax1, label='first babies') # first plot
others.groupby(by=['prglength']).size().plot(kind='bar', ax=ax1, color='r',
               label='others') #second plot
ax1.legend(loc='best')
ax1.set_xlabel('weeks')
ax1.set_ylabel('frequency')
ax1.set_title('Histogram')

在此处输入图像描述

但我想要这样的东西,或者像我说的那样,堆积条形图,以便更好地区分类别:

在此处输入图像描述

我不能使用stacked=True,因为它不能使用两个不同的图,我不能创建一个新的数据框,因为first_babies并且others没有相同数量的元素。

谢谢

4

1 回答 1

1

首先创建一个新列来区分'first_babies'

live['first_babies'] = live['birthord'].lambda(x: 'first_babies' if x==1 else 'others')

你可以unstack分组:

grouped = live.groupby(by=['prglength', 'first_babies']).size()
unstacked_count = grouped.size().unstack()

现在您可以直接绘制堆积条形图

unstacked_count.plot(kind='bar', stacked=True)
于 2012-12-21T04:40:14.353 回答