【发布时间】:2020-07-16 20:02:16
【问题描述】:
我有一个 plot_graph() 函数,可以将 pandas 数据框绘制为折线图。
def plot_graph(df):
ax = plt.gca()
#df["Date"].dt.strftime("%m/%d/%y")
#df["date"] = df["date"].astype('datetime64[ns]')
print(df['date'])
df.plot(kind='line', x='date', y='Actual', ax=ax)
df.plot(kind='line', x='date', y='Expected', color='red', ax=ax)
ax.xaxis.set_major_locator(plt.MaxNLocator(3))
plt.savefig("fig1.png")
我以这种格式传递 pandas 数据帧
date actual expected
2019-11 20 65
2019-12 35 65
当我绘制折线图时,x 轴标签无法以 (yyyy-mm) 格式正确显示。我相信它是日期格式。所以我尝试将其转换为日期。我尝试了所有选项(在代码中注释),似乎没有任何效果。任何建议都会受到欢迎。
【问题讨论】:
-
使用 Matplotlib 的 DateFormatter?
-
@QuangHoang:效果也不好
-
你的
ax.xaxis.set_major_locator(plt.MaxNLocator(3))看起来很危险:-)。 -
@QuangHoang:好的,这是我的尝试之一,但效果不佳
标签: python pandas matplotlib