python - Seaborn Barplot 日期轴不可格式化
问题描述
如何调整 seaborn x 轴的日期格式?我通常使用
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
但这会引发错误
ValueError: DateFormatter found a value of x=0, which is an illegal date
尽管日期数据的格式正确为 dtype='datetime64[ns]' 并且没有 0 值。
该图表由
data = data.melt('Name', var_name='country', value_name='cpi')
data.set_index('Name',inplace=True)
fig, ax = plt.subplots(figsize=(10, 6), dpi=80)
ax = sns.barplot(x=data.index, y='cpi', hue='country', data=data, ax=ax)
fig.autofmt_xdate()
这是日期轴数据的样子:
data.index
Out[286]:
DatetimeIndex(['2019-04-30', '2019-05-31', '2019-06-30', '2019-07-31',
'2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',
'2019-12-31', '2020-01-31', '2020-02-29', '2020-03-31',
'2019-04-30', '2019-05-31', '2019-06-30', '2019-07-31',
'2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',
'2019-12-31', '2020-01-31', '2020-02-29', '2020-03-31',
'2019-04-30', '2019-05-31', '2019-06-30', '2019-07-31',
'2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',
'2019-12-31', '2020-01-31', '2020-02-29', '2020-03-31',
'2019-04-30', '2019-05-31', '2019-06-30', '2019-07-31',
'2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',
'2019-12-31', '2020-01-31', '2020-02-29', '2020-03-31',
'2019-04-30', '2019-05-31', '2019-06-30', '2019-07-31',
'2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',
'2019-12-31', '2020-01-31', '2020-02-29', '2020-03-31',
'2019-04-30', '2019-05-31', '2019-06-30', '2019-07-31',
'2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',
'2019-12-31', '2020-01-31', '2020-02-29', '2020-03-31'],
dtype='datetime64[ns]', name='Name', freq=None)
解决方案
同时,我使用以下调整找到了一个可行的解决方案
ax.set_xticklabels([datetime.strptime(t.get_text(), '%Y-%m-%dT%H:%M:%S.%f000').strftime('%b %Y') for t in ax.get_xticklabels()])
我不认为它很漂亮,所以如果你有更多的pythonic方式来处理这个问题,请告诉我。
推荐阅读
- python - 编写一个程序,一个数字由三个数字组成,将数字分成单独的数字
- javascript - 承诺然后拒绝,然后解决
- apache-kafka - debian上的融合路径在哪里
- python - 如何检查 Python 日志的最大错误级别?
- opayo - 正确挑战后 3DSv2 Sagepay 直接集成“找不到页面”
- javascript - 我可以通过 API 获得 Linkedin 个人资料的活动状态吗?
- ios - 将视频保存到我的相机胶卷返回错误:操作无法完成。(可可错误-1。)
- python - 如何将 Matplotlib 图形转换为 PIL Image 对象(不保存图像)
- python - 将数据类型系列转换为日期时间
- python - Numpy 对两个数组进行排序,其中一个数组作为轴 1 中的键