我现在使用这些代码绘制了一个非常简单的(x轴上的年、月)日期的直方图:
#!/usr/bin/python
import pandas as pd
import matplotlib.pyplot as plt
file = 'dates.txt'
df = pd.read_csv("dates.txt", header=None)
df["dates"] = pd.to_datetime(df[0])
grouped = df["dates"].groupby([df["dates"].dt.year, df["dates"].dt.month]).count().plot(kind="bar")
plt.show()
它看起来像这样:
我希望用相应的月份缩写替换月份的数字表示。例如,(2015,7) --> (2015,7月)。因此,我在下面的脚本中尝试了以下代码apply(lambda x: calendar.month_abbr[x])
:
#!/usr/bin/python
import pandas as pd
import matplotlib.pyplot as plt
import calendar
file = 'dates.txt'
df = pd.read_csv("dates.txt", header=None)
df["dates"] = pd.to_datetime(df[0])
#print(df["dates"])
#df.groupby(df["dates"].dt.month).count().plot(kind="bar")
graph = df["dates"].groupby([df["dates"].dt.year, df["dates"].dt.month.apply(lambda x: calendar.month_abbr[x])]).count().plot(kind="bar", y="Calls")
graph.set_ylabel("Call Volume")
graph.set_xlabel("Date")
plt.show()
但这给了我一些意想不到的输出。月份进行了转换,但现在它们的顺序是错误的。
发布于 2019-06-26 08:37:49
您可以尝试按月份周期分组,并手动重新标记刻度:
new_df = df["dates"].groupby(df.dates.dt.to_period('M')).count()
# new label
labels = new_df.index.strftime("%Y-%b")
# plot and re-label:
fig, ax = plt.subplots(figsize=(16,9))
new_df.plot(kind="bar", ax=ax)
ax.set_xticklabels(labels)
plt.show()
输出:
https://stackoverflow.com/questions/56763581
复制相似问题