从 pandas DataReader 导入数据时,x 轴日期未显示在 matplotlib 上
x-axis dates not showing up on matplotlib when importing data from pandas DataReader
我正在使用 pandas DataReader 在 matplotlib 中绘制股票图表,但是当我使用以下代码时,日期没有显示在 x 轴上:
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import datetime as dt
from datetime import datetime
import pandas_datareader.data as web
start = datetime(2014,1,1)
end = datetime(2018,9,27)
spy = web.DataReader('SPY','iex',start,end)
spy['open'].plot(xlim=['2018-01-01','2018-02-28'])
结果:
Chart of SPY with no x-axis dates
但是,当我使用以下命令从 csv 导入相同的数据时,绘制数据时日期显示得很好:
spy_csv = pd.read_csv('spy.csv',index_col='date',parse_dates=True)
我假设 "parse_dates=True" 有所不同,所以我想知道从 DataReader 导入时是否有等效命令。在我的 DataReader 代码中,这个等价物会是什么样子?
我认为您应该将索引更改为 datetime
格式
spy.index=pd.to_datetime(spy.index)
然后,使用 Timestamp
传递 xlim
spy['open'].plot(xlim=[pd.Timestamp('2018-01-01'),pd.Timestamp('2018-02-28')])
我正在使用 pandas DataReader 在 matplotlib 中绘制股票图表,但是当我使用以下代码时,日期没有显示在 x 轴上:
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import datetime as dt
from datetime import datetime
import pandas_datareader.data as web
start = datetime(2014,1,1)
end = datetime(2018,9,27)
spy = web.DataReader('SPY','iex',start,end)
spy['open'].plot(xlim=['2018-01-01','2018-02-28'])
结果: Chart of SPY with no x-axis dates
但是,当我使用以下命令从 csv 导入相同的数据时,绘制数据时日期显示得很好:
spy_csv = pd.read_csv('spy.csv',index_col='date',parse_dates=True)
我假设 "parse_dates=True" 有所不同,所以我想知道从 DataReader 导入时是否有等效命令。在我的 DataReader 代码中,这个等价物会是什么样子?
我认为您应该将索引更改为 datetime
格式
spy.index=pd.to_datetime(spy.index)
然后,使用 Timestamp
spy['open'].plot(xlim=[pd.Timestamp('2018-01-01'),pd.Timestamp('2018-02-28')])