如何使用matplotlib绘制正确的日期?
我正在尝试使用Python、pandas和matplotlib,但遇到了一些新手问题。
这是我简单的脚本:
from dateutil.relativedelta import relativedelta
import Quandl
start_date = datetime.datetime.now() - relativedelta(days=5)
data_frame = Quandl.get("GOOG/NASDAQ_AAPL",
trim_start=start_date)
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot(data_frame['Close'].index, data_frame['Close'])
plt.gcf().autofmt_xdate()
plt.savefig('plot')
plt.close()
这个脚本生成了下面的图:

我想知道怎么才能让x轴显示格式好看的日期(比如2014-04-24)?
我猜这和data_frame['Close'].index
有关。它现在显示的是:
<class 'pandas.tseries.index.DatetimeIndex'>
[2014-04-21, ..., 2014-04-25]
Length: 5, Freq: None, Timezone: None
我原本期待看到类似于[1950-01-31 00:00:00, ..., 2013-02-28 00:00:00]
这样的输出,这是我在网上看到的文章中提到的。所以我在考虑是否需要使用datetime.strptime
,但不确定这样做是否正确;而且我也不太清楚怎么能简洁地与日期时间索引一起使用。
谢谢你的时间!
1 个回答
0
在 matplotlib
这个库里,你可以通过直接修改 major_formater
来获得想要的 x 轴刻度格式。
import matplotlib.dates as mdates
plt.plot(data_frame['Close'].index, data_frame['Close'])
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y/%b/%d-%H:%S'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=1))
plt.xticks(rotation=45, fontsize = 8)