Python matplotlib.dates.DayLocator() Examples

The following are 21 code examples of matplotlib.dates.DayLocator(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.dates , or try the search function .
Example #1
Source File: test_dates.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_too_many_date_ticks():
    # Attempt to test SF 2715172, see
    # https://sourceforge.net/tracker/?func=detail&aid=2715172&group_id=80706&atid=560720
    # setting equal datetimes triggers and expander call in
    # transforms.nonsingular which results in too many ticks in the
    # DayLocator.  This should trigger a Locator.MAXTICKS RuntimeError
    t0 = datetime.datetime(2000, 1, 20)
    tf = datetime.datetime(2000, 1, 20)
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    with pytest.warns(UserWarning) as rec:
        ax.set_xlim((t0, tf), auto=True)
        assert len(rec) == 1
        assert 'Attempting to set identical left==right' in str(rec[0].message)
    ax.plot([], [])
    ax.xaxis.set_major_locator(mdates.DayLocator())
    with pytest.raises(RuntimeError):
        fig.savefig('junk.png') 
Example #2
Source File: test_dates.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def test_too_many_date_ticks():
    # Attempt to test SF 2715172, see
    # https://sourceforge.net/tracker/?func=detail&aid=2715172&group_id=80706&atid=560720
    # setting equal datetimes triggers and expander call in
    # transforms.nonsingular which results in too many ticks in the
    # DayLocator.  This should trigger a Locator.MAXTICKS RuntimeError
    t0 = datetime.datetime(2000, 1, 20)
    tf = datetime.datetime(2000, 1, 20)
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    with pytest.warns(UserWarning) as rec:
        ax.set_xlim((t0, tf), auto=True)
        assert len(rec) == 1
        assert 'Attempting to set identical left==right' in str(rec[0].message)
    ax.plot([], [])
    ax.xaxis.set_major_locator(mdates.DayLocator())
    with pytest.raises(RuntimeError):
        fig.savefig('junk.png') 
Example #3
Source File: report.py    From simglucose with MIT License 6 votes vote down vote up
def ensemblePlot(df):
    df_BG = df.unstack(level=0).BG
    df_CGM = df.unstack(level=0).CGM
    df_CHO = df.unstack(level=0).CHO
    fig = plt.figure()
    ax1 = fig.add_subplot(311)
    ax2 = fig.add_subplot(312)
    ax3 = fig.add_subplot(313)
    ax1 = ensemble_BG(df_BG, ax=ax1, plot_var=True, nstd=1)
    ax2 = ensemble_BG(df_CGM, ax=ax2, plot_var=True, nstd=1)
    # t = df_CHO.index.to_pydatetime()
    t = pd.to_datetime(df_CHO.index)
    ax3.plot(t, df_CHO)

    ax1.tick_params(labelbottom=False)
    ax2.tick_params(labelbottom=False)
    ax3.xaxis.set_minor_locator(mdates.AutoDateLocator())
    ax3.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M\n'))
    ax3.xaxis.set_major_locator(mdates.DayLocator())
    ax3.xaxis.set_major_formatter(mdates.DateFormatter('\n%b %d'))
    ax3.set_xlim([t[0], t[-1]])
    ax1.set_ylabel('Blood Glucose (mg/dl)')
    ax2.set_ylabel('CGM (mg/dl)')
    ax3.set_ylabel('CHO (g)')
    return fig, ax1, ax2, ax3 
Example #4
Source File: report.py    From simglucose with MIT License 6 votes vote down vote up
def ensemble_BG(BG, ax=None, plot_var=False, nstd=3):
    mean_curve = BG.transpose().mean()
    std_curve = BG.transpose().std()
    up_env = mean_curve + nstd * std_curve
    down_env = mean_curve - nstd * std_curve

    # t = BG.index.to_pydatetime()
    t = pd.to_datetime(BG.index)
    if ax is None:
        fig, ax = plt.subplots(1)
    if plot_var and not std_curve.isnull().all():
        ax.fill_between(
            t, up_env, down_env, alpha=0.5, label='+/- {0}*std'.format(nstd))
    for p in BG:
        ax.plot_date(
            t, BG[p], '-', color='grey', alpha=0.5, lw=0.5, label='_nolegend_')
    ax.plot(t, mean_curve, lw=2, label='Mean Curve')
    ax.xaxis.set_minor_locator(mdates.HourLocator(interval=3))
    ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M\n'))
    ax.xaxis.set_major_locator(mdates.DayLocator())
    ax.xaxis.set_major_formatter(mdates.DateFormatter('\n%b %d'))

    ax.axhline(70, c='green', linestyle='--', label='Hypoglycemia', lw=1)
    ax.axhline(180, c='red', linestyle='--', label='Hyperglycemia', lw=1)

    ax.set_xlim([t[0], t[-1]])
    ax.set_ylim([BG.min().min() - 10, BG.max().max() + 10])
    ax.legend()
    ax.set_ylabel('Blood Glucose (mg/dl)')
    #     fig.autofmt_xdate()
    return ax 
Example #5
Source File: rendering.py    From simglucose with MIT License 6 votes vote down vote up
def adjust_xlim(ax, timemax, xlabel=False):
    xlim = mdates.num2date(ax.get_xlim())
    update = False

    # remove timezone awareness to make them comparable
    timemax = timemax.replace(tzinfo=None)
    xlim[0] = xlim[0].replace(tzinfo=None)
    xlim[1] = xlim[1].replace(tzinfo=None)

    if timemax > xlim[1] - timedelta(minutes=30):
        xmax = xlim[1] + timedelta(hours=6)
        update = True

    if update:
        ax.set_xlim([xlim[0], xmax])
        for spine in ax.spines.values():
            ax.draw_artist(spine)
        ax.draw_artist(ax.xaxis)
        if xlabel:
            ax.xaxis.set_minor_locator(mdates.AutoDateLocator())
            ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M\n'))
            ax.xaxis.set_major_locator(mdates.DayLocator())
            ax.xaxis.set_major_formatter(mdates.DateFormatter('\n%b %d')) 
Example #6
Source File: get_coin_data.py    From crypto_predictor with MIT License 6 votes vote down vote up
def get_graph(df, coin_name, day_interval, dates=True):
    import matplotlib.dates as mdates

    from matplotlib import pyplot as plt

    fig, ax = plt.subplots(figsize=(10, 5))
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%a'))
    if dates:
        plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%b'))
    plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=day_interval))
    plt.gcf().autofmt_xdate()
    plt.xlabel('Date', fontsize=14)
    plt.ylabel('Price', fontsize=14)
    plt.title('{} Price History'.format(coin_name))
    y = df[coin_name]
    plt.plot(df['date'], y) 
