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


Python dates.num2date方法代碼示例

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


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

示例1: send_command

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import num2date [as 別名]
def send_command(self, ser,command,eol,hex=False):
            if hex:
                command = self.hexify_command(command,eol)
            else:
                command = eol+command+eol
            #print 'Command:  %s \n ' % command.replace(eol,'')
            sendtime = date2num(datetime.utcnow())
            #print "Sending"
            ser.write(command)
            #print "Received something - interpretation"
            response = self.lineread(ser,eol)
            #print "interprete", response
            receivetime = date2num(datetime.utcnow())
            meantime = np.mean([receivetime,sendtime])
            #print "Timediff", (receivetime-sendtime)*3600*24
            return response, num2date(meantime).replace(tzinfo=None) 
開發者ID:geomagpy,項目名稱:magpy,代碼行數:18,代碼來源:callprotocol.py

示例2: test_yearlocator_pytz

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import num2date [as 別名]
def test_yearlocator_pytz():
    import pytz

    tz = pytz.timezone('America/New_York')
    x = [tz.localize(datetime.datetime(2010, 1, 1))
            + datetime.timedelta(i) for i in range(2000)]
    locator = mdates.AutoDateLocator(interval_multiples=True, tz=tz)
    locator.create_dummy_axis()
    locator.set_view_interval(mdates.date2num(x[0])-1.0,
                              mdates.date2num(x[-1])+1.0)

    np.testing.assert_allclose([733408.208333, 733773.208333, 734138.208333,
                                734503.208333, 734869.208333,
                                735234.208333, 735599.208333], locator())
    expected = ['2009-01-01 00:00:00-05:00',
                '2010-01-01 00:00:00-05:00', '2011-01-01 00:00:00-05:00',
                '2012-01-01 00:00:00-05:00', '2013-01-01 00:00:00-05:00',
                '2014-01-01 00:00:00-05:00', '2015-01-01 00:00:00-05:00']
    st = list(map(str, mdates.num2date(locator(), tz=tz)))
    assert st == expected 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:22,代碼來源:test_dates.py

示例3: readGiopsIce

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import num2date [as 別名]
def readGiopsIce(lat,lon,datenum):
    di = 0            
    for datei in datenum:
        print datei 
        dt0= datetime.strptime(datei, "%Y-%m-%d %H:%M:%S")
        dt1 = mdates.date2num(dt0)
#        dt2 = mdates.num2date(dt1)
        
#        print dt0,dt2
#        taxis.append(dt1)        
        
        dayStr = str(dt0.year)+str(dt0.month).rjust(2,'0')+str(dt0.day).rjust(2,'0')
#        print dayStr
        
        ficePath = "/home/xuj/work/project/novaFloat/iceData/"
        
        fname = ficePath+"giops_"+dayStr+"00_ice.nc"
        
        cfile = Dataset(fname,'r')
        
        aice = np.squeeze(cfile.variables["aice"][0,:,:])
        
    

    return giopsIce 
開發者ID:DFO-Ocean-Navigator,項目名稱:Ocean-Data-Map-Project,代碼行數:27,代碼來源:usingFloat2extracCls4.py

示例4: adjust_xlim

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import num2date [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

示例5: test_drange

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import num2date [as 別名]
def test_drange():
    """
    This test should check if drange works as expected, and if all the
    rounding errors are fixed
    """
    start = datetime.datetime(2011, 1, 1, tzinfo=mdates.UTC)
    end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)
    delta = datetime.timedelta(hours=1)
    # We expect 24 values in drange(start, end, delta), because drange returns
    # dates from an half open interval [start, end)
    assert_equal(24, len(mdates.drange(start, end, delta)))

    # if end is a little bit later, we expect the range to contain one element
    # more
    end = end + datetime.timedelta(microseconds=1)
    assert_equal(25, len(mdates.drange(start, end, delta)))

    # reset end
    end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)

    # and tst drange with "complicated" floats:
    # 4 hours = 1/6 day, this is an "dangerous" float
    delta = datetime.timedelta(hours=4)
    daterange = mdates.drange(start, end, delta)
    assert_equal(6, len(daterange))
    assert_equal(mdates.num2date(daterange[-1]), end - delta) 
