猿问

如何更正python matplotlib图中x标签的顺序

我有以下要绘制的数据。


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 月恢复,如图所示(图表的确切值因我更改值而不同)。我怎样才能把它按正确的顺序排列?


千万里不及你
浏览 161回答 2
2回答

蛊毒传说

您可以使用以下方法。这个想法是按照这个和这篇文章中所示对月份列进行排序# Capitalize the month namesdf["month"] = df["month"].str.capitalize()# Correct the spelling of Februarydf['month'] = df['month'].str.replace('Feburary','February')# Convert to datetime object for sortingdf['month_in'] = pd.DatetimeIndex(pd.to_datetime(df['month'], format='%B')).month# Sort using the indexdf = df.set_index('month_in').sort_index()plot_timeline_data(df)

牛魔王的故事

Dataframe.plot让你的工作更容易一些 - 它将每个系列绘制为不同的线,并保持你指定的顺序:import matplotlib.pyplot as plt# Convert the dataframe to series of yearsdf = 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 ticksplt.xticks(range(12), df.index)
随时随地看视频慕课网APP

相关分类

Python
我要回答