Skip to main content
 首页 » 编程设计

python之来自 Pandas 中两个不同来源的堆叠条形图

2025年05月04日7cloudgamer

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

这是代码:

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 和 其他没有相同数量的元素。

谢谢

请您参考如下方法:

首先新建一个列来区分'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() 

现在您可以绘制 stacked bar-plot直接:

unstacked_count.plot(kind='bar', stacked=True)