Example #7
Source File: test_dates.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def test_too_many_date_ticks():
    # Attempt to test SF 2715172, see
    # https://sourceforge.net/tracker/?func=detail&aid=2715172&group_id=80706&atid=560720
    # setting equal datetimes triggers and expander call in
    # transforms.nonsingular which results in too many ticks in the
    # DayLocator.  This should trigger a Locator.MAXTICKS RuntimeError
    t0 = datetime.datetime(2000, 1, 20)
    tf = datetime.datetime(2000, 1, 20)
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    with pytest.warns(UserWarning) as rec:
        ax.set_xlim((t0, tf), auto=True)
        assert len(rec) == 1
        assert 'Attempting to set identical left==right' in str(rec[0].message)
    ax.plot([], [])
    ax.xaxis.set_major_locator(mdates.DayLocator())
    with pytest.raises(RuntimeError):
        fig.savefig('junk.png') 
Example #8
Source File: test_dates.py    From ImageFusion with MIT License 6 votes vote down vote up
def test_too_many_date_ticks():
    # Attempt to test SF 2715172, see
    # https://sourceforge.net/tracker/?func=detail&aid=2715172&group_id=80706&atid=560720
    # setting equal datetimes triggers and expander call in
    # transforms.nonsingular which results in too many ticks in the
    # DayLocator.  This should trigger a Locator.MAXTICKS RuntimeError
    warnings.filterwarnings(
        'ignore',
        'Attempting to set identical left==right results\\nin singular '
        'transformations; automatically expanding.\\nleft=\d*\.\d*, '
        'right=\d*\.\d*',
        UserWarning, module='matplotlib.axes')
    t0 = datetime.datetime(2000, 1, 20)
    tf = datetime.datetime(2000, 1, 20)
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.set_xlim((t0, tf), auto=True)
    ax.plot([], [])
    ax.xaxis.set_major_locator(mdates.DayLocator())
    assert_raises(RuntimeError, fig.savefig, 'junk.png') 
