Search code examples
pythonpandasmatplotlibpandas-datareader

x-axis dates not showing up on matplotlib when importing data from pandas DataReader


I'm using pandas DataReader to graph stock charts in matplotlib, but the dates don't show up on the x-axis when I use the following code:

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'])

Result: Chart of SPY with no x-axis dates

However, when I import the same data from csv using the following command, the dates show up just fine when I plot the data:

spy_csv = pd.read_csv('spy.csv',index_col='date',parse_dates=True)

I'm assuming the "parse_dates=True" is making the difference, so I'm wondering if there is an equivalent command when importing from DataReader. What would that equivalent look like in my DataReader code?


Solution

  • I think you should change your index to datetime format

    spy.index=pd.to_datetime(spy.index)
    

    Then , pass the xlim by using Timestamp

    spy['open'].plot(xlim=[pd.Timestamp('2018-01-01'),pd.Timestamp('2018-02-28')])
    

    enter image description here