Cassie H.
Cassie H.

Reputation: 393

Making values of the axis dates on a matplotlib graph

I have a time series graph made using pandas and matplotlib. My function looks like this:

def graph(file):
    pdf = PdfPages('...pdf')
    # Temporal Change (Time Series)
    pd.read_csv(file, usecols=['close','open']).plot()
    plt.xlabel('Date')
    plt.ylabel('Value')
    plt.title('Open/Close Over Time')
    plt.show()

My data file has headers corresponding to values, and the date header is at index 0. (If thats relevant?)

Right now the graph works but the index of the value is displayed for time instead of the date. How would I make the x-axis(Date) display the dates that correspond to the data instead of the index?

EDIT: Data file looks like this

date    close   volume  open    high    low
2017/09/13  173.05  9112378 173.01  173.17  172.06
2017/09/12  172.96  11179730    173.76  174 171.75
2017/09/11  173.51  12353760    172.4   173.89  172.2
2017/09/08  170.95  10985350    173.09  173.49  170.8
2017/09/07  173.21  18039640    171.94  173.3067    170.27
2017/09/06  172.09  13886740    170.91  172.48  169.57
2017/09/05  170.72  13214940    171.27  172.3875    169.55
2017/09/01  172.02  11663360    172.4   172.915 171.31
2017/08/31  171.97  17216280    170.4   172.145 170.06

Is a .csv file, ^that was copied from it being open in excel

Upvotes: 0

Views: 93

Answers (1)

Paul H
Paul H

Reputation: 68146

If you're going to use pandas's plotting methods and want datetimes, I recommend ensuring that you're parsing the dates and setting them as the index. I also, recommend the object-oriented matplotlib interface.

from io import StringIO
from matplotlib import pyplot
import pandas

datafile = StringIO("""\
date    close   volume  open    high    low
2017/09/13  173.05  9112378 173.01  173.17  172.06
2017/09/12  172.96  11179730    173.76  174 171.75
2017/09/11  173.51  12353760    172.4   173.89  172.2
2017/09/08  170.95  10985350    173.09  173.49  170.8
2017/09/07  173.21  18039640    171.94  173.3067    170.27
2017/09/06  172.09  13886740    170.91  172.48  169.57
2017/09/05  170.72  13214940    171.27  172.3875    169.55
2017/09/01  172.02  11663360    172.4   172.915 171.31
2017/08/31  171.97  17216280    170.4   172.145 170.06
""")

fig, ax = pyplot.subplots(figsize=(7, 5))
_ = (
    pandas.read_csv(datafile, sep='\s+',
                    usecols=['date', 'open', 'close'],
                    parse_dates=['date'])
        .set_index('date')
        .plot(ax=ax)
)
ax.set_xlabel('Date')
ax.set_ylabel('BUY! SELL!')
ax.set_title('Money money money money')

enter image description here

Upvotes: 3

Related Questions