【问题标题】:Sort by month in a plot在图中按月排序
【发布时间】:2022-12-10 22:44:40
【问题描述】:

我正在使用以下代码绘制图表。

count = dict(crime_data["Month"].value_counts())
x = list (count.keys())
y = list (count.values())
plt.figure(figsize = (8,6))
plt.title(label = "Crime Rate by Month")
plt.ylabel("Number of Crimes")
plt.xlabel("Month")
plt.plot(x,y)
plt.show()

但是,我得到如下图,我想对其进行排序,以便将月份列为一月、二月、三月等。 剧情:https://prnt.sc/L8ql76ruULz-

我怎样才能做到这一点?提前致谢。

【问题讨论】:

  • 你能分享一个最小的可重现的例子吗作为文本count 的?
  • 1 月 21 日 > 9000,2 月 21 日 > 10000,3 月 21 日 > 8500 同样。此数据取自 CSV 文件。

标签: python pandas matplotlib


【解决方案1】:

您可以使用 matplotlib.dates.DateFormatter

给你一般逻辑,我正在使用 cmets 中给出的可重现示例。

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

df = pd.DataFrame({'Month': ['Feb-21', 'Jan-21', 'Mar-21'], 'Count': [10000, 9000, 8500]})

df["Month"] = pd.to_datetime(df["Month"], format="%b-%y")

f, ax = plt.subplots(figsize = [7, 3])
ax.plot(df["Month"], df["Count"])
ax.set_xticks(df["Month"].unique())

ax.xaxis.set_major_formatter(DateFormatter("%b-%Y"))

# 输出 :

使用的数据框:

print(df)
    Month  Count
0  Feb-21  10000
1  Jan-21   9000
2  Mar-21   8500

【讨论】:

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