開發者ID:miloharper,項目名稱:neural-network-animation,代碼行數:28,代碼來源:test_dates.py

示例6: __call__

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import num2date [as 別名]
def __call__(self, x, pos=0):
        'Return the label for time x at position pos'
        ind = int(np.round(x))
        if ind >= len(self.dates) or ind < 0:
            return ''

        return num2date(self.dates[ind]).strftime(self.fmt) 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:9,代碼來源:date_index_formatter2.py

示例7: test_drange

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import num2date [as 別名]
def test_drange():
    """
    This test should check if drange works as expected, and if all the
    rounding errors are fixed
    """
    start = datetime.datetime(2011, 1, 1, tzinfo=mdates.UTC)
    end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)
    delta = datetime.timedelta(hours=1)
    # We expect 24 values in drange(start, end, delta), because drange returns
    # dates from an half open interval [start, end)
    assert len(mdates.drange(start, end, delta)) == 24

    # if end is a little bit later, we expect the range to contain one element
    # more
    end = end + datetime.timedelta(microseconds=1)
    assert len(mdates.drange(start, end, delta)) == 25

    # reset end
    end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)

    # and tst drange with "complicated" floats:
    # 4 hours = 1/6 day, this is an "dangerous" float
    delta = datetime.timedelta(hours=4)
    daterange = mdates.drange(start, end, delta)
    assert len(daterange) == 6
    assert mdates.num2date(daterange[-1]) == (end - delta) 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:28,代碼來源:test_dates.py

示例8: getTickDatetimeByXPosition

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import num2date [as 別名]
def getTickDatetimeByXPosition(self,xAxis):
        """mid
        根據傳入的x軸坐標值,返回其所代表的時間
        """
        tickDatetimeRet = xAxis
        minYearDatetimeNum = mpd.date2num(dt.datetime(1900,1,1))
        if(xAxis > minYearDatetimeNum):
            tickDatetime = mpd.num2date(xAxis).astimezone(pytz.timezone('utc'))
            if(tickDatetime.year >=1900):
                tickDatetimeRet = tickDatetime 
        return tickDatetimeRet 
開發者ID:zhengwsh,項目名稱:InplusTrader_Linux,代碼行數:13,代碼來源:monitor_tick_main.py

示例9: __getTickDatetimeByXPosition

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import num2date [as 別名]
def __getTickDatetimeByXPosition(self,xAxis):
        """mid
        默認計算方式,用datetimeNum標記x軸
        根據某個view中鼠標所在位置的x坐標獲取其所在tick的time,xAxis可以是index,也可是一datetime轉換而得到的datetimeNum
        return:str
        """        
        tickDatetimeRet = xAxis
        minYearDatetimeNum = mpd.date2num(dt.datetime(1900,1,1))
        if(xAxis > minYearDatetimeNum):
            tickDatetime = mpd.num2date(xAxis).astimezone(pytz.timezone('utc'))
            if(tickDatetime.year >=1900):
                tickDatetimeRet = tickDatetime 
        return tickDatetimeRet       
    
    #---------------------------------------------------------------------- 
開發者ID:zhengwsh,項目名稱:InplusTrader_Linux,代碼行數:17,代碼來源:uiCrosshair.py

示例10: plotYearly

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import num2date [as 別名]
def plotYearly(dictframe, ax, uncertainty, color='#0072B2'):

    if ax is None:
        figY = plt.figure(facecolor='w', figsize=(10, 6))
        ax = figY.add_subplot(111)
    else:
        figY = ax.get_figure()
    ##
    # Find the max index for an entry of each month
    ##
    months = dictframe.ds.dt.month
    ind = []
    for month in range(1,13):
        ind.append(max(months[months == month].index.tolist()))
    ##
    # Plot from the minimum of those maximums on (this will almost certainly result in only 1 year plotted)
    ##
    ax.plot(dictframe['ds'][min(ind):], dictframe['yearly'][min(ind):], ls='-', c=color)
    if uncertainty:
        ax.fill_between(dictframe['ds'].values[min(ind):], dictframe['yearly_lower'][min(ind):], dictframe['yearly_upper'][min(ind):], color=color, alpha=0.2)
    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
    months = MonthLocator(range(1, 13), bymonthday=1, interval=2)
    ax.xaxis.set_major_formatter(FuncFormatter(
        lambda x, pos=None: '{dt:%B} {dt.day}'.format(dt=num2date(x))))
    ax.xaxis.set_major_locator(months)
    ax.set_xlabel('Day of year')
    ax.set_ylabel('yearly')
    figY.tight_layout()
    return figY 
