首页 > 解决方案 > 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)

标签: pythondatedatetimebar-chartseaborn

解决方案


同时,我使用以下调整找到了一个可行的解决方案

    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方式来处理这个问题,请告诉我。


推荐阅读