代码之家  ›  专栏  ›  技术社区  ›  Nathan123

如何使用matplotlib创建堆叠条形图?

  •  0
  • Nathan123  · 技术社区  · 4 年前

    我有一个pandas数据框架,其中包含一些示例数据,如下所示

       year_start       party  num_legistators
    0         2010    democrat               50
    1         2010  republican              133
    2         2010     unknown                4
    3         2011    democrat               67
    4         2011  republican              56
    5         2012    democrat               76
    6         2012  republican              43
    

    我正在尝试创建一个以x轴为中心的堆叠条形图 year_start y轴是 num_legislators 堆叠条的颜色为 party

    到目前为止,我已经这样做了

    df_toviz.plot(x= "year_start", kind='bar', stacked=True)

    enter image description here

    我怎样才能被堆叠起来?

    1 回复  |  直到 4 年前
        1
  •  1
  •   akuiper    4 年前

    您需要首先旋转数据帧,以便 party

    Full example

    df.pivot('year_start', 'party', 'num_legistators').plot.bar(stacked=True)
    plt.show()
    

    enter image description here