【问题标题】:Stacked bar plots from two different sources in PandasPandas 中两个不同来源的堆积条形图
【发布时间】:2012-12-20 23:41:03
【问题描述】:

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

这是代码:

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

谢谢

【问题讨论】:

    标签: python matplotlib pandas


    【解决方案1】:

    先新建一列区分'first_babies'

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

    你可以unstackgroupby:

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

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

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

    【讨论】:

    • 有趣,但我收到以下错误:ReshapeError:索引包含重复条目,无法重塑。没错,您输入的 week 实际上是 'prglength' 并且肯定具有重复值。
    • @RobertSmith 应该这样做!
    • 顺便说一句,我认为 lambda 行不通。我用地图代替。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 2016-05-24
    • 2018-05-09
    相关资源
    最近更新 更多