【问题标题】:How Do I Sort Bar Chart by Month Names?如何按月份名称对条形图进行排序?
【发布时间】:2020-11-27 23:35:37
【问题描述】:

我有以下代码,但我希望它按月份而不是总数排序。 日期格式为 YYYY-MM-DD

df.groupby(df['date'].dt.strftime('%B'))['total'].sum().sort_values().plot.bar(figsize=(20,10))

【问题讨论】:

    标签: python python-3.x pandas matplotlib


    【解决方案1】:

    月份名称是字符串,Python 不知道如何将它们与实际顺序联系起来。你可以试试reindex:

    # you need to type this in
    months = ['January', 'February', 'March', 'April',
              'May', 'June', 'July', 'August',
              'September', 'October', 'November', 'December']
    
    (df.groupby(df['date'].dt.strftime('%B'))
       ['total'].sum()
       .reindex(months)
       .plot.bar(figsize=(20,10))
    )
    

    或者,更不容易出错的是将数字月份与名称一起分组,然后丢弃数字:

    (df.groupby([df['date'].dt.month,df['date'].dt.strftime('%B')])
       ['total'].sum()
       .reset_index(level=0)
       .plot.bar(figsize=(20,10))
    )
    

    【讨论】:

      【解决方案2】:

      您需要告诉sort_values() 函数您希望它如何执行此操作。尝试用sort_values(by='date')替换这部分表达式

      【讨论】:

        【解决方案3】:

        只需添加一个新列作为月份并按它排序:

        df['Month'] = df['date'].dt.month    
        df.groupby('Month').sum().sort_values(by = 'Month')['total'].plot.bar(figsize=(20,10))
        

        结果:

        如果您希望按字母顺序排列,请相应地制作月份列:

        df['Month'] = df['date'].dt.month_name()
        df.groupby('Month').sum().sort_values(by = 'Month')['total'].plot.bar(figsize=(20,10))
        

        结果:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-19
          • 2018-06-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多