python - 如何格式化轴 x 日期 ('dd/mm/yyyy' )?

标签 python pandas date matplotlib plot

我曾搜索过如何使用 pandasmatplotlib 将 x 轴的格式从“Y-m-d”更改为“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()

最佳答案

我在 ImportanceOfBeingErnest 的帮助下解决了这个问题,使用 xticklabels

df_w = df['week'] == dt.datetime.strptime('2016-03-13','%Y-%m-%d')
ax = df[df_w].plot(kind='bar',x='week');
ax.set_xlabel("Week");
new_label = []
for i in ax.get_xticklabels():
    date = dt.datetime.strptime(i.get_text(), '%Y-%m-%d %H:%M:%S')
    new_label.append(date.strftime("%d/%m/%Y"))

ax.set_xticklabels(new_label);

output

关于python - 如何格式化轴 x 日期 ('dd/mm/yyyy' )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48344566/

相关文章:

python - 从 URL 中读取图像并保存在内存中

python - Django、 celery 、Redis、RabbitMQ : Chained Tasks for Fanout-On-Writes

python - python 中的范围和 "for loops"?

python - 使用请求获取 .onion 域

python - 如何用条件逐行替换

python - 使用 Pandas 自定义排名选择

python - 使用 numpy 将数据分组为时间相关集

javascript - 如何在jquery中比较两个格式为 "dd-mm-yyyy hh:mm"的日期

swift - "EEE, dd MMM yyyy hh:mm:ss zzz"字符串转换为日期

php - 按上个月、上周、昨天等查询