【发布时间】:2018-06-28 21:34:54
【问题描述】:
我已经搜索了如何使用 pandas 和 matplotlib 将我的轴 x 的格式从“Ymd”更改为“d/m/Y”,但我找不到任何适合我的方法。
所以,这是我的代码:
import matplotlib.dates as mdates
df_w = df['week'] == dt.datetime.strptime('2016-03-13','%Y-%m-%d')
ax = df[df_w].plot(kind='bar',x='week');
_fmt = mdates.DateFormatter('%d/%m/%Y')
ax.xaxis.set_major_formatter(_fmt)
我收到了这个错误:
ValueError: DateFormatter found a value of x=0, which is an illegal
date. This usually occurs because you have not informed the axis that
it is plotting dates, e.g., with ax.xaxis_date()
【问题讨论】:
-
即使我输入 ax.xaxis_date () 我也会得到同样的错误。
-
您不能在使用 pandas 创建的轴上使用 matplotlib 日期格式化程序。这是非常不幸的,通常使用 matplotlib.dates 格式化程序功能的唯一解决方案是使用任何 matplotlib 绘图函数实际绘制数据,而不是 DataFrame.plot 包装器。
-
但是,由于在这种情况下,目的似乎只绘制一个条形图,您可以简单地将刻度标签替换为您想要阅读的内容。
-
你能告诉我任何使用ticklabel的代码示例吗?
-
如果您提供minimal reproducible example,可以在问题中运行,我可以提供答案。否则,您可能会搜索有关该主题的其他问题的解决方案。
标签: python pandas date matplotlib plot