【问题标题】:Stacked Bar Plot with Two Key DataFrame带有两个关键数据框的堆积条形图
【发布时间】:2016-01-27 00:01:22
【问题描述】:

我有一个带有两个键的数据框。我正在寻找 key2 中项目数量的堆积条形图(意味着从完全填充的数据列中获取计数值)。

我拥有的数据框的一小部分是:

Sector            industry                   
Basic Industries  Agricultural Chemicals         17
                  Aluminum                        3
                  Containers/Packaging            1
                  Electric Utilities: Central     2
                  Engineering & Construction     12
Name: Symbol, dtype: int64

Key1 是部门,Key2 是行业。我希望 Symbol 中的值(计数的列表示为行业堆叠)在包含 Basic Industries 的栏中。

我知道如果我做一个df.reset_index,我会有一个包含(非唯一)部门和行业的列和一个整数计数器。有没有办法简单地将第 1,2,3 列数据分配给 pandas plot 或 matplotlib 以制作堆叠条形图?

或者,有没有一种方法可以轻松地指定使用上述数据框中的两个键?

我正在寻找更有经验的人提供的方法指导以及实际语法方面的帮助。

【问题讨论】:

    标签: python pandas matplotlib plot


    【解决方案1】:

    我刚刚添加了一个新的部门来改进示例。

                                               Symbol
    Sector            industry                           
    Basic Industries  Agricultural Chemicals           17
                      Aluminum                          3
                      Containers/Packaging              1
                      Electric Utilities: Central       2
                      Engineering & Construction       22
    Basic Industries2 Agricultural Chemicals            7
                      Aluminum                          8
                      Containers/Packaging             11
                      Electric Utilities: Central       7
                      Engineering & Construction        4
    

    假设您的数据框由 ["Sector", "industry"] 索引,您首先需要 reset_index,然后旋转您的数据框,最后制作堆叠图。

    df.reset_index().pivot_table(index="industry", columns="Sector", values="Symbol").T.plot(kind='bar', stacked=True, figsize=(14, 6))
    

    【讨论】:

    • 谢谢!我看到你使用了数据透视表。我得去复习了。我已经接触过 Pandas 中的数据透视表,但看起来我应该更多地回顾一下,因为它们在许多情况下可能很有用。再次感谢!
    【解决方案2】:

    另一种方式,而不是reset_index,你可以使用这个:

    df.unstack().Symbol.plot(kind='bar', stacked=True)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      • 2018-09-22
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      相关资源
      最近更新 更多