Example #9
Source File: live_chart_utils.py    From catalyst with Apache License 2.0 6 votes vote down vote up
def format_ax(ax):
    """
    Trying to assign reasonable parameters to the time axis.

    Parameters
    ----------
    ax:

    """
    # TODO: room for improvement
    ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))
    ax.xaxis.set_major_formatter(fmt)

    locator = mdates.HourLocator(interval=4)
    locator.MAXTICKS = 5000
    ax.xaxis.set_minor_locator(locator)

    datemin = pd.Timestamp.utcnow()
    ax.set_xlim(datemin)

    ax.grid(True) 
Example #10
Source File: test_dates.py    From neural-network-animation with MIT License 6 votes vote down vote up
def test_too_many_date_ticks():
    # Attempt to test SF 2715172, see
    # https://sourceforge.net/tracker/?func=detail&aid=2715172&group_id=80706&atid=560720
    # setting equal datetimes triggers and expander call in
    # transforms.nonsingular which results in too many ticks in the
    # DayLocator.  This should trigger a Locator.MAXTICKS RuntimeError
    warnings.filterwarnings(
        'ignore',
        'Attempting to set identical left==right results\\nin singular '
        'transformations; automatically expanding.\\nleft=\d*\.\d*, '
        'right=\d*\.\d*',
        UserWarning, module='matplotlib.axes')
    t0 = datetime.datetime(2000, 1, 20)
    tf = datetime.datetime(2000, 1, 20)
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.set_xlim((t0, tf), auto=True)
    ax.plot([], [])
    ax.xaxis.set_major_locator(mdates.DayLocator())
    assert_raises(RuntimeError, fig.savefig, 'junk.png') 
Example #11
Source File: PriceTradeAnalyzer.py    From Stock-Price-Trade-Analyzer with GNU General Public License v3.0 5 votes vote down vote up
def PlotScalerDateAdjust(minDate:datetime, maxDate:datetime, ax):
	if type(minDate)==str:
		daysInGraph = DateDiffDays(minDate,maxDate)
	else:
		daysInGraph = (maxDate-minDate).days
	if daysInGraph >= 365*3:
		majorlocator =  mdates.YearLocator()
		minorLocator = mdates.MonthLocator()
		majorFormatter = mdates.DateFormatter('%m/%d/%Y')
	elif daysInGraph >= 365:
		majorlocator =  mdates.MonthLocator()
		minorLocator = mdates.WeekdayLocator()
		majorFormatter = mdates.DateFormatter('%m/%d/%Y')
	elif daysInGraph < 90:
		majorlocator =  mdates.DayLocator()
		minorLocator = mdates.DayLocator()
		majorFormatter =  mdates.DateFormatter('%m/%d/%Y')
	else:
		majorlocator =  mdates.WeekdayLocator()
		minorLocator = mdates.DayLocator()
		majorFormatter =  mdates.DateFormatter('%m/%d/%Y')
	ax.xaxis.set_major_locator(majorlocator)
	ax.xaxis.set_major_formatter(majorFormatter)
	ax.xaxis.set_minor_locator(minorLocator)
	#ax.xaxis.set_minor_formatter(daysFmt)
	ax.set_xlim(minDate, maxDate) 
Example #12
Source File: test_dates.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_RRuleLocator_dayrange():
    loc = mdates.DayLocator()
    x1 = datetime.datetime(year=1, month=1, day=1, tzinfo=mdates.UTC)
    y1 = datetime.datetime(year=1, month=1, day=16, tzinfo=mdates.UTC)
    loc.tick_values(x1, y1)
    # On success, no overflow error shall be thrown 
Example #13
Source File: test_dates.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_DayLocator():
    with pytest.raises(ValueError):
        mdates.DayLocator(interval=-1)
    with pytest.raises(ValueError):
        mdates.DayLocator(interval=-1.5)
    with pytest.raises(ValueError):
        mdates.DayLocator(interval=0)
    with pytest.raises(ValueError):
        mdates.DayLocator(interval=1.3)
    mdates.DayLocator(interval=1.0) 
Example #14
Source File: test_dates.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_DayLocator():
    with pytest.raises(ValueError):
        mdates.DayLocator(interval=-1)
    with pytest.raises(ValueError):
        mdates.DayLocator(interval=-1.5)
    with pytest.raises(ValueError):
        mdates.DayLocator(interval=0)
    with pytest.raises(ValueError):
        mdates.DayLocator(interval=1.3)
    mdates.DayLocator(interval=1.0) 
Example #15
Source File: test_dates.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_RRuleLocator_dayrange():
    loc = mdates.DayLocator()
    x1 = datetime.datetime(year=1, month=1, day=1, tzinfo=mdates.UTC)
    y1 = datetime.datetime(year=1, month=1, day=16, tzinfo=mdates.UTC)
    loc.tick_values(x1, y1)
    # On success, no overflow error shall be thrown 
Example #16
Source File: test_dates.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_RRuleLocator_dayrange():
    loc = mdates.DayLocator()
    x1 = datetime.datetime(year=1, month=1, day=1, tzinfo=pytz.UTC)
    y1 = datetime.datetime(year=1, month=1, day=16, tzinfo=pytz.UTC)
    loc.tick_values(x1, y1)
    # On success, no overflow error shall be thrown 
Example #17
Source File: test_dates.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_DayLocator():
    with pytest.raises(ValueError):
        mdates.DayLocator(interval=-1)
    with pytest.raises(ValueError):
        mdates.DayLocator(interval=-1.5)
    with pytest.raises(ValueError):
        mdates.DayLocator(interval=0)
    with pytest.raises(ValueError):
        mdates.DayLocator(interval=1.3)
    mdates.DayLocator(interval=1.0) 
Example #18
Source File: chart.py    From XQuant with MIT License 4 votes vote down vote up
def _make_chart(df, chartfn, **kwargs):
    fig = plt.figure()
    ax1 = plt.subplot2grid((6, 4), (1, 0), rowspan=4, colspan=4)
    ax1.grid(True)
    plt.ylabel('Price')
    plt.setp(plt.gca().get_xticklabels(), visible=False)
    chartfn(df, ax1)
    if 'lines' in kwargs:
        _plot_lines(kwargs['lines'])
    if 'band' in kwargs:
        _plot_band(kwargs['band'])
    if 'events' in kwargs:
        _plot_events(kwargs['events'])

    ax2 = plt.subplot2grid((6, 4), (5, 0), sharex=ax1, rowspan=1, colspan=4)
    volume = df['volume']
    pos = df['open'] - df['close'] <= 0  # mask
    neg = df['open'] - df['close'] > 0
    ax2.bar(volume[pos].index, volume[pos], color='red', width=0.4, align='center', alpha=0.5)
    ax2.bar(volume[neg].index, volume[neg], color='green', width=0.4, align='center', alpha=0.5)
    # ax2.bar(df.index, df.loc[:, 'volume'],align='center')
    ax2.xaxis.set_major_locator(mticker.MaxNLocator(12))
    ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    if len(df.index) <= 500:
        ax2.xaxis.set_minor_locator(mdates.DayLocator())
    ax2.yaxis.set_ticklabels([])
    ax2.grid(True)
    plt.ylabel('Volume')
    plt.xlabel('DateTime')
    plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
    ax3 = plt.subplot2grid((6, 4), (0, 0), sharex=ax1, rowspan=1, colspan=4)
    if 'tracks' in kwargs:
        _plot_tracks(kwargs['tracks'])
    ax3.yaxis.set_ticklabels([])
    # ax3.yaxis.tick_right()
    ax3.grid(True)
    ax3.xaxis.set_visible(False)
    ax3.set_ylabel('Observe')
    plt.subplots_adjust(left=.09, bottom=.18, right=.94, top=0.94, wspace=.20, hspace=0)
    if 'title' in kwargs:
        plt.suptitle(kwargs['title'])
    if 'fname' in kwargs:
        plt.savefig(kwargs['fname'], bbox_inches='tight')
    plt.show()
    # plt.close() 
Example #19
Source File: plot.py    From PGPortfolio with GNU General Public License v3.0 4 votes vote down vote up
def plot_backtest(config, algos, labels=None):
    """
    @:param config: config dictionary
    @:param algos: list of strings representing the name of algorithms or index of pgportfolio result
    """
    results = []
    for i, algo in enumerate(algos):
        if algo.isdigit():
            results.append(np.cumprod(_load_from_summary(algo, config)))
            logging.info("load index "+algo+" from csv file")
        else:
            logging.info("start executing "+algo)
            results.append(np.cumprod(execute_backtest(algo, config)))
            logging.info("finish executing "+algo)

    start, end = _extract_test(config)
    timestamps = np.linspace(start, end, len(results[0]))
    dates = [datetime.datetime.fromtimestamp(int(ts)-int(ts)%config["input"]["global_period"])
             for ts in timestamps]

    weeks = mdates.WeekdayLocator()
    days = mdates.DayLocator()

    rc("font", **{"family": "sans-serif", "sans-serif": ["Helvetica"],
                  "size": 8})

    """
    styles = [("-", None), ("--", None), ("", "+"), (":", None),
              ("", "o"), ("", "v"), ("", "*")]
    """
    fig, ax = plt.subplots()
    fig.set_size_inches(9, 5)
    for i, pvs in enumerate(results):
        if len(labels) > i:
            label = labels[i]
        else:
            label = NAMES[algos[i]]
        ax.semilogy(dates, pvs, linewidth=1, label=label)
        #ax.plot(dates, pvs, linewidth=1, label=label)

    plt.ylabel("portfolio value $p_t/p_0$", fontsize=12)
    plt.xlabel("time", fontsize=12)
    xfmt = mdates.DateFormatter("%m-%d %H:%M")
    ax.xaxis.set_major_locator(weeks)
    ax.xaxis.set_minor_locator(days)
    datemin = dates[0]
    datemax = dates[-1]
    ax.set_xlim(datemin, datemax)

    ax.xaxis.set_major_formatter(xfmt)
    plt.grid(True)
    plt.tight_layout()
    ax.legend(loc="upper left", prop={"size":10})
    fig.autofmt_xdate()
    plt.savefig("result.eps", bbox_inches='tight',
                pad_inches=0)
    plt.show() 
Example #20
Source File: rendering.py    From simglucose with MIT License 4 votes vote down vote up
def initialize(self):
        plt.ion()
        fig, axes = plt.subplots(4)

        axes[0].set_ylabel('BG (mg/dL)')
        axes[1].set_ylabel('CHO (g/min)')
        axes[2].set_ylabel('Insulin (U/min)')
        axes[3].set_ylabel('Risk Index')

        lineBG, = axes[0].plot([], [], label='BG')
        lineCGM, = axes[0].plot([], [], label='CGM')
        lineCHO, = axes[1].plot([], [], label='CHO')
        lineIns, = axes[2].plot([], [], label='Insulin')
        lineLBGI, = axes[3].plot([], [], label='Hypo Risk')
        lineHBGI, = axes[3].plot([], [], label='Hyper Risk')
        lineRI, = axes[3].plot([], [], label='Risk Index')

        lines = [lineBG, lineCGM, lineCHO, lineIns, lineLBGI, lineHBGI, lineRI]

        axes[0].set_ylim([70, 180])
        axes[1].set_ylim([-5, 30])
        axes[2].set_ylim([-0.5, 1])
        axes[3].set_ylim([0, 5])

        for ax in axes:
            ax.set_xlim(
                [self.start_time, self.start_time + timedelta(hours=3)])
            ax.legend()

        # Plot zone patches
        axes[0].axhspan(70, 180, alpha=0.3, color='limegreen', lw=0)
        axes[0].axhspan(50, 70, alpha=0.3, color='red', lw=0)
        axes[0].axhspan(0, 50, alpha=0.3, color='darkred', lw=0)
        axes[0].axhspan(180, 250, alpha=0.3, color='red', lw=0)
        axes[0].axhspan(250, 1000, alpha=0.3, color='darkred', lw=0)

        axes[0].tick_params(labelbottom=False)
        axes[1].tick_params(labelbottom=False)
        axes[2].tick_params(labelbottom=False)
        axes[3].xaxis.set_minor_locator(mdates.AutoDateLocator())
        axes[3].xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M\n'))
        axes[3].xaxis.set_major_locator(mdates.DayLocator())
        axes[3].xaxis.set_major_formatter(mdates.DateFormatter('\n%b %d'))

        axes[0].set_title(self.patient_name)

        return fig, axes, lines 
Example #21
Source File: viz.py    From py-openaq with MIT License 4 votes vote down vote up
def tsindex(ax):
    """
        Reset the axis parameters to look nice!
    """
    # Get dt in days
    dt = ax.get_xlim()[-1] - ax.get_xlim()[0]

    if dt <= 1./24.:   # less than one hour
        pass
    elif dt <= 1.:     # less than one day
        ax.xaxis.set_minor_locator( dates.HourLocator() )
        ax.xaxis.set_minor_formatter( dates.DateFormatter(""))

        ax.xaxis.set_major_locator( dates.HourLocator( interval=3))
        ax.xaxis.set_major_formatter( dates.DateFormatter("%-I %p"))
    elif dt <= 7.:      # less than one week
        ax.xaxis.set_minor_locator( dates.DayLocator())
        ax.xaxis.set_minor_formatter( dates.DateFormatter("%d"))

        ax.xaxis.set_major_locator( dates.DayLocator( bymonthday=[1, 8, 15, 22]) )
        ax.xaxis.set_major_formatter( dates.DateFormatter("\n%b\n%Y") )
    elif dt <= 14.:     # less than two weeks
        ax.xaxis.set_minor_locator( dates.DayLocator())
        ax.xaxis.set_minor_formatter( dates.DateFormatter("%d"))

        ax.xaxis.set_major_locator( dates.DayLocator( bymonthday=[1, 15]) )
        ax.xaxis.set_major_formatter( dates.DateFormatter("\n%b\n%Y") )
    elif dt <= 28.:     # less than four weeks
        ax.xaxis.set_minor_locator( dates.DayLocator())
        ax.xaxis.set_minor_formatter( dates.DateFormatter("%d"))

        ax.xaxis.set_major_locator( dates.MonthLocator() )
        ax.xaxis.set_major_formatter( dates.DateFormatter("\n%b\n%Y") )
    elif dt <= 4 * 30.: # less than four months
        ax.xaxis.set_minor_locator( dates.DayLocator( bymonthday=[1, 7, 14, 21] ))
        ax.xaxis.set_minor_formatter( dates.DateFormatter("%d"))

        ax.xaxis.set_major_locator( dates.MonthLocator())
        ax.xaxis.set_major_formatter( dates.DateFormatter("\n%b\n%Y") )
    else:
        ax.xaxis.set_minor_locator( dates.MonthLocator(interval=2) )
        ax.xaxis.set_minor_formatter( dates.DateFormatter("%b"))

        ax.xaxis.set_major_locator( dates.MonthLocator(bymonth=[1]) )
        ax.xaxis.set_major_formatter( dates.DateFormatter("\n%Y"))


    return ax