NaN
NaN

Reputation: 691

How can I change the x-axis index date format in matplotlib?

My code below outputs the following image:

from datetime import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
import os

start = dt(2017, 1, 1)
end = dt.now()

df = web.get_data_yahoo('AAPL', start, end, interval = 'd')
df['30_sma'] = df['Adj Close'].rolling(window=30, 
min_periods=None).mean()

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(df.index, df['Adj Close'])
ax.plot(df.index, df['30_sma'])
plt.show()

AAPL stock price, bad date format

I would like the date to show up as YYYY-MM-DD or YYYY-MM format. I have tried creating a new column in my data frame made up of the index, but that did not change anything when I plotted it.

Upvotes: 1

Views: 2385

Answers (1)

cs95
cs95

Reputation: 402263

This would work by calling df.plot and passing ax as a parameter -

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

df[['Adj Close', '30_sma']].plot(ax=ax)
plt.show()

enter image description here

Upvotes: 1

Related Questions