plotting dates

539 days ago by jason3

import datetime from matplotlib.pyplot import figure, show from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange from numpy import arange date1 = datetime.datetime( 2000, 3, 2) date2 = datetime.datetime( 2000, 3, 6) delta = datetime.timedelta(hours=int(6)) dates = drange(date1, date2, delta) y = arange( len(dates)*1.0) fig = figure() ax = fig.add_subplot(111) ax.plot_date(dates, y*y) # this is superfluous, since the autoscaler should get it right, but # use date2num and num2date to to convert between dates and floats if # you want; both date2num and num2date convert an instance or sequence ax.set_xlim( dates[0], dates[-1] ) # The hour locator takes the hour or sequence of hours you want to # tick, not the base multiple ax.xaxis.set_major_locator( DayLocator() ) ax.xaxis.set_minor_locator( HourLocator(arange(0,25,6)) ) ax.xaxis.set_major_formatter( DateFormatter('%Y-%m-%d') ) ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S') fig.autofmt_xdate() fig.savefig('test.png') 
       
from pylab import figure, show from matplotlib.finance import quotes_historical_yahoo from matplotlib.dates import YearLocator, MonthLocator, DateFormatter import datetime date1 = datetime.date( 1995, 1, 1 ) date2 = datetime.date( 2004, 4, 12 ) years = YearLocator() # every year months = MonthLocator() # every month yearsFmt = DateFormatter('%Y') quotes = quotes_historical_yahoo( 'INTC', date1, date2) if len(quotes) == 0: raise SystemExit dates = [q[0] for q in quotes] opens = [q[1] for q in quotes] fig = figure() ax = fig.add_subplot(111) ax.plot_date(dates, opens, '-') # format the ticks ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(yearsFmt) ax.xaxis.set_minor_locator(months) ax.autoscale_view() # format the coords message box def price(x): return '$%1.2f'%x ax.fmt_xdata = DateFormatter('%Y-%m-%d') ax.fmt_ydata = price ax.grid(True) fig.autofmt_xdate() fig.savefig('test.png') 
       
# this should work, but apparently we have to convert toordinal() for this to work. # see from matplotlib.dates import YearLocator, DateFormatter import datetime data=[ (datetime.date( 1995, 1, 1 ), 30), (datetime.date( 1996, 3, 1 ), 50), (datetime.date( 1997, 2, 4 ), 40), ] list_plot([(i.toordinal(), j) for i,j in data],ticks=[YearLocator(),None],tick_formatter=[DateFormatter('%Y-%m-%d'),None])