Python matplotlib.dates.num2date() Examples
The following are 18
code examples of matplotlib.dates.num2date().
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: rendering.py From simglucose with MIT License | 6 votes |
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 #2
Source File: test_dates.py From coffeegrindsize with MIT License | 6 votes |
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
Example #3
Source File: test_dates.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #4
Source File: usingFloat2extracCls4.py From Ocean-Data-Map-Project with GNU General Public License v3.0 | 6 votes |
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
Example #5
Source File: callprotocol.py From magpy with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #6
Source File: statistics_histograms.py From wiki-scripts with GNU General Public License v3.0 | 5 votes |
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")
Example #7
Source File: test_dates.py From twitter-stock-recommendation with MIT License | 5 votes |
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)
Example #8
Source File: test_dates.py From coffeegrindsize with MIT License | 5 votes |
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)
Example #9
Source File: stochastic_volatility.py From numpyro with Apache License 2.0 | 5 votes |
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()
Example #10
Source File: test_dates.py From ImageFusion with MIT License | 5 votes |
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)
Example #11
Source File: htsPlot.py From htsprophet with MIT License | 5 votes |
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
Example #12
Source File: uiCrosshair.py From InplusTrader_Linux with MIT License | 5 votes |
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 #----------------------------------------------------------------------
Example #13
Source File: monitor_tick_main.py From InplusTrader_Linux with MIT License | 5 votes |
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
Example #14
Source File: test_dates.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #15
Source File: date_index_formatter2.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #16
Source File: test_dates.py From neural-network-animation with MIT License | 5 votes |
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)
Example #17
Source File: tools.py From tropycal with MIT License | 4 votes |
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
Example #18
Source File: mpplot.py From magpy with BSD 3-Clause "New" or "Revised" License | 4 votes |
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) # # # #####################################################################