当前位置: 首页>>代码示例>>Python>>正文


Python dates.DateFormatter方法代码示例

本文整理汇总了Python中matplotlib.dates.DateFormatter方法的典型用法代码示例。如果您正苦于以下问题:Python dates.DateFormatter方法的具体用法?Python dates.DateFormatter怎么用?Python dates.DateFormatter使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.dates的用法示例。


在下文中一共展示了dates.DateFormatter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: plot_timeseries

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import DateFormatter [as 别名]
def plot_timeseries(DF, ax, name, startDate, stopDate, ylim=False):
    """
    plots timeseries graphs
    """
  
    # original time series
    ax.plot(DF[name],color='#1f77b4')
    ax.set_ylabel(name)
    ax.set_ylim(ylim)
    ax.set_xlim(pd.datetime.strptime(startDate,'%Y-%m-%d'),\
                pd.datetime.strptime(stopDate,'%Y-%m-%d'))

    # boxcar average
    ax.plot(DF[name].rolling(180).mean(),color='red')

    # make the dates exact
    ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d') 
开发者ID:samsammurphy,项目名称:ee-atmcorr-timeseries,代码行数:19,代码来源:plots.py

示例2: test_DateFormatter

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import DateFormatter [as 别名]
def test_DateFormatter():
    import matplotlib.testing.jpl_units as units
    units.register()

    # Lets make sure that DateFormatter will allow us to have tick marks
    # at intervals of fractional seconds.

    t0 = datetime.datetime(2001, 1, 1, 0, 0, 0)
    tf = datetime.datetime(2001, 1, 1, 0, 0, 1)

    fig = plt.figure()
    ax = plt.subplot(111)
    ax.set_autoscale_on(True)
    ax.plot([t0, tf], [0.0, 1.0], marker='o')

    # rrule = mpldates.rrulewrapper( dateutil.rrule.YEARLY, interval=500 )
    # locator = mpldates.RRuleLocator( rrule )
    # ax.xaxis.set_major_locator( locator )
    # ax.xaxis.set_major_formatter( mpldates.AutoDateFormatter(locator) )

    ax.autoscale_view()
    fig.autofmt_xdate() 
开发者ID:miloharper,项目名称:neural-network-animation,代码行数:24,代码来源:test_dates.py

示例3: test_empty_date_with_year_formatter

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import DateFormatter [as 别名]
def test_empty_date_with_year_formatter():
    # exposes sf bug 2861426:
    # https://sourceforge.net/tracker/?func=detail&aid=2861426&group_id=80706&atid=560720

    # update: I am no longer believe this is a bug, as I commented on
    # the tracker.  The question is now: what to do with this test

    import matplotlib.dates as dates

    fig = plt.figure()
    ax = fig.add_subplot(111)

    yearFmt = dates.DateFormatter('%Y')
    ax.xaxis.set_major_formatter(yearFmt)

    with tempfile.TemporaryFile() as fh:
        assert_raises(ValueError, fig.savefig, fh) 
开发者ID:miloharper,项目名称:neural-network-animation,代码行数:19,代码来源:test_dates.py

示例4: test_empty_date_with_year_formatter

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import DateFormatter [as 别名]
def test_empty_date_with_year_formatter():
    # exposes sf bug 2861426:
    # https://sourceforge.net/tracker/?func=detail&aid=2861426&group_id=80706&atid=560720

    # update: I am no longer believe this is a bug, as I commented on
    # the tracker.  The question is now: what to do with this test

    import matplotlib.dates as dates

    fig = plt.figure()
    ax = fig.add_subplot(111)

    yearFmt = dates.DateFormatter('%Y')
    ax.xaxis.set_major_formatter(yearFmt)

    with tempfile.TemporaryFile() as fh:
        with pytest.raises(ValueError):
            fig.savefig(fh) 
开发者ID:holzschu,项目名称:python3_ios,代码行数:20,代码来源:test_dates.py

示例5: graphRawFX

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import DateFormatter [as 别名]
def graphRawFX():
    
    fig=plt.figure(figsize=(10,7))
    ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)
    ax1.plot(date,bid)
    ax1.plot(date,ask)
    
    #ax1.plot(date,((bid+ask)/2))
    #ax1.plot(date,percentChange(ask[0],ask),'r')
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
    #####
    plt.grid(True)
    for label in ax1.xaxis.get_ticklabels():
            label.set_rotation(45)
    plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)
    #######
    ax1_2 = ax1.twinx()
    #ax1_2.plot(date, (ask-bid))
    ax1_2.fill_between(date, 0, (ask-bid), facecolor='g',alpha=.3)
    #ax1_2.set_ylim(0, 3*ask.max())
    #######
    plt.subplots_adjust(bottom=.23)
    #plt.grid(True)
    plt.show() 
开发者ID:PythonProgramming,项目名称:Pattern-Recognition-for-Forex-Trading,代码行数:26,代码来源:machFX7.py

示例6: graphRawFX

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import DateFormatter [as 别名]
def graphRawFX():
    date,bid,ask = np.loadtxt('GBPUSD1d.txt', unpack=True,
                              delimiter=',',
                              converters={0:mdates.strpdate2num('%Y%m%d%H%M%S')})

    fig=plt.figure(figsize=(10,7))

    ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)
    ax1.plot(date,bid)
    ax1.plot(date,ask)

    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))

    for label in ax1.xaxis.get_ticklabels():
            label.set_rotation(45)
    plt.subplots_adjust(bottom=.23)
    plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)
    plt.grid(True)
    plt.show() 
开发者ID:PythonProgramming,项目名称:Pattern-Recognition-for-Forex-Trading,代码行数:21,代码来源:machFX2.py

