我正在尝试格式化我的x轴以仅显示日期。这是我的代码:
start = datetime(2017, 1, 1)
end = datetime(2018, 3, 9)
stock = web.DataReader('AAPL', 'morningstar', start, end)
daily_close = stock[['Close']]
stock['Close'].plot(figsize=(12,8))
plt.xlabel('Date')
plt.xticks(rotation=30)
plt.show()
答案 0 :(得分:0)
将这些行放在plt.show()
date_labels = [dt.strftime('%Y-%m-%d') for dt in stock.index.get_level_values('Date')]
ticks, labels = plt.xticks()
new_labels = [date_labels[int(i)] for i in ticks if i < len(date_labels)]
new_ticks = ticks[0:len(new_labels)]
plt.xticks(new_ticks, new_labels)
代码将日期时间从索引转换为表示日期的字符串列表,并用相应的日期覆盖X轴上的刻度标签。