開發者ID:CollinRooney12,項目名稱:htsprophet,代碼行數:31,代碼來源:htsPlot.py

示例11: plot_date_bars

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import num2date [as 別名]
def plot_date_bars(bin_data, bin_edges, title, ylabel, fname):
    """
    Semi-generic function to plot a bar graph, x-label is fixed to "date" and the
    x-ticks are formatted accordingly.

    To plot a histogram, the histogram data must be calculated manually outside
    this function, either manually or using :py:func`numpy.histogram`.

    :param bin_data: list of data for each bin
    :param bin_edges: list of bin edges (:py:class:`datetime.date` objects), its
                      length must be ``len(data)+1``
    :param title: title of the plot
    :param ylabel: label of y-axis
    :param fname: output file name
    """
    import matplotlib.pyplot as plt
    from matplotlib.dates import date2num, num2date
    from matplotlib import ticker

    plt.figure()  # clear previous figure
    plt.title(title)
    plt.xlabel("date")
    plt.ylabel(ylabel)

    # plot the bars, width of the bins is assumed to be fixed
    plt.bar(date2num(bin_edges[:-1]), bin_data, width=date2num(bin_edges[1]) - date2num(bin_edges[0]))

    # x-ticks formatting
    plt.gca().xaxis.set_major_formatter(ticker.FuncFormatter(lambda numdate, _: num2date(numdate).strftime('%Y-%m-%d')))
    plt.gcf().autofmt_xdate()
    plt.tick_params(axis="x", which="both", direction="out")
    plt.xticks([date2num(ts) for ts in bin_edges if ts.month % 12 == 1])

    plt.savefig(fname, papertype="a4") 
開發者ID:lahwaacz,項目名稱:wiki-scripts,代碼行數:36,代碼來源:statistics_histograms.py

示例12: main

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import num2date [as 別名]
def main(args):
    _, fetch = load_dataset(SP500, shuffle=False)
    dates, returns = fetch()
    init_rng_key, sample_rng_key = random.split(random.PRNGKey(args.rng_seed))
    model_info = initialize_model(init_rng_key, model, model_args=(returns,))
    init_kernel, sample_kernel = hmc(model_info.potential_fn, algo='NUTS')
    hmc_state = init_kernel(model_info.param_info, args.num_warmup, rng_key=sample_rng_key)
    hmc_states = fori_collect(args.num_warmup, args.num_warmup + args.num_samples, sample_kernel, hmc_state,
                              transform=lambda hmc_state: model_info.postprocess_fn(hmc_state.z),
                              progbar=False if "NUMPYRO_SPHINXBUILD" in os.environ else True)
    print_results(hmc_states, dates)

    fig, ax = plt.subplots(1, 1)
    dates = mdates.num2date(mdates.datestr2num(dates))
    ax.plot(dates, returns, lw=0.5)
    # format the ticks
    ax.xaxis.set_major_locator(mdates.YearLocator())
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    ax.xaxis.set_minor_locator(mdates.MonthLocator())

    ax.plot(dates, jnp.exp(hmc_states['s'].T), 'r', alpha=0.01)
    legend = ax.legend(['returns', 'volatility'], loc='upper right')
    legend.legendHandles[1].set_alpha(0.6)
    ax.set(xlabel='time', ylabel='returns', title='Volatility of S&P500 over time')

    plt.savefig("stochastic_volatility_plot.pdf")
    plt.tight_layout() 
開發者ID:pyro-ppl,項目名稱:numpyro,代碼行數:29,代碼來源:stochastic_volatility.py

