Home > Back-end >  Entire data from date range not being plotted in matplotlib
Entire data from date range not being plotted in matplotlib

Time:12-14

I have the following code:

import pandas as pd
from pandas import DataFrame as df
import matplotlib
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import datetime
import warnings
warnings.filterwarnings("ignore")
from matplotlib.dates import date2num
from matplotlib import dates as mdates
from matplotlib.ticker import NullFormatter
from matplotlib.dates import MonthLocator, DateFormatter

start = datetime.date(2021,1,1)
end = datetime.date.today()

stock =  'fb'

data = web.DataReader(stock, 'yahoo', start, end)
data.index = pd.to_datetime(data.index, format ='%Y-%m-%d')
data = data[~data.index.duplicated(keep='first')]
data.reset_index()

data['month'] = data.index.month
data['week'] = data.index.week
data['day'] = data.index.day
data = data.reset_index()
del data['Date']
data.set_index('month',append=True,inplace=True)
data.set_index('week',append=True,inplace=True)
data.set_index('day',append=True,inplace=True)

fig, ax = plt.subplots(dpi=300, figsize =(15,4))
plt.plot(data.index.get_level_values(0), data['Close'])
locator = mdates.MonthLocator()
ax.xaxis.set_major_locator(MonthLocator())
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

ax.xaxis.set_major_formatter(NullFormatter())
ax.xaxis.set_major_formatter(DateFormatter('%b'))

plt.show()

This code produces the following plot: enter image description here

For some reason it is not plotting right. Since the data here is till the month of December but for some reason it is just showing the plot till end of August.

CodePudding user response:

Enter Datetime in X-Axis

data = web.DataReader(stock, 'yahoo', start, end)

# first always do sorting
data = data.sort_index()

# then create x and y axis
x = []
y = []
for index, row in data.iterrows():
    x.append(index.date())
    y.append(row['Close'])

# then create your plot
fig, ax = plt.subplots(dpi=300, figsize =(15,4))
plt.plot(x, y)

locator = mdates.MonthLocator()
ax.xaxis.set_major_locator(MonthLocator())
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

ax.xaxis.set_major_formatter(NullFormatter())
ax.xaxis.set_major_formatter(DateFormatter('%b'))

plt.show()

I checked it on my system it was working like below:

Graph

  • Related