如何调整海波恩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)
你的解决方案看起来不错,我给它加了个赞。如果你想要一些不那么啰嗦的东西,你可以这样做。
x_dates = data.index.strftime('%b %Y').sort_values().unique()
ax.set_xticklabels(labels=x_dates, rotation=45, ha='right')
这样你就不需要 fig.autofmt_xdate()
呼叫。
同时,我想出了一个有效的解决方案,使用以下调整
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的处理方式请告诉我。