Search code examples
pythonmatplotlibtrendline

Python Matplotlib axis is blank for date with trend line


I can correctly plot a trendline with price data but the both X Y axis of date formatting is blank. I am not sure what is messing up this plot configuration for the axis. Here is the Python 2.7 code:

y = df['Close']

# calc the trendline http://stackoverflow.com/questions/26447191/how-to-add-trendline-in-python-matplotlib-dot-scatter-graphs

l = []
for t in df['Time']:
    datetime_object = datetime.datetime.strptime(str(t), '%H:%M')
    print datetime_object.hour
    print datetime_object.minute
    l.append((3600 * datetime_object.hour + 60 * datetime_object.minute))
x = l
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
fig = plt.figure()
ax = fig.add_subplot(111)

#http://stackoverflow.com/questions/17709823/plotting-timestamps-hour-minute-seconds-with-matplotlib
plt.xticks(rotation=25)
ax = plt.gca()
ax.set_xticks(x)
xfmt = md.DateFormatter('%H:%M')
ax.xaxis.set_major_formatter(xfmt)

ax.plot(x, p(x), 'r--')
ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%3.4f')) #http://stackoverflow.com/questions/29188757/matplotlib-specify-format-of-floats-for-tick-lables
plt.show()

Also, df['Close'] would have value samples of:

114.684
114.679

df['Time'] would contains sample values:

23:20
23:21

Solution

  • Update: I found the source of your problem.

    In addition to the below problem you incorrectly copied the answer to the linked question.

    You wrote: ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%3.4f')) You need: ax.yaxis.set_major_formatter(FormatStrFormatter('%3.4f'))

    See updated graph:

    https://i.sstatic.net/4fhxY.jpg

    In your code, you begin axis changes before you have actually plotted anything.

    If you move your ax.plot(x, p(x), 'r--') to just below your add_subplot line this will work:

    import numpy as np
    from matplotlib import pyplot as plt
    import datetime
    
    import matplotlib
    from matplotlib.ticker import FormatStrFormatter
    
    df = pandas.DataFrame()
    df['Time'] = pandas.Series(['23:2','22:1'])
    df['Close'] = pandas.Series([114.,114.])
    
    y = df['Close']
    
    # calc the trendline http://stackoverflow.com/questions/26447191/how-to-add-trendline-in-python-matplotlib-dot-scatter-graphs
    
    l = []
    for t in df['Time']:
        datetime_object = datetime.datetime.strptime(str(t), '%H:%M')
        print datetime_object.hour
        print datetime_object.minute
        l.append((3600 * datetime_object.hour + 60 * datetime_object.minute))
    x = l
    z = np.polyfit(x, y, 1)
    p = np.poly1d(z)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    #Added:
    ax.plot(x, p(x), 'r--')
    
    #http://stackoverflow.com/questions/17709823/plotting-timestamps-hour-   minute-seconds-with-matplotlib
    plt.xticks(rotation=25)
    ax = plt.gca()
    ax.set_xticks(x)
    xfmt = md.DateFormatter('%H:%M')
    ax.xaxis.set_major_formatter(xfmt)
    
    # REMOVED: ax.plot(x, p(x), 'r--')
    # Changed: ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%3.4f')) 
    ax.yaxis.set_major_formatter(FormatStrFormatter('%3.4f'))
    #http://stackoverflow.com/questions/29188757/matplotlib-specify-format-of-    floats-for-tick-lables
    plt.show()