【问题标题】:How to make bar plot with converting the month column in python?如何通过在python中转换月份列来制作条形图?
【发布时间】:2016-12-21 17:16:53
【问题描述】:

我有一个这样的数据框。月份列是字符串类型。 我想制作一个从 201501 到 201505 的条形图,其中 x 轴是月份,而 y 轴是 total_gmv。 x 格式就像 Jan,2015 Feb 2015。那么我怎样才能使用 python 实现呢?谢谢。

month   total_gmv
201501  NaN
201502  2.824294e+09
201503  7.742665e+09
201504  2.024132e+10
201505  6.705012e+10

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    df = pd.DataFrame(
        {'month': ['201501', '201502', '201503', '201504', '201505'], 
         'total_gmv': [np.nan, 2.824294e+09, 7.742665e+09, 2.024132e+10, 6.705012e+10]})
    
    df['month'] = pd.to_datetime(df['month'], format='%Y%m').dt.month
    df = df.set_index('month')
    
    print df
    df.plot(kind='bar')
    plt.show()
    

    结果:

              total_gmv
    month              
    1               NaN
    2      2.824294e+09
    3      7.742665e+09
    4      2.024132e+10
    5      6.705012e+10
    

    【讨论】:

    • 谢谢。实际上我希望将 x 轴标记为 Jan.2015 feb.2015
    【解决方案2】:

    您应该能够强制月份为时间戳,然后将其设置为索引并绘制它。

    df['month'] = pd.to_datetime(df.month)
    ax = df.set_index('month').plot(kind='bar')
    

    您可能必须更改日期格式。

    import matplotlib.dates as mdates
    ax.xaxis.set_major_formatter= mdates.DateFormatter('%b, %Y')
    

    查看here for more

    【讨论】:

      【解决方案3】:

      以前的回复有一些线索,但它没有显示详尽的答案。 您必须设置自定义 xtick 标签并像这里一样旋转它:

      import numpy as np
      import pandas as pd
      import matplotlib.pyplot as plt
      
      df = pd.DataFrame(
          {'month': ['201501', '201502', '201503', '201504', '201505'], 
           'total_gmv': [np.nan, 2.824294e+09, 7.742665e+09, 2.024132e+10, 6.705012e+10]})
      df['month'] = pd.to_datetime(df['month'], format='%Y%m', errors='ignore')
      
      ax = df.plot(kind='bar')
      ax.set_xticklabels(df['month'].dt.strftime('%b, %Y'))
      plt.xticks(rotation=0)
      plt.show()
      

      【讨论】:

        【解决方案4】:

        您应该使用matplotlib.pyplotcalendar 模块。

        import matplotlib.pyplot as plt
        import calendar
        
        #change the numeric representation to texts (201501 -> Jan,2015)
        df['month_name'] = [','.join([calendar.month_name[int(date[-1:-3]),date[-3:]] for date in df['month']
        
        #change the type of df['month'] to int so plt can read it
        df['month'].apply(int)
        
        x = df['month']
        y = df['total_gmv']
        plt.bar(x, y, align = 'center')
        
        #i'm not sure if you have to change the Series to a list; do whatever works
        plt.xticks =(x, df['month_name']) 
        plt.show()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-11-11
          • 2012-11-26
          • 2020-09-28
          • 2019-07-30
          • 1970-01-01
          • 2017-01-12
          • 1970-01-01
          相关资源
          最近更新 更多