Matplotlib autodatelocator custom date formatting?

Posted by jawonlee on Stack Overflow See other posts from Stack Overflow or by jawonlee
Published on 2010-06-08T23:41:48Z Indexed on 2010/06/09 18:22 UTC
Read the original article Hit count: 245

Filed under:
|

I'm using Matplotlib to dynamically generate .png charts from a database. The user may set as the x-axis any given range of datetimes, and I need to account for all of it. While Matplotlib has the dates.AutoDateLocator(), I want the datetime format printed on the chart to be context-specific - e.g. if the user is charting from 3 p.m. to 5 p.m., the year/month/day information doesn't need to be displayed. Right now, I'm manually creating Locator and Formatter objects thusly:

def get_ticks(start, end):
    from datetime import timedelta as td
    delta = end - start

    if delta <= td(minutes=10):
        loc = mdates.MinuteLocator()
        fmt = mdates.DateFormatter('%I:%M %p')
    elif delta <= td(minutes=30):
        loc = mdates.MinuteLocator(byminute=range(0,60,5))
        fmt = mdates.DateFormatter('%I:%M %p')
    elif delta <= td(hours=1):
        loc = mdates.MinuteLocator(byminute=range(0,60,15))
        fmt = mdates.DateFormatter('%I:%M %p')
    elif delta <= td(hours=6):
        loc = mdates.HourLocator()
        fmt = mdates.DateFormatter('%I:%M %p')
    elif delta <= td(days=1):
        loc = mdates.HourLocator(byhour=range(0,24,3))
        fmt = mdates.DateFormatter('%I:%M %p')
    elif delta <= td(days=3):
        loc = mdates.HourLocator(byhour=range(0,24,6))
        fmt = mdates.DateFormatter('%I:%M %p')
    elif delta <= td(weeks=2):
        loc = mdates.DayLocator()
        fmt = mdates.DateFormatter('%b %d')
    elif delta <= td(weeks=12):
        loc = mdates.WeekdayLocator()
        fmt = mdates.DateFormatter('%b %d')
    elif delta <= td(weeks=52):
        loc = mdates.MonthLocator()
        fmt = mdates.DateFormatter('%b')
    else:
        loc = mdates.MonthLocator(interval=3)
        fmt = mdates.DateFormatter('%b %Y')
    return loc,fmt

Is there a better way of doing this?

© Stack Overflow or respective owner

Related posts about python

Related posts about matplotlib