【问题标题】:how to create a stacked bar chart with matplotlib?如何使用 matplotlib 创建堆积条形图?
【发布时间】:2021-11-17 22:08:01
【问题描述】:

我有一个带有一些示例数据的 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)

我如何被堆叠?

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您需要先旋转您的数据框,以便 party 成为列:

    Full example

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-02
      • 2018-01-17
      • 2019-11-28
      • 2021-09-28
      • 1970-01-01
      • 2014-06-02
      相关资源
      最近更新 更多