gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:13:29 25 4
gpt4 key购买 nike

我曾搜索过如何使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com