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

Posted

技术标签:

【中文标题】如何更正python matplotlib图中x标签的顺序【英文标题】:How to correct the order of x labels in python matplotlib graph 【发布时间】: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 月恢复,如图所示(图表的确切值不同,因为我更改了值)。我怎样才能把它按正确的顺序排列?

【问题讨论】:

【参考方案1】:

您可以使用以下方法。这个想法是对月份列进行排序,如this和this 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 循环以绘制年份之前

【讨论】:

以上是关于如何更正python matplotlib图中x标签的顺序的主要内容,如果未能解决你的问题,请参考以下文章

使用 Matplotlib 如何在最终图中突出显示一个点

如何从 seaborn / matplotlib 图中删除或隐藏 x 轴标签

如何在 matplotlib 图中设置默认缩放?

如何在一个图中构建两个图,模块 Matplotlib [重复]

Python,x轴标题与matplotlib中的刻度标签重叠

如何在 Python matplotlib 子图中显示图例