【问题标题】:Plot group bar charts with matplotlib or Seaborn with Datetime Index in Python使用 matplotlib 或 Seaborn 在 Python 中使用日期时间索引绘制组条形图
【发布时间】:2020-07-08 02:20:02
【问题描述】:

我有一个 Pandas DataFrame,它由一个日期列和一个感兴趣的类别列组成。我想查看每个月的频率计数。当我用 matplotlib 做这个时,我得到了一些看起来很糟糕的东西。

这是按月份分组时框架的外观:

df.resample("M")["category_col"].value_counts(normalize=True).mul(100)

Output

date                         category_col      
2019-12-31  A                41.929004
            B                25.758765
            C                17.752111
            D                9.189919
            E                3.625122
            F                1.745080
2020-01-31  A                54.052744
            C                16.347271
            B                14.414431
            D                11.677537
            E                2.675607
            F                0.832411
2020-02-29  A                48.928468
            D                22.011116
            C                14.084507
            C                11.729162
            E                2.193272
            F                1.053475
2020-03-31  A                54.435410
            D                15.718065
            C                14.577060
            B                11.335682
            E                2.884205
            F                1.049578
Name: category_col, dtype: float64

这是我的尝试

df.date = pd.to_datetime(df.date)
df.set_index("date", inplace=True)
df.resample("M")["category_col"].value_counts(normalize=True).mul(100).plot(kind="bar")

查看下面的输出:

这就是我想要的:

【问题讨论】:

    标签: python pandas dataframe matplotlib seaborn


    【解决方案1】:

    我认为你需要Series.unstackrename 来表示日期时间month name year

    df.date = pd.to_datetime(df.date)
    df = df.set_index("date")
    
    s = df.resample("M")["category_col"].value_counts(normalize=True).mul(100)
    
    s.unstack().rename(lambda x: x.strftime('%B %Y')).plot(kind="bar")
    

    示例:

    print (s)
    date        category_col
    2019-12-31  A               41.929004
                B               25.758765
                C               17.752111
                D                9.189919
                E                3.625122
                F                1.745080
    2020-01-31  A               54.052744
                C               16.347271
                B               14.414431
                D               11.677537
                E                2.675607
                F                0.832411
    2020-02-29  A               48.928468
                B               22.011116
                C               14.084507
                D               11.729162
                E                2.193272
                F                1.053475
    2020-03-31  A               54.435410
                D               15.718065
                C               14.577060
                B               11.335682
                E                2.884205
                F                1.049578
    Name: A, dtype: float64
    

    print (s.unstack())
    category_col          A          B          C          D         E         F
    date                                                                        
    2019-12-31    41.929004  25.758765  17.752111   9.189919  3.625122  1.745080
    2020-01-31    54.052744  14.414431  16.347271  11.677537  2.675607  0.832411
    2020-02-29    48.928468  22.011116  14.084507  11.729162  2.193272  1.053475
    2020-03-31    54.435410  11.335682  14.577060  15.718065  2.884205  1.049578
    

    print (s.unstack().rename(lambda x: x.strftime('%B %Y')))
    category_col           A          B          C          D         E         F
    date                                                                         
    December 2019  41.929004  25.758765  17.752111   9.189919  3.625122  1.745080
    January 2020   54.052744  14.414431  16.347271  11.677537  2.675607  0.832411
    February 2020  48.928468  22.011116  14.084507  11.729162  2.193272  1.053475
    March 2020     54.435410  11.335682  14.577060  15.718065  2.884205  1.049578
    

    【讨论】:

    • 这很好用。但条形图未排序,日期显示为 2020-01-31、2020-02,31。如何将它们更改为 1 月、2 月等?
    • 在我执行import datetime from datetime 并应用上述内容后,我收到以下错误:AttributeError: 'str' object has no attribute 'strftime'
    • @A.JT - 没有丢失df.date = pd.to_datetime(df.date) df = df.set_index("date") ?
    • 是的,它是一个日期时间
    • @A.JT - print (s.unstack().index) 是什么?
    【解决方案2】:

    首先,要获取月份的名称,重置索引并选择正确的列:

    df['month'] = df['date'].apply(lambda x: pd.Timestamp(x).strftime('%B'))
    
    df = df.reset_index()
    
    df = df[['month','category_col','value]]
    

    然后,假设您有一个这样的数据框(称为 df):

    month       category_col     value      
    September   A                41.929004
    September   B                25.758765
    

    使用 Seaborn 执行以下操作以获取您正在寻找的情节:

    import seaborn as sns 
    ax = sns.barplot(x="month", y="value", hue="category_col", data=df)
    

    【讨论】:

      猜你喜欢
      • 2013-10-20
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 2018-11-23
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多