示例13: ploteasy

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import num2date [as 別名]
def ploteasy(stream):
    '''
    DEFINITION:
        Plots all data in stream. That's it.
        This function has no formatting options whatsoever.
        Very useful for quick & easy data evaluation.

    PARAMETERS:
    Variables:
        - stream:       (DataStream object) Stream to plot

    RETURNS:
        - plot:         (Pyplot plot) Returns plot as plt.show()

    EXAMPLE:
        >>> ploteasy(somedata)
    '''

    keys = stream._get_key_headers(numerical=True)
    if len(keys) > 9:
        keys = keys[:8]
    try:
        sensorid = stream.header['SensorID']
    except:
        sensorid = ''
    try:
        datadate = datetime.strftime(num2date(stream[0].time),'%Y-%m-%d')
    except:
        datadate = datetime.strftime(num2date(stream.ndarray[0][0]),'%Y-%m-%d')

    plottitle = "%s (%s)" % (sensorid,datadate)
    logger.info("Plotting keys:", keys)
    plot_new(stream, keys,
                confinex = True,
                plottitle = plottitle)

#####################################################################
#                                                                   #
#       MAIN PLOTTING FUNCTIONS                                     #
#       (for plotting geomagnetic data)                             #
#                                                                   #
##################################################################### 
開發者ID:geomagpy,項目名稱:magpy,代碼行數:44,代碼來源:mpplot.py

示例14: interpHovmoller

# 需要導入模塊: from matplotlib import dates [as 別名]
# 或者: from matplotlib.dates import num2date [as 別名]
def interpHovmoller(self,target_track,window=4,align='backward'):
        r"""
        Creates storm-centered interpolated data in polar coordinates for each timestep, and averages azimuthally to create a hovmoller.
        
        target_track = dict
            dict of either archer or hurdat data (contains lat, lon, time/date)
        window = hours
            sets window in hours relative to the time of center pass for interpolation use.
        """
    
        #Store the dataframe containing recon data
        tmpRecon = self.dfRecon.copy()
        #Sets window as a timedelta object
        window = timedelta(seconds=int(window*3600))
        
        #Error check for time dimension name
        if 'time' not in target_track.keys():
            target_track['time']=target_track['date']
        
        #Find times of all center passes
        centerTimes = tmpRecon[tmpRecon['iscenter']==1]['time']
        
        #Data is already centered on center time, so shift centerTimes to the end of the window
        spaceInterpTimes = [t+window/2 for t in centerTimes]
        
        #Takes all times within track dictionary that fall between spaceInterpTimes
        trackTimes = [t for t in target_track['time'] if min(spaceInterpTimes)<t<max(spaceInterpTimes)]
        
        #Iterate through all data surrounding a center pass given the window previously specified, and create a polar
        #grid for each
        start_time = dt.now()
        print("--> Starting interpolation")
        
        spaceInterpData={}
        for time in spaceInterpTimes:
            #Temporarily set dfRecon to this centered subset window
            self.dfRecon = tmpRecon[(tmpRecon['time']>time-window) & (tmpRecon['time']<=time)]
            print(time)
            grid_rho, grid_phi, grid_z_pol = self.interpPol() #Create polar centered grid
            grid_azim_mean = np.mean(grid_z_pol,axis=0) #Average azimuthally
            spaceInterpData[time] = grid_azim_mean #Append data for this time step to dictionary
        
        #Sets dfRecon back to original full data
        self.dfRecon = tmpRecon
        reconArray = np.array([i for i in spaceInterpData.values()])

        #Interpolate over every half hour
        newTimes = np.arange(mdates.date2num(trackTimes[0]),mdates.date2num(trackTimes[-1])+1e-3,1/48)    
        oldTimes = mdates.date2num(spaceInterpTimes)
        reconTimeInterp=np.apply_along_axis(lambda x: np.interp(newTimes,oldTimes,x),
                                 axis=0,arr=reconArray)
        time_elapsed = dt.now() - start_time
        tsec = str(round(time_elapsed.total_seconds(),2))
        print(f"--> Completed interpolation ({tsec} seconds)")
        
        #Output RMW and hovmoller data and store as an attribute in the object
        self.rmw = grid_rho[0,np.nanargmax(reconTimeInterp,axis=1)]
        self.Hovmoller = {'time':mdates.num2date(newTimes),'radius':grid_rho[0,:],'hovmoller':reconTimeInterp}
        return self.Hovmoller 
開發者ID:tropycal,項目名稱:tropycal,代碼行數:61,代碼來源:tools.py


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