示例7: graphRawFX

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import DateFormatter [as 别名]
def graphRawFX():
    
    fig=plt.figure(figsize=(10,7))
    ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)
    ax1.plot(date,bid)
    ax1.plot(date,ask)
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
    plt.grid(True)
    for label in ax1.xaxis.get_ticklabels():
            label.set_rotation(45)
    plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)
    ax1_2 = ax1.twinx()
    ax1_2.fill_between(date, 0, (ask-bid), facecolor='g',alpha=.3)

    plt.subplots_adjust(bottom=.23)
    plt.show() 
开发者ID:PythonProgramming,项目名称:Pattern-Recognition-for-Forex-Trading,代码行数:18,代码来源:machFX14.py

示例8: get_graph

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import DateFormatter [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

示例9: adjust_xlim

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import DateFormatter [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

示例10: ensemble_BG

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import DateFormatter [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

示例11: ensemblePlot

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import DateFormatter [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

示例12: matplotlib_locator_formatter

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import DateFormatter [as 别名]
def matplotlib_locator_formatter(timedelta, span=1):
    """
    Compute appropriate locator and formatter for renderers
    based on matplotlib, depending on designated time span.
    """
    from matplotlib.dates import date_ticker_factory, DateFormatter
    locator, formatter = date_ticker_factory(span)

    # http://pandas.pydata.org/pandas-docs/stable/timedeltas.html
    # https://stackoverflow.com/questions/16103238/pandas-timedelta-in-days
    is_macro = timedelta <= Timedelta(days=1)
    is_supermacro = timedelta <= Timedelta(minutes=5)

    if is_macro:
        #formatter = DateFormatter(fmt='%H:%M:%S.%f')
        formatter = DateFormatter(fmt='%H:%M')

    if is_supermacro:
        formatter = DateFormatter(fmt='%H:%M:%S')

        # Formatter overrides
        #if formatter.fmt == '%H:%M\n%b %d':
        #    formatter = DateFormatter(fmt='%Y-%m-%d %H:%M')

    # Labs
    #from matplotlib.dates import AutoDateLocator, AutoDateFormatter, HOURLY
    #locator = AutoDateLocator(maxticks=7)
    #locator.autoscale()
    #locator.intervald[HOURLY] = [5]
    #formatter = AutoDateFormatter(breaks)
    #formatter = date_format('%Y-%m-%d\n%H:%M')

    # Default building blocks
    #from matplotlib.dates import AutoDateFormatter, AutoDateLocator
    #locator = AutoDateLocator()
    #formatter = AutoDateFormatter(locator)

    return locator, formatter 
开发者ID:daq-tools,项目名称:kotori,代码行数:40,代码来源:util.py

示例13: __call__

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import DateFormatter [as 别名]
def __call__(self, x, pos=0):
        fmt = self._get_fmt(x)
        self._formatter = dates.DateFormatter(fmt, self._tz)
        return self._formatter(x, pos) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:6,代码来源:converter.py

示例14: plot_supply

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import DateFormatter [as 别名]
def plot_supply(request):
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.dates import DateFormatter
    currency = request.GET['currency']
    genesis = crypto_data[currency.lower()]['genesis_date']
    currency_name = crypto_data[currency.lower()]['name']
    s = SupplyEstimator(currency)

    try:
        max_block = crypto_data[currency.lower()]['supply_data']['reward_ends_at_block']
        end = s.estimate_date_from_height(max_block)
    except KeyError:
        end = genesis + datetime.timedelta(days=365 * 50)

    x = list(date_generator(genesis, end))
    y = [s.calculate_supply(at_time=z)/1e6 for z in x]

    fig = Figure()
    ax = fig.add_subplot(111)
    ax.plot_date(x, y, '-')

    ax.set_title("%s Supply" % currency_name)
    ax.grid(True)
    ax.xaxis.set_label_text("Date")
    ax.yaxis.set_label_text("%s Units (In millions)" % currency.upper())

    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    fig.autofmt_xdate()

    canvas = FigureCanvas(fig)
    response = http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response 
开发者ID:priestc,项目名称:MultiExplorer,代码行数:36,代码来源:views.py

示例15: plotTimeline

# 需要导入模块: from matplotlib import dates [as 别名]
# 或者: from matplotlib.dates import DateFormatter [as 别名]
def plotTimeline(dataTask, filename):
    """Build a timeline"""

    fig = plt.figure()
    ax = fig.gca()

    worker_names = [x for x in dataTask.keys() if "broker" not in x]

    min_time = getMinimumTime(dataTask)
    ystep = 1. / (len(worker_names) + 1)

    y = 0
    for worker, vals in dataTask.items():
        if "broker" in worker:
            continue
        y += ystep
        if hasattr(vals, 'values'):
            for future in vals.values():
                start_time = [future['start_time'][0] - min_time]
                end_time = [future['end_time'][0] - min_time]
                timelines(ax, y, start_time, end_time)

    #ax.xaxis_date()
    #myFmt = DateFormatter('%H:%M:%S')
    #ax.xaxis.set_major_formatter(myFmt)
    #ax.xaxis.set_major_locator(SecondLocator(0, interval=20))

    #delta = (stop.max() - start.min())/10
    ax.set_yticks(np.arange(ystep, 1, ystep))
    ax.set_yticklabels(worker_names)
    ax.set_ylim(0, 1)
    #fig.xlim()
    ax.set_xlabel('Time')
    fig.savefig(filename) 
开发者ID:soravux,项目名称:scoop,代码行数:36,代码来源:process_debug.py


注:本文中的matplotlib.dates.DateFormatter方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。