wesm / pydata-book

Materials and IPython notebooks for "Python for Data Analysis" by Wes McKinney, published by O'Reilly Media
Other
22.27k stars 15.2k forks source link

Ch9: datetime object needs to be converted to ordinal number #78

Closed aalhaimi closed 3 years ago

aalhaimi commented 6 years ago

Just wanted to report a small issue I had with the code posted in ch9 under the heading Annotations and Drawing on a Subplot

from datetime import datetime

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

data = pd.read_csv('examples/spx.csv', index_col=0, parse_dates=True)
spx = data['SPX']

spx.plot(ax=ax, style='k-')

crisis_data = [
    (datetime(2007, 10, 11), 'Peak of bull market'),
    (datetime(2008, 3, 12), 'Bear Stearns Fails'),
    (datetime(2008, 9, 15), 'Lehman Bankruptcy')
]

for date, label in crisis_data:
    ax.annotate(label, xy=(date, spx.asof(date) + 75),
                xytext=(date, spx.asof(date) + 225),
                arrowprops=dict(facecolor='black', headwidth=4, width=2,
                                headlength=4),
                horizontalalignment='left', verticalalignment='top')

# Zoom in on 2007-2010
ax.set_xlim(['1/1/2007', '1/1/2011'])
ax.set_ylim([600, 1800])

ax.set_title('Important dates in the 2008-2009 financial crisis')

This section didn't work for me. Had to convert the date in the for loop from the object to ordinal number.

The updated for loop looks like this:

for date, label in crisis_data:
    ax.annotate(label, xy=(date.toordinal(), spx.asof(date) + 75),
                xytext=(date.toordinal(), spx.asof(date) + 225),
                arrowprops=dict(facecolor='black', headwidth=4, width=2,
                                headlength=4),
                horizontalalignment='left', verticalalignment='top')
wesm commented 3 years ago

This appears to work correctly with the latest version of matplotlib, so this was likely a bug in the past