當前位置: 首頁>>代碼示例>>Python>>正文


Python dates.DayLocator方法代碼示例

本文整理匯總了Python中matplotlib.dates.DayLocator方法的典型用法代碼示例。如果您正苦於以下問題:Python dates.DayLocator方法的具體用法?Python dates.DayLocator怎麽用?Python dates.DayLocator使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在matplotlib.dates的用法示例。


在下文中一共展示了dates.DayLocator方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_too_many_date_ticks

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import DayLocator [as 別名]
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') 
開發者ID:miloharper,項目名稱:neural-network-animation,代碼行數:22,代碼來源:test_dates.py

示例2: test_too_many_date_ticks

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import DayLocator [as 別名]
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') 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:20,代碼來源:test_dates.py

示例3: format_ax

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import DayLocator [as 別名]
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) 
開發者ID:enigmampc,項目名稱:catalyst,代碼行數:23,代碼來源:live_chart_utils.py

示例4: get_graph

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import DayLocator [as 別名]
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) 
開發者ID:andrebrener,項目名稱:crypto_predictor,代碼行數:18,代碼來源:get_coin_data.py

示例5: adjust_xlim

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import DayLocator [as 別名]
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')) 
開發者ID:jxx123,項目名稱:simglucose,代碼行數:25,代碼來源:rendering.py

示例6: ensemble_BG

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import DayLocator [as 別名]
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 
開發者ID:jxx123,項目名稱:simglucose,代碼行數:33,代碼來源:report.py

示例7: ensemblePlot

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import DayLocator [as 別名]
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 
開發者ID:jxx123,項目名稱:simglucose,代碼行數:27,代碼來源:report.py

示例8: test_RRuleLocator_dayrange

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import DayLocator [as 別名]
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 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:8,代碼來源:test_dates.py

示例9: test_DayLocator

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import DayLocator [as 別名]
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) 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:12,代碼來源:test_dates.py

示例10: PlotScalerDateAdjust

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import DayLocator [as 別名]
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) 
開發者ID:TimRivoli,項目名稱:Stock-Price-Trade-Analyzer,代碼行數:28,代碼來源:PriceTradeAnalyzer.py

示例11: test_RRuleLocator_dayrange

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import DayLocator [as 別名]
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 
開發者ID:alvarobartt,項目名稱:twitter-stock-recommendation,代碼行數:8,代碼來源:test_dates.py

示例12: tsindex

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import DayLocator [as 別名]
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 
開發者ID:dhhagan,項目名稱:py-openaq,代碼行數:50,代碼來源:viz.py

示例13: plot_backtest

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import DayLocator [as 別名]
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() 
開發者ID:ZhengyaoJiang,項目名稱:PGPortfolio,代碼行數:59,代碼來源:plot.py

示例14: _make_chart

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import DayLocator [as 別名]
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() 
開發者ID:X0Leon,項目名稱:XQuant,代碼行數:47,代碼來源:chart.py

示例15: initialize

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import DayLocator [as 別名]
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 
開發者ID:jxx123,項目名稱:simglucose,代碼行數:49,代碼來源:rendering.py


注:本文中的matplotlib.dates.DayLocator方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。