[Tutor] matplotlib question - Dates not showing up on X axis

eryksun eryksun at gmail.com
Tue Nov 6 05:02:44 CET 2012


On Mon, Nov 5, 2012 at 12:42 PM, jim schmidt <txherper at gmail.com> wrote:
>
>     fig = figure()
>
>     ax = fig.add_subplot(1,1,1)
>     ax.plot_date(dates, kbSec, '-')
>
>     ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO))
>     ax.xaxis.set_major_formatter(DateFormatter('%m-%d'))
>     fig.autofmt_xdate()
>     show()

The dates have to be in ordinal form (i.e. days since 1/1/1). You can
use datetime's toordinal() method for that, or
matplotlib.dates.epoch2num:

    from pylab import figure, show
    from matplotlib.dates import (epoch2num, WeekdayLocator,
      DateFormatter, MONDAY)

    # epoch dates - 10/21, 10/29, 11/5
    epoch_dates = [1350792000, 1351483200, 1352091600]
    # convert to ordinal form
    dates = [epoch2num(d) for d in epoch_dates]
    kbSec = [24.3, 32.5, 21]

    fig = figure()
    ax = fig.add_subplot(1,1,1)
    ax.plot_date(dates, kbSec, '-')
    ax.xaxis.set_major_locator(WeekdayLocator(MONDAY))
    ax.xaxis.set_major_formatter(DateFormatter('%m-%d'))
    fig.autofmt_xdate()
    show()


More information about the Tutor mailing list