3

I am trying to use matplotlib to graph stock prices against a datetime index.

So I have a graph that looks like this:

Data looks like this.

And I need it to look like this:

Data looks like this.

I think it might have something to do with xticks, but I cannot figure out how to make xticks work with a datetime index. Thanks for the help.

tesla['Open'].plot(title='Open Price', label = 'Tesla', figsize = (16, 6))  
ford['Open'].plot(label = 'ford')  
gm['Open'].plot(label = 'GM')  
plt.legend()  
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
Danny
  • 470
  • 4
  • 14
mikecaro2
  • 35
  • 1
  • 4

1 Answers1

2

Like this:

import pandas as pd
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame({'values':np.random.randint(0,1000,36)},index=pd.date_range(start='2014-01-01',end='2016-12-31',freq='M'))
fig,ax1 = plt.subplots()
plt.plot(df.index,df.values)
monthyearFmt = mdates.DateFormatter('%Y-%m')
ax1.xaxis.set_major_formatter(monthyearFmt)
_ = plt.xticks(rotation=45)

Output:

enter image description here

EDIT:

Let's use set_major_locator with MonthLocator

import pandas as pd
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame({'values':np.random.randint(0,1000,36)},index=pd.date_range(start='2014-01-01',end='2016-12-31',freq='M'))
fig,ax1 = plt.subplots()
plt.plot(df.index,df.values)
monthyearFmt = mdates.DateFormatter('%Y-%m')
ax1.xaxis.set_major_formatter(monthyearFmt)
ax1.xaxis.set_major_locator(mdates.MonthLocator([1,7]))
_ = plt.xticks(rotation=45)

Output:

enter image description here

Scott Boston
  • 147,308
  • 15
  • 139
  • 187
  • This works for getting it into the correct format, but it does not allow me to specify the number of xticks there are on the x axis. My graph currently has 6 and I would like to have 9. Thank you for the additional information though. – mikecaro2 Apr 13 '18 at 03:31
  • @mikecaro2 is this what you are looking for? – Scott Boston Apr 13 '18 at 03:50
  • 1
    This doesn't answer the question. -1 – Hamlett Oct 17 '19 at 02:59