【问题标题】:How to correct the order of x labels in python matplotlib graph如何更正python matplotlib图中x标签的顺序
【发布时间】:2020-09-05 14:26:09
【问题描述】:

我想要绘制以下数据。

month      year       total_sales
May         2020        7
June        2020        2  
July        2020        1
August      2020        2
September   2020        22 
October     2020       11
November    2020        6
December    2020        3
January     2019        3
feburary    2019        11
March       2019        65 
April       2019        22
May         2019        33
June        2019        88
July        2019        44
August      2019        12
September   2019        32
October     2019        54
November    2019        76
December    2019        23
January     2018        12
feburary    2018        32
March       2018        234
April       2018        2432
May         2018        432

这是我用来执行此操作的代码:

def plot_timeline_data(df):
    fig, ax = plt.subplots()

    ax.set_xticklabels(df['month'].unique(), rotation=90)

    for name, group in df.groupby('year'):
        ax.plot(group['month'], group['total_sales'], label=name,linestyle='--', marker='o')

    ax.legend()
    plt.tight_layout()
    plt.show()

我希望 x 标签的顺序从 1 月到 12 月开始,但我的图表从 5 月到 12 月开始,然后从 1 月到 4 月恢复,如图所示(图表的确切值不同,因为我更改了值)。我怎样才能把它按正确的顺序排列?

【问题讨论】:

    标签: python python-3.x pandas matplotlib


    【解决方案1】:

    您可以使用以下方法。这个想法是对月份列进行排序,如thisthis post中所示

    # Capitalize the month names
    df["month"] = df["month"].str.capitalize()
    
    # Correct the spelling of February
    df['month'] = df['month'].str.replace('Feburary','February')
    
    # Convert to datetime object for sorting
    df['month_in'] = pd.DatetimeIndex(pd.to_datetime(df['month'], format='%B')).month
    
    # Sort using the index
    df = df.set_index('month_in').sort_index()
    
    plot_timeline_data(df)
    

    【讨论】:

      【解决方案2】:

      Dataframe.plot 让您的工作更轻松 - 它将每个系列绘制为不同的线,并保持您指定的顺序:

      import matplotlib.pyplot as plt
      
      # Convert the dataframe to series of years
      df = df.set_index(["month","year"])["total_sales"].unstack()
      # Sort the index (which is month)
      df = df.loc[[
          "January","feburary","March","April","May","June",
          "July", "August", "September","October", "November", "December"
      ]]
      # Plot!
      df.plot(marker="o", linestyle="--", rot=90)
      # Show all ticks
      plt.xticks(range(12), df.index)
      

      【讨论】:

        【解决方案3】:

        我认为您需要更改熊猫数据框中 'month' 索引的顺序。 尝试添加:

        group['month'] = group['month'][8:] + group['month'][:8]
        

        在取消 for 循环以绘制年份之前

        【讨论】:

          猜你喜欢
          • 2021-04-18
          • 2020-02-04
          • 1970-01-01
          • 2018-02-06
          • 2019-04-03
          • 2019-07-02
          • 1970-01-01
          • 2014-03-13
          • 1970-01-01
          相关资源
          最近更新 更多