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)
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)
def main(): parser = argparse.ArgumentParser() # adding the arguments parser.add_argument( "-e", default=datetime.today().isoformat(timespec='hours')[:-3]) parser.add_argument("-t", default='1y') parser.add_argument("-i", default='^GDAXI') # Parse and print the results args = parser.parse_args() print(args) # compute timeframe if args.t == '1y': timeframe = timedelta(days=365) elif args.t == '5y': timeframe = timedelta(days=365 * 5) elif args.t == '10y': timeframe = timedelta(days=365 * 10) elif args.t == '6m': timeframe = timedelta(days=30 * 6) elif args.t == '3m': timeframe = timedelta(days=30 * 3) elif args.t == '1m': timeframe = timedelta(days=30) else: timeframe = timedelta(days=365) tickerSymbol = args.i end = args.e start = (datetime.fromisoformat(end) - timeframe).isoformat(timespec='hours')[:-3] # getting the financial data from yfinance tickerData = yf.Ticker(tickerSymbol) # selecting the correct timeperiod tickerDf = tickerData.history(period='1s', start=start, end=end) start = datetime.fromisoformat(start) end = datetime.fromisoformat(end) # plotting the data green if overall close goes up and red if down if tickerDf.iloc[0]['Close'] < tickerDf.iloc[-1]['Close']: plx.plot(drange(start, end, timedelta(days=1)), tickerDf['Close'], line_color='green') else: plx.plot(drange(start, end, timedelta(days=1)), tickerDf['Close'], line_color='red') plx.show()
def gen_data(date_current, type, precision): data_to_process = [] #debugging delta = datetime.timedelta(minutes=precision) #debugging if type == 'dayh': date_previous = date_current - datetime.timedelta(days=1) for item in drange(date_previous, date_current + datetime.timedelta(days=1), delta): #debugging data_to_process.append({ 'datetimestamp': num2date(item), 'Pactiva': 1 }) #debugging elif type == 'week': date_previous = (date_current - datetime.timedelta(days=7 + date_current.weekday())) for item in drange(date_previous, date_current + datetime.timedelta(days=1), delta): #debugging data_to_process.append({ 'datetimestamp': num2date(item), 'Pactiva': 1 }) #debugging elif type == 'month': if date_current.month < 2: date_previous = date_current.replace(year=date_current.year - 1, month=12, day=1) else: date_previous = date_current.replace(month=date_current.month - 1, day=1) for item in drange(date_previous, date_current + datetime.timedelta(days=1), delta): #debugging data_to_process.append({ 'datetimestamp': num2date(item), 'Pactiva': 1 }) #debugging elif type == 'year': date_previous = date_current.replace(year=date_current.year - 1, month=1, day=1) for item in drange(date_previous, date_current + datetime.timedelta(days=1), delta): #debugging data_to_process.append({ 'datetimestamp': num2date(item), 'Pactiva': 1 }) #debugging return data_to_process
def gen_time_seq(date_start_string, tstep, n_tstep, date_string_format = '%Y-%m-%d %H:%M' ) : """ Description. Parameters ---------- date_start_string : date from which to start the sequence in string format '%Y-%m-%d %H:%M', e.g. '2015-03-02 12:00'. tstep : length of time step in seconds. n_tstep : number of time steps date_string_format : date string format used in input file, see https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior Returns ------- dates_out : list of datetime objects Examples -------- # generate a sequence of 20 datetimes instances starting from 2015-03-02 12:00 at 1-minute-interval. >>> dates_out = gen_time_seq(date_start_string = '2015-03-02 12:00' ,tstep = 60 ,n_tstep = 20) """ # convert date_start_string to datetime format date_start = dt.datetime.strptime(date_start_string, date_string_format) # estimate date_end in datetime format date_end = date_start + dt.timedelta(seconds = tstep*n_tstep) # generate sequence of dates datenums_out = mdates.drange(date_start,date_end - dt.timedelta(seconds=0.001), dt.timedelta(seconds=tstep)) # convert to list of datetime dates_out = mdates.num2date(datenums_out) return(dates_out)
def print_data(time_series, start_date): date_range = mdates.drange(start_date, datetime.date.today(), datetime.timedelta(days=1)) #plt.plot_date(date_range, usa_data) #initial guess for curve fit coefficients guess = [300000, 0.1, 50] # coefficients and curve fit for curve xdata = np.arange(0, len(time_series)) popt, pcov = curve_fit(logistic_growth, xdata, time_series, p0=guess) print(f'Curve fit arguments: {popt}') xfuture = np.arange(175) ydata = logistic_growth(xdata, *popt) # Growth plt.plot(xdata, ydata) plt.plot(xdata, time_series) # derivatives plt.plot(xdata[:-1], np.diff(ydata)) plt.plot(xdata[:-1], np.diff(time_series)) # predictions plt.plot(xfuture, logistic_growth(xfuture, *popt)) plt.show()
def getFigure_DataAndRevisionData(shop_id, data_from, data_end): startDate = datetime.datetime(2015, 6, 1) endDate = datetime.datetime(2017, 1, 1) delta = datetime.timedelta(days=20) dates = drange(startDate, endDate, delta) fig = plt.figure(figsize=(15, 8)) view_ax = fig.add_subplot(1, 1, 1) plt.xlabel('date') plt.ylabel('view_counts') plt.xticks(dates) view_ax.set_xticklabels(dates, rotation=45, size=10) view_ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) dataOfShopid = getDataFromStartToEnd(pay_data, shop_id) dataReviseOfShopid = getDataFromStartToEnd(pay_revised_data, shop_id) view_ax.plot_date(dataOfShopid[0], dataOfShopid[1], 'c--', marker='.', linewidth=0.5) view_ax.plot_date(dataReviseOfShopid[0], dataReviseOfShopid[1], 'r--', marker='.', linewidth=0.5) return view_ax
def render_matplotlib_png(alert_router_id, points, start, end, step): """Render a graph PNG based on timeseries data using matplotlib. Args: alert_router_id: a alert_id-router_gid string points: timeseries traffic data points start: arrow object representing the start time of the alert end: arrow object reprsenting the end time of the alert step: the time period each entry in the timeseries data spans """ # every day days = DayLocator() # every hour hours = HourLocator(interval=9) delta = datetime.timedelta(seconds=step) # calculate x axis points based on step and start time dates = drange(start, end, delta) # using AGG fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(111) ax.plot_date(dates, points, '.-') ax.grid(True) ax.xaxis.set_major_locator(days) ax.xaxis.set_minor_locator(hours) ax.xaxis.set_major_formatter(DateFormatter('%a')) ax.xaxis.set_minor_formatter(DateFormatter('%H:%M')) ax.set_xlabel('time') ax.set_ylabel('bps') ax.set_title('Router Traffic - {}'.format(alert_router_id)) fig.autofmt_xdate() fig.savefig('{}.png'.format(alert_router_id))
def numPRMerged_graph(df): """This function will create a graph for Num of Pr merged""" # get oldest and youngest dates from the list datelist = df['dates'] oldest = min(datelist) youngest = max(datelist) timegap = 12 dates = mdates.drange(oldest, youngest, timedelta(weeks=timegap)) # data counts = df['counts'] # Set up the axes and figure fig, ax = plt.subplots() # (To use the exact code below, you'll need to convert your sequence # of datetimes into matplotlib's float-based date format. # Use "dates = mdates.date2num(dates)" to convert them.) dates = mdates.date2num(dates) width = np.diff(dates).min() # Make a bar plot. Note that I'm using "dates" directly instead of plotting # "counts" against x-values of [0,1,2...] ax.bar(datelist, counts.tolist(), align='center', width=width, ec='blue') # Tell matplotlib to interpret the x-axis values as dates ax.xaxis_date() # Make space for and rotate the x-axis tick labels fig.autofmt_xdate() plt.ylabel('Counts') plt.xlabel('Dates') plt.title('Number of PRs merged over time') plt.savefig('PRmergeRates.png', dpi=400) plt.show()
def locKumulativ(scaleFactor=1, filename="locKumulativ"): cursor.execute( "SELECT commits.date FROM commits ORDER BY date ASC LIMIT 1") firstDate = list(map(lambda x: x[0], cursor.fetchall()))[0] firstDate = datetime.fromisoformat(firstDate) dates = [firstDate.date()] cursor.execute( "SELECT commits.date,SUM(modification.loc_variation) from repository JOIN commits ON commits.repository_id == repository.id JOIN modification ON modification.commit_id == commits.id GROUP BY commits.date" ) dateLocvar = cursor.fetchall() dates = list(map(lambda x: datetime.fromisoformat(x[0]), dateLocvar)) locVar = list(map(lambda x: x[1], dateLocvar)) sum_dict = {} for i in range(len(dates)): date = dates[i].date() count = locVar[i] sum_dict[date] = sum_dict.get(date, 0) + count dates = num2date( drange( min(dates).date(), max(dates).date() + timedelta(1), timedelta(1))) sums = numpy.asarray( [sum_dict.get(d.date(), 0) / scaleFactor for d in dates]).cumsum() plt.step(dates, sums, alpha=1, label="LOC", linewidth=2) plt.grid(True) plt.xlabel('Zeit', fontsize=16) plt.ylabel('Lambdas / LOC', fontsize=16) plt.legend(title='Legende') plt.savefig("plots/3-data/" + filename + ".png", dpi=500, pad_inches=0)
def plot_accum(serie, data, real_data=True, ax=None, label="Modelo", blur=1.0, cor_serie="C0", cor_dados='C1x-', eng_fmt=True, legend=True, cut_day=None, loc=1): n_pts = len(serie) start = dt.datetime.strptime("29-03-2020", "%d-%m-%Y") then = start + dt.timedelta(days=n_pts) days = mdates.drange(start, then, dt.timedelta(days=1)) if ax == None: ax = plt.gca() ax.plot(days, serie, cor_serie, label=label, alpha=blur) if cut_day != None: new_cut_day = start + dt.timedelta(days=cut_day) ax.axvline(x=new_cut_day, color="grey", linestyle="--") if real_data: ax.plot(days, data, cor_dados, label="Dados") ax.grid() ax.set_xlabel("Dias") if eng_fmt: ax.yaxis.set_major_formatter(EngFormatter()) if legend: ax.legend(loc=loc) ax.xaxis.set_major_formatter(mdates.DateFormatter("%d/%m")) return
def rise_set2(): fig, ax = plt.subplots() x = np.linspace(0, 366, 366) y = 12 - azimuth(lat*torad, asin(sin(D*torad)*sin(w*x*torad)))/15 z = 12 + azimuth(lat*torad, asin(sin(D*torad)*sin(w*x*torad)))/15 now = dt.datetime.now() equinox = datetime(2020,3,20) then = equinox + dt.timedelta(days=366) days = mdates.drange(equinox,then,dt.timedelta(days=1)) #ax.text(0.0, 0.2, "Date", transform=ax.transAxes, # fontsize=14, fontname='Monospace', color='tab:blue') plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y')) #('%Y-%m-%d')) plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=15)) plt.plot(days,y, label='rise') plt.plot(days,z, label='set') #color = 'tab:blue' ax.set_ylabel('time (h)', fontsize=12, fontname='Monospace', color='tab:blue') ax.set_xlabel('Date', fontsize=12, fontname='Monospace', color='tab:blue') plt.legend() plt.gcf().autofmt_xdate() #ax.plot(x,y) #ax.plot(x,z) plt.title('Rise and set time') #ax.set_ylim(-25,25) plt.grid() #plt.axis("equal") plt.show()
def set_df(df, dt_start, dt_fim, municipios='all', skip=False, header=['Data', 'Municipio', 'Casos']): if municipios == 'all': municipios = set(df['Municipio']) else: if skip == True: municipios = set( df[~df['Municipio'].str.contains('|'.join(municipios))] ['Municipio']) else: municipios = set(df[df['Municipio'].str.contains( '|'.join(municipios))]['Municipio']) ## Configurando os dias dt_start = dt.datetime.strptime(dt_start, '%d-%m-%Y') dt_fim = dt.datetime.strptime(dt_fim, '%d-%m-%Y') days = mdates.drange(dt_start, dt_fim, dt.timedelta(days=1)) dt_start = dt.datetime.strftime(dt_start, '%d-%m-%Y') dt_fim = dt.datetime.strftime(dt_fim, '%d-%m-%Y') dates = [ dt.datetime.strftime(mdates.num2date(i), '%d-%m-%Y').replace('-', '/') for i in days ] ## Extraindo os dados e organizando em listas para o Dicionario casos = [] nome_m = [] data_m = [] for m in municipios: lst = [] lst_m = [m] * len(dates) lst_d = [] for d in dates: df = df[df['Municipio'] == m] lst.append(len(df[df['Data'] == d])) lst_d.append(d) nome_m.append(lst_m) casos.append(lst) data_m.append(lst_d) ## Criando o Dicionario lst = [[], [], []] for c, m, d in zip(casos, nome_m, data_m): lst[0] += d lst[1] += m lst[2] += c dic = {} for i, h in enumerate(header): dic.update({h: lst[i]}) ## Transformando o dicionario em DataFrame df = pd.DataFrame(dic) return df
def initPlot(self): """ redraw the canvas to set the initial x and y axes when plotting starts """ self.starttime = datetime.datetime.today() self.currenttime = self.starttime + datetime.timedelta(seconds=3) self.endtime = self.starttime + datetime.timedelta(seconds=15) self.timeaxis = num2date(drange(self.starttime, self.endtime, datetime.timedelta(milliseconds=10))) self.xvalues.append(self.timeaxis[0]) self.yvalues.append(self.parentPanel.myECG.ecg_leadII[0]) # for counter purposes only self.ybuffer = self.yvalues self.lines[0].set_data(self.xvalues, self.yvalues) self.axes.set_xlim((date2num(self.starttime), date2num(self.currenttime))) self.axes.xaxis.set_ticklabels( self.createXTickLabels(self.currenttime), rotation=30, ha="right", size="smaller", name="Calibri" ) self.samples_counter += 1 self.ysamples_counter += 1 self.buff_counter = 1
def generate_graph(): date1 = datetime.datetime( 2000, 3, 2) date2 = datetime.datetime( 2000, 3, 6) delta = datetime.timedelta(hours=6) dates = drange(date1, date2, delta) y = arange( len(dates)*1.0) fig, ax = pyplot.subplots() ax.plot_date(dates, y*y) ax.set_xlim( dates[0], dates[-1] ) ax.xaxis.set_major_locator( DayLocator() ) ax.xaxis.set_minor_locator( HourLocator(arange(0,25,6)) ) ax.xaxis.set_major_formatter( DateFormatter('%Y-%m-%d') ) ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S') fig.autofmt_xdate() file_name = str(generate_uuid()) + '.png' complete_file_name = GRAPHS_FOLDER + '/' + file_name logger.debug ("Generando grafico: " + file_name) pyplot.savefig( complete_file_name ) #pyplot.show() return [file_name,complete_file_name]
def reposPTime(filename="reposPTime"): cursor.execute("SELECT commits.date from commits") commitDates = cursor.fetchall() commitDates = list(map(lambda x: datetime.fromisoformat(x[0]), commitDates)) cursor.execute("SELECT repository.creation from repository") repoDates = cursor.fetchall() repoDates = list( map(lambda x: datetime.fromisoformat(x[0]).date(), repoDates)) dates = num2date( drange( min(commitDates).date(), max(commitDates).date() + timedelta(1), timedelta(1))) repo_dict = {} for i in range(len(dates)): date = dates[i].date() repo_dict[date] = len(list(filter(lambda x: x < date, repoDates))) repos = numpy.asarray([repo_dict.get(d.date(), 0) for d in dates]) plt.step(dates, repos, label="Anzahl Repositories") plt.legend(title='Anzahl Repositories', bbox_to_anchor=(0.05, 0.95), loc=2, borderaxespad=0.) plt.savefig("plots/3-data/" + filename + ".png", dpi=300)
def get_time_info(nc_file, current_utc_hour, tz_info): """ Retrieves time frame of plots starting at the current UTC hour and ending 3 days after the current hour. Parameters ---------- nc_file : object The netCDF dataset that provides the start time of data. current_utc_hour : float The current UTC hour. Returns ------- dates : list A list of Gregorian ordinals (floats) from the current UTC time to 3 days later """ #init_time = nc_file.variables["forc_time"][:][0] init_time = nc_file.variables["forc_time"][:] #print "init_time: ", init_time init_time = init_time + current_utc_hour * 3600 #begin_time = datetime.datetime.fromtimestamp(init_time, tz=tz_info) #end_time = datetime.datetime.fromtimestamp(init_time + (3*24*3600), tz=tz_info) # only plot 3 days begin_time = datetime.datetime.fromtimestamp(init_time) end_time = datetime.datetime.fromtimestamp(init_time + (3*24*3600)) # only plot 3 days #print "tz_info: ", tz_info #print "begin_time: ", begin_time #print "end_time: ", end_time delta = datetime.timedelta(hours=1) # Move time interval before all var arrays are set dates = drange(begin_time, end_time, delta) return dates
def draw(): from matplotlib.dates import DayLocator, HourLocator,MonthLocator ,WeekdayLocator, DateFormatter, drange from matplotlib.dates import MONDAY import datetime mondays = WeekdayLocator() days = DayLocator(None, 3) months = MonthLocator() yList = [0]*55 yList[0] = 0.11; yList[1] = 0.109; yList[2] = 0.108;yList[3] = 0.11; yList[4] = 0.111; yList[5] = 0.109; yList[6] = 0.111; yList[7] = 0.109; yList[8] = 0.108; yList[9] = 0.111; yList[10] = 0.112 figure, axes = plt.subplots() startDate = datetime.datetime(2014, 3, 6, 0, 0, 0) endDate = datetime.datetime(2014, 4, 30, 0, 0, 0) delta = datetime.timedelta(hours=24) dates = drange(startDate , endDate, delta) axes.plot_date(dates, yList, '-', marker='.', linewidth=1) axes.xaxis.set_major_locator(days) axes.xaxis.set_major_formatter( DateFormatter("%b '%d")) axes.xaxis.set_minor_locator(mondays) axes.fmt_xdata = DateFormatter("%b '%d") plt.ylim(0.08,0.20) plt.ylabel('播放率') axes.autoscale_view() axes.xaxis.grid(True, 'major') axes.xaxis.grid(True, 'minor') axes.grid(True) figure.autofmt_xdate() plt.show()
def run(self): """ start ECG plotting """ while not self.stopPlotThread.isSet(): self.parentFrame.ecgplotter.plot() # check if the thread has been stopped. if yes, no need to update endtime. if not self.stopPlotThread.isSet(): self.parentFrame.ecgplotter.endtime += datetime.timedelta(seconds=15) # initialize the time size (nagiiba kase after every 15 seconds. needs to be extended self.parentFrame.ecgplotter.timeaxis = num2date( drange( self.parentFrame.ecgplotter.starttime, self.parentFrame.ecgplotter.endtime, datetime.timedelta(milliseconds=10), ) ) else: break # add slider at the end of plotting only self.parentFrame.ecgplotter.addSlider(self.parentFrame.ecgplotter.endtime) self.parentFrame.ecgplotter.canvas.draw() self.parentFrame.ecgplotter.gui_repaint()
def plot_peaks_lockdown(dictagg, verzia_modelu, scen_vyber, legenda_vsetky_scenare, title, total_days, day_zero=dt.datetime.now() - dt.timedelta(days=0), SEIR=True): end = day_zero + dt.timedelta(days=total_days + 1) days = mdates.drange(day_zero, end, dt.timedelta(days=1)) months = mdates.MonthLocator() sns.set(rc={'figure.figsize': (11, 4)}) legenda = [legenda_vsetky_scenare[scen] for scen in scen_vyber] fig, ax = plt.subplots() clrs = ['red', 'purple', 'teal', 'blue', 'green', 'yellow', 'orange'] linest = '-' with sns.axes_style("darkgrid"): for scen in scen_vyber: if scen > 0: linest = '--' scenar = 'SIR_scenar' + str(scen) means = dictagg[scenar].inf p5 = dictagg[scenar].inf5 p95 = dictagg[scenar].inf95 if SEIR == True: means = means + dictagg[scenar].exp p5 = p5 + dictagg[scenar].exp5 p95 = p95 + dictagg[scenar].exp95 ax.plot(days, means, c=clrs[scen], linestyle=linest) ax.fill_between(days, p5, p95, alpha=0.3, facecolor=clrs[scen]) ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b' '%y')) plt.xticks(rotation=45) plt.title(title) plt.ylabel('Pomer nakazených') plt.legend(legenda) plt.tight_layout() plt.axvline(x=day_zero + dt.timedelta(days=42), label='Lockdown 6 týždňov', color='purple') plt.axvline(x=day_zero + dt.timedelta(days=21), label='Lockdown 3 týždne', color='orange') path = './plots/' + str(verzia_modelu) + '.png' plt.savefig(path, dpi=300) plt.close i = 0 for scen in scen_vyber: scenar = 'SIR_scenar' + str(scen) print('Scenar:', legenda[i], ', Peak:', np.round(np.max(dictagg[scenar].inf) * 100, 2), '%, Day: ', dictagg[scenar].inf.idxmax()) i += 1
def plot_samples(sc, basedir, idx=None): res = 15 t_day_start = sc.t_block_start - timedelta(hours=sc.t_block_start.hour, minutes=sc.t_block_start.minute) skip = (t_day_start - sc.t_start).total_seconds() / 60 / res i_block_start = (sc.t_block_start - t_day_start).total_seconds() / 60 / res i_block_end = (sc.t_block_end - t_day_start).total_seconds() / 60 / res t = drange(sc.t_block_start, sc.t_block_end, timedelta(minutes=res)) unctrl = load(p(basedir, sc.run_unctrl_datafile)) P_el_unctrl = unctrl[:, 0, skip + i_block_start:skip + i_block_end].sum(0) sample_data = load(p(basedir, sc.run_pre_samplesfile)) if idx is not None: sample_data = sample_data[idx].reshape((1, ) + sample_data.shape[1:]) fig, ax = plt.subplots(len(sample_data)) if len(sample_data) == 1: ax = [ax] for i, samples in enumerate(sample_data): # t = np.arange(samples.shape[-1]) # ax[i].plot(t, P_el_unctrl, ls=':') l_unctrl, = ax[i].plot_date(t, P_el_unctrl, fmt=':', color=PRIMB, drawstyle='steps-post', lw=0.75) l_unctrl.set_dashes([1.0, 1.0]) for s in samples: ax[i].plot_date(t, s, fmt='-', drawstyle='steps-post', lw=0.75) fig.autofmt_xdate()
def plot_slp(sc, bd): slp = _read_slp(sc, bd) res = 1 if (sc.t_end - sc.t_start).total_seconds() / 60 == slp.shape[-1] * 15: res = 15 t = drange(sc.t_start, sc.t_end, timedelta(minutes=res)) fig, ax = plt.subplots() ax.set_ylabel('P$_{el}$ [kW]') ymax = max(slp.max(), slp.max()) ymin = min(slp.min(), slp.min()) ax.set_ylim(ymin - (ymin * 0.1), ymax + (ymax * 0.1)) ax.plot_date(t, slp, fmt='-', lw=1, label='H0') leg0 = ax.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=4, borderaxespad=0.0, fancybox=False) fig.autofmt_xdate() for label in leg0.get_texts(): label.set_fontsize('x-small') fig.subplots_adjust(left=0.1, right=0.95, top=0.88, bottom=0.2) return fig
def plot_samples(sc, basedir, idx=None): res = 15 t_day_start = sc.t_block_start - timedelta(hours=sc.t_block_start.hour, minutes=sc.t_block_start.minute) skip = (t_day_start - sc.t_start).total_seconds() / 60 / res i_block_start = (sc.t_block_start - t_day_start).total_seconds() / 60 / res i_block_end = (sc.t_block_end - t_day_start).total_seconds() / 60 / res t = drange(sc.t_block_start, sc.t_block_end, timedelta(minutes=res)) unctrl = load(p(basedir, sc.run_unctrl_datafile)) P_el_unctrl = unctrl[:,0,skip + i_block_start:skip + i_block_end].sum(0) sample_data = load(p(basedir, sc.run_pre_samplesfile)) if idx is not None: sample_data = sample_data[idx].reshape((1,) + sample_data.shape[1:]) fig, ax = plt.subplots(len(sample_data)) if len(sample_data) == 1: ax = [ax] for i, samples in enumerate(sample_data): # t = np.arange(samples.shape[-1]) # ax[i].plot(t, P_el_unctrl, ls=':') l_unctrl, = ax[i].plot_date(t, P_el_unctrl, fmt=':', color=PRIMB, drawstyle='steps-post', lw=0.75) l_unctrl.set_dashes([1.0, 1.0]) for s in samples: ax[i].plot_date(t, s, fmt='-', drawstyle='steps-post', lw=0.75) fig.autofmt_xdate()
def draw(item, maxy, ylabel, filename_fig): array = np.zeros((plot_resolution_x, plot_resolution_y)) # x1 = np.arange(max_x * 1000)/1000 for detections in item: x1, y1 = zip(*detections) # p = np.poly1d(coeffs) # y1 = np.exp(p(x1)) zer = np.zeros_like(array) prev_point = None for x_elem, y_elem in zip(x1, y1): if y_elem >= maxy: continue if x_elem >= max_x: continue x_p = x_to_xid(x_elem, max_x, plot_resolution_x) y_p = y_to_yid(y_elem, maxy, plot_resolution_y) if prev_point is None: zer[x_p, y_p] = 1.0 else: zer[prev_point[0]:(x_p + 1), prev_point[1]:(y_p + 1)] = 1.0 prev_point = (x_p, y_p) array += zer fig, ax = plt.subplots(figsize=(10, 6)) # s = ndimage.generate_binary_structure(2, 1) # array = ndimage.grey_dilation(array, footprint=s) pa = ax.imshow(np.rot90(array), cmap='BuPu', vmin=0, vmax=np.maximum(5, np.percentile(array, 99)), aspect='auto') ax.set_title(f'q={q_id}, ({bundle_prefix.strip("_")})', fontsize=18) cbb = plt.colorbar(pa, shrink=0.35) cbarlabel = 'Zagęszczenie trajektorii' cbb.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom", fontsize=18) ax.set_xticks( np.arange(0, plot_resolution_x + 1, 7 * plot_resolution_x / max_x)) now = parser.parse(begin_date) then = now + dt.timedelta(days=max_x + 1) days = mdates.drange(now, then, dt.timedelta(days=7)) t = [ dt.datetime.fromordinal(int(day)).strftime('%d/%m/%y') for day in days ] ax.set_xticklabels([t[i] for i, v in enumerate(range(0, max_x + 1, 7))], rotation=30) ax.set_yticks([ v for v in np.arange(plot_resolution_y, -1, -plot_resolution_y / 10.0) ]) ax.set_yticklabels([int(v) for v in np.arange(0, maxy + 1, maxy / 10.0) ]) # , list(np.arange(20))) ax.set_ylabel(ylabel, fontsize=18) xlabel_pl = 'Data' xlabel_en = 'Days from today' xlabel = xlabel_pl ax.set_xlabel(xlabel, fontsize=18, labelpad=16) plt.tight_layout() plt.savefig(os.path.join(d, filename_fig), dpi=300) plt.close(fig)
def test_drange(self): temp = self.temp temp = temp.split(" ") x = datetime.datetime(int(temp[0]), int(temp[1]), int(temp[2])) y = datetime.datetime(int(temp[3]), int(temp[4]), int(temp[5])) delta = datetime.timedelta(hours=5) self.assertEqual( dates.drange(x, y, delta)[5], float(self.expectedValue))
def hist_date(date_vector, lim_inf, lim_sup, dt=1): # Default = 1day bin ''' Create the bin of a datetime vector. Input: @date_vector : array of dates in DATETIME format (length = N) @lim_inf : min of the hist x-range, in DATETIME format (e.g., min(date_vector)) @lim_sup : max of the hist x-range, in DATETIME format (e.g., max(date_vector)) @dt : sampling interval (default = 1 day) Output: @bins4hist : array of date values (in float) for the histogram, with the latest values being lim_sup + 1 dt (length = N+1) @bins4plot : array of date values (in float) for the bar plot (length = N) @cnts : counts in each bins4hist (length = N) ''' delta = datetime.timedelta(days=dt) # Bins of 24hrs #Convert the limits in order to start from 00:00:00 of the first day and finish on 23:59:59 of the last day lim_inf = float(int(matplotlib.dates.date2num(lim_inf))) lim_sup = math.ceil(matplotlib.dates.date2num(lim_sup)) #Convert datetime dates into floats date_vector_num = map( lambda x: matplotlib.dates.date2num(x), date_vector) # == date_num = matplotlib.dates.date2num(date_good) #Ned to re-convert into datetime format for the drange() lim_inf = matplotlib.dates.num2date(lim_inf) lim_sup = matplotlib.dates.num2date(lim_sup) #Create the array bins4plot with equally spaced dates, with step = dt #bins4plots contains N points, from lim_inf -> lim_sup bins4plot = drange(lim_inf, lim_sup, delta) #bins4hist contains N+1 points, from lim_inf -> lim_sup + 1 dt bins4hist = drange(lim_inf, lim_sup + datetime.timedelta(days=dt), delta) #Counts in each bins4hist cnts = np.histogram(date_vector_num, bins=bins4hist)[0] #date_vector_num = [matplotlib.dates.date2num(item) for item in date_vector] # Convert type(datetime) -> number #cnts = np.histogram(date_vector_num, bins = dt_limits)[0] # Counts for each dt, with width = delta #bins4hist = [0.5*(dt_limits[i] + dt_limits[i+1]) for i in range(len(dt_limits)-1)] # Re-compute the center of each bin in order to have same size counts and dt_i return bins4hist, bins4plot, cnts
def plot_data(epidemics_start_date, confirmed_cases, recovered_cases, death_cases, daily_tests=None, paper_config=False): """Plot the time series epidemiological statistics. Parameters ---------- epidemics_start_date : datetime.datetime First day of the epidemics. confirmed_cases : numpy.ndarray Cumulative number of confirmed positive infected cases. recovered_cases : numpy.ndarray Cumulative number of confirmed recoveries. death_cases : numpy.ndarray Cumulative number of confirmed deaths. daily_tests : numpy.ndarray, optional Time series of daily performed tests. paper_config : bool, optional Activate LaTeX mode. """ removed_cases = recovered_cases + death_cases active_cases = confirmed_cases - removed_cases epidemics_end_date = epidemics_start_date \ + dt.timedelta(confirmed_cases.size) days = mdates.drange( epidemics_start_date, epidemics_end_date, dt.timedelta(days=1)) if paper_config: configure_paper() fig = plt.figure(figsize=(9, 5)) else: mpl.rcParams.update(mpl.rcParamsDefault) fig = plt.figure(figsize=(9, 5)) axs = fig.subplots(nrows=2, ncols=2, sharex=True, squeeze=True) axs[0,0].plot(days, confirmed_cases, '.-', c='b', label='Total confirmed cases') axs[0,0].plot(days, recovered_cases, '.--', c='r', label='Total recovered cases') axs[0,0].legend() axs[0,0].grid() axs[0,0].set_ylabel('$N$') axs[1,0].plot(days, death_cases, '.-', c='b', label='Death cases') axs[1,0].legend() axs[1,0].grid() axs[1,0].set_ylabel('$N$') axs[0,1].plot(days, active_cases, '.-', c='b', label='Current active cases') axs[0,1].legend() axs[0,1].grid() axs[0,1].set_ylabel('$N$') if daily_tests is not None: axs[1,1].plot(days, daily_tests, '.-', c='b', label='Tests performed') axs[1,1].legend() axs[1,1].grid() axs[1,1].set_ylabel('$N$') _ = fig.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) _ = fig.gca().xaxis.set_major_locator(mdates.DayLocator(interval=20)) _ = plt.gcf().autofmt_xdate() plt.tight_layout() plt.show()
def plot(context, spills=False, filename=None, showlegend=True): """Produce a pretty plot of supply and demand.""" spill = context.spill # aggregate demand demand = context.demand.sum(axis=0) plt.ylabel('Power (MW)') title = 'Supply/demand balance\nRegions: %s' % context.regions plt.suptitle(title) if showlegend: _legend(context) xdata = mdates.drange(context.startdate, context.startdate + dt.timedelta(hours=context.hours), dt.timedelta(hours=1)) # Plot demand first. plt.plot(xdata, demand, color='black', linewidth=2) if spills: peakdemand = np.empty_like(demand) peakdemand.fill(demand.max()) plt.plot(xdata, peakdemand, color='black', linestyle='dashed') accum = np.zeros(context.timesteps) prev = accum.copy() for g in _generator_list(context): idx = context.generators.index(g) accum += context.generation[idx] # Ensure total generation does not exceed demand in any timestep. assert(np.round(accum, 6) > np.round(demand, 6)).sum() == 0 plt.plot(xdata, accum, color='black', linewidth=0.5) plt.fill_between(xdata, prev, accum, facecolor=g.patch.get_fc()) prev = accum.copy() # Unmet demand is shaded red. plt.fill_between(xdata, accum, demand, facecolor='red') if spills: prev = demand.copy() for g in [g for g in context.generators if g.region() in context.regions]: idx = context.generators.index(g) accum += spill[idx] plt.plot(xdata, accum, color='black') plt.fill_between(xdata, prev, accum, facecolor=g.patch.get_fc(), alpha=0.3) prev = accum.copy() plt.gca().xaxis_date() plt.gcf().autofmt_xdate() for hr in np.argwhere(context.unserved): unserved_dt = context.startdate + dt.timedelta(hours=hr[0]) xvalue = mdates.date2num(unserved_dt) _, ymax = plt.gca().get_ylim() plt.plot([xvalue], [ymax - 200], "yv", markersize=15, color='red') if not filename: plt.show() # pragma: no cover else: plt.savefig(filename)
def simulate(epidemics_start_date, confirmed_cases, averaging_period=16, symptoms_delay=3): """Simulate and visualize the R0 with respect to the number of confirmed infections daily." Parameters ---------- epidemics_start_date : datetime.datetime confirmed_cases : numpy.ndarray The total number of confirmed infected COVID-19 cases per day. averaging_period : int, optional Parameter for smoothing the `confirmed_cases` array. symptoms_delay : int, optional Number of days between the infection and the confirmation (incubation period estimate). """ delay = averaging_period + symptoms_delay R = _estimate(confirmed_cases, averaging_period, symptoms_delay) R_averaging_period = int(averaging_period / symptoms_delay) R_smoothed = moving_average(R, R_averaging_period) epidemics_duration = confirmed_cases.size dates = mdates.drange( epidemics_start_date, epidemics_start_date + dt.timedelta(days=epidemics_duration), dt.timedelta(days=1)) fig = plt.figure(figsize=(12, 6)) ax1 = fig.add_subplot(111) ax1.plot(dates, confirmed_cases, 'b-', label='Cumalitive cases') ax1.tick_params(axis='y', labelcolor='b') ax1.set_ylabel('Confirmed cases', color='b') ax1.legend() ax1.grid(None) ax2 = ax1.twinx() ax2.scatter(dates[:-delay + 1], R, color='r', edgecolor='black', label='R values') ax2.plot(dates, np.ones(dates.shape), 'k--', label='Critical value') ax2.plot(dates[R_averaging_period:-delay + 2], R_smoothed, 'r-', linewidth=2, label='R averaged') ax2.tick_params(labelcolor='r') ax2.set_ylabel('R values', color='r') ax2.legend() fig.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) fig.gca().xaxis.set_major_locator(mdates.DayLocator(interval=10)) fig.autofmt_xdate() plt.show()
def print_plot_for_dollar_euro_x_days(days): dollar = get_currency_rates_from_x_last_days('usd', days) euro = get_currency_rates_from_x_last_days('eur', days) # for example dollar[0] has rates, dollar[1] has dates if len(dollar[0]) > 0: x__days_ago_date = (datetime.strptime(dollar[1][0], "%Y-%m-%d")).date() today_date = (datetime.strptime(euro[1][len(euro[1]) - 1], "%Y-%m-%d") + timedelta(days=1)).date() dates = drange(x__days_ago_date, today_date, timedelta(days=1)) print_plot_for_currencies(dollar[0], euro[0], dates)
def plot_aggregated(sc, bd, unctrl, ctrl, ctrl_sched, res=1): t_day_start = sc.t_block_start - timedelta(hours=sc.t_block_start.hour, minutes=sc.t_block_start.minute) t = drange(t_day_start, sc.t_end, timedelta(minutes=res)) skip = (t_day_start - sc.t_start).total_seconds() / 60 / res i_block_start = (sc.t_block_start - t_day_start).total_seconds() / 60 / res i_block_end = (sc.t_block_end - t_day_start).total_seconds() / 60 / res P_el_unctrl = unctrl[:,0,skip:].sum(0) P_el_ctrl = ctrl[:,0,skip:].sum(0) P_el_sched = ctrl_sched[:,skip:].sum(0) T_storage_ctrl = ctrl[:,2,skip:] ft = np.array([t[0]] + list(np.repeat(t[1:-1], 2)) + [t[-1]]) P_el_ctrl_fill = np.repeat(P_el_ctrl[:-1], 2) fig, ax = plt.subplots(2, sharex=True) fig.subplots_adjust(left=0.11, right=0.95, hspace=0.3, top=0.98, bottom=0.2) ax[0].set_ylabel('P$_{\mathrm{el}}$ [kW]') ymax = max(P_el_unctrl.max(), P_el_ctrl_fill.max(), P_el_sched.max(), 0) / 1000.0 ymin = min(P_el_unctrl.min(), P_el_ctrl_fill.min(), P_el_sched.min(), 0) / 1000.0 ax[0].set_ylim(ymin - abs(ymin * 0.1), ymax + abs(ymax * 0.1)) # xspace = (t[-1] - t[-2]) ax[0].set_xlim(t[0], t[24]) ax[0].axvspan(t[i_block_start], t[i_block_end], fc=GRAY+(0.1,), ec=EC) ax[0].axvline(t[0], ls='-', color=GRAY, lw=0.5) ax[0].axvline(t[len(t)/2], ls='-', color=GRAY, lw=0.5) l_unctrl, = ax[0].plot_date(t, P_el_unctrl / 1000.0, fmt=':', color=PRIMB, drawstyle='steps-post', lw=0.75) l_unctrl.set_dashes([1.0, 1.0]) # add lw=0.0 due to bug in mpl (will show as hairline in pdf though...) l_ctrl = ax[0].fill_between(ft, P_el_ctrl_fill / 1000.0, facecolors=PRIM+(0.5,), edgecolors=EC, lw=0.0) # Create proxy artist as l_ctrl legend handle l_ctrl_proxy = Rectangle((0, 0), 1, 1, fc=PRIM, ec=WHITE, lw=0.0, alpha=0.5) l_sched, = ax[0].plot_date(t, P_el_sched / 1000.0, fmt='-', color=PRIM, drawstyle='steps-post', lw=0.75) ymax = T_storage_ctrl.max() - 273 ymin = T_storage_ctrl.min() - 273 ax[1].set_ylim(ymin - abs(ymin * 0.01), ymax + abs(ymax * 0.01)) ax[1].set_ylabel('T$_{\mathrm{storage}}\;[^{\circ}\mathrm{C}]$', labelpad=9) ax[1].axvspan(t[i_block_start], t[i_block_end], fc=GRAY+(0.1,), ec=EC) ax[1].axvline(t[0], ls='-', color=GRAY, lw=0.5) ax[1].axvline(t[len(t)/2], ls='-', color=GRAY, lw=0.5) for v in T_storage_ctrl: ax[1].plot_date(t, v - 273.0, fmt='-', color=PRIMA, alpha=0.25, lw=0.5) l_T_med, = ax[1].plot_date(t, T_storage_ctrl.mean(0) - 273.0, fmt='-', color=PRIMA, alpha=0.75, lw=1.5) ax[0].xaxis.get_major_formatter().scaled[1/24.] = '%H:%M' ax[-1].set_xlabel('Time') fig.autofmt_xdate() ax[1].legend([l_sched, l_unctrl, l_ctrl_proxy, l_T_med], ['Schedule', 'Uncontrolled', 'Controlled', 'Storage temperatures'], bbox_to_anchor=(0., 1.03, 1., .103), loc=8, ncol=4, handletextpad=0.2, mode='expand', handlelength=3, borderaxespad=0.25, fancybox=False, fontsize='x-small') return fig
def Draw_Figure(pay_data,all_view_data,shop_id): shop_path = 'data/shop_info.txt' '''读取shop_info data''' shop_info = pd.read_csv(shop_path, names=['shopid', 'city_name', 'location_id', 'per_pay', 'score', 'comment_cnt', 'shop_level', 'cate1_name', 'cate2_name', 'cate3_name']) startDate = datetime.datetime(2015, 6, 1) endDate = datetime.datetime(2017, 1, 1) delta = datetime.timedelta(days=20) dates = drange(startDate, endDate, delta) #获取date刻度List fig = plt.figure(figsize=(15, 8)) view_ax = fig.add_subplot(1, 1, 1) view_ax.set_xticklabels(dates, rotation=45, size=5) _cur_shop_info = shop_info[shop_info.shopid == shop_id ] if str(_cur_shop_info.cate1_name.values[0]) == '美食': figure_pay_path = 'M1_Figure\\'; else: figure_pay_path = 'CS1_Figure\\'; plt.title('\nshopID:'+str(_cur_shop_info.shopid.values[0])+' city:'+str(_cur_shop_info.city_name.values[0]) +' perpay:'+str(_cur_shop_info.per_pay.values[0])+'\nscore:'+str(_cur_shop_info.score.values[0])+' conmment:'+ str(_cur_shop_info.comment_cnt.values[0])+' cate1_name:'+str(_cur_shop_info.cate1_name.values[0])+'\ncate2_name:'+ str(_cur_shop_info.cate2_name.values[0])+'cate3_name'+str(_cur_shop_info.cate3_name.values[0])) ##################绘制view_time折线图############################################################################################# _cur_date_series = all_view_data[all_view_data.shopid == shop_id]['time'].tolist() _cur_count_series = all_view_data[all_view_data.shopid == shop_id]['count'].tolist() _cd_series = pd.Series(_cur_count_series, index=_cur_date_series) if len(_cd_series.index)!=0: view_index = pd.DatetimeIndex([_cd_series.index[0], _cd_series.index[len(_cd_series)-1]]) else: view_index = pd.DatetimeIndex(['2016-7-1', '2016-10-31']) _view_series = pd.Series([0, 0], index=view_index).resample('D', ).pad() for time in _cd_series.index: _view_series[time] = _cd_series[time] view_cur_date_series = _view_series.index view_cur_count_series =_view_series.values ###########################绘制pay_time折线图########################################################################### _cur_date_series = pay_data[pay_data.shopid == shop_id]['time'].tolist() _cur_count_series = pay_data[pay_data.shopid == shop_id]['count'].tolist() _cd_series = pd.Series(_cur_count_series, index=_cur_date_series) pay_index = pd.DatetimeIndex([_cd_series.index[0], _cd_series.index[len(_cd_series)-1]]) _pay_series = pd.Series([0, 0], index=pay_index).resample('D', ).pad() for time in _cd_series.index: _pay_series[time] = _cd_series[time] pay_cur_date_series = _pay_series.index pay_cur_count_series = _pay_series.values ######################################################################################################################## figure_name =figure_pay_path + str(shop_id) + '_view_time.png' view_ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d') ) view_ax.plot_date(view_cur_date_series,view_cur_count_series,'m-', marker='.',linewidth=1); view_ax.plot_date(pay_cur_date_series, pay_cur_count_series, 'k-', marker='.',linewidth=1); print figure_name plt.savefig(figure_name) view_ax.clear()
def return_date_list(start, end): delta = datetime.timedelta(days=1) # set increment as one day float_date_list = drange(start, end, delta) date_list = [] for day in range(len(float_date_list)): # create a dates list with YYYY-MM-DD date format date_list.append(date.fromordinal(int(float_date_list[day])).strftime('%Y-%m-%d')) return date_list
def newusersEvolution(cursor=None, title=''): result = cursor.execute("SELECT STRFTIME('%Y-%m-%d', rev_timestamp) AS date, rev_user_text FROM revision WHERE 1 ORDER BY date ASC") newusers = {} for row in result: if not newusers.has_key(row[1]): newusers[row[1]] = datetime.date(year=int(row[0][0:4]), month=int(row[0][5:7]), day=int(row[0][8:10])) newusers2 = {} for newuser, date in newusers.items(): if newusers2.has_key(date): newusers2[date] += 1 else: newusers2[date] = 1 newusers_list = [[x, y] for x, y in newusers2.items()] newusers_list.sort() startdate = newusers_list[0][0] enddate = newusers_list[-1:][0][0] delta = datetime.timedelta(days=1) newusers_list = [] #reset, adding all days between startdate and enddate d = startdate while d < enddate: if newusers2.has_key(d): newusers_list.append([d, newusers2[d]]) else: newusers_list.append([d, 0]) d += delta import pylab from matplotlib.dates import DateFormatter, rrulewrapper, RRuleLocator, drange loc = pylab.MonthLocator(bymonth=(1,6)) formatter = DateFormatter('%Y-%m-%d') dates = drange(startdate, enddate, delta) fig = pylab.figure() ax = fig.add_subplot(1,1,1) ax.set_ylabel('Newusers') ax.set_xlabel('Date (YYYY-MM-DD)') print '#'*100 print len(dates) print dates print '#'*100 print len(pylab.array([y for x, y in newusers_list])) print pylab.array([y for x, y in newusers_list]) print '#'*100 pylab.plot_date(dates, pylab.array([y for x, y in newusers_list]), 'o', color='green') ax.xaxis.set_major_locator(loc) ax.xaxis.set_major_formatter(formatter) ax.set_title(title) ax.grid(True) ax.set_yscale('log') labels = ax.get_xticklabels() pylab.setp(labels, rotation=30, fontsize=10)
def getEmptyTimeArrayRange(sampleMeasurement, interval, startDate, endDate): """ Use the mat lab dates function instead of a loop to make the array Use this to test the speed difference""" newStartTime = CbibsStationJsonMgr.getStartDate( sampleMeasurement, startDate, interval) endDate = endDate.replace(tzinfo=pytz.utc) # Generate a series of dates (these are in matplotlib's internal date format) emptyArray = mdates.drange(newStartTime, endDate, datetime.timedelta(minutes=(interval / 60))) return emptyArray
def newpagesEvolution(cursor=None, title=''): result = cursor.execute( "SELECT STRFTIME('%Y-%m-%d', page_creation_timestamp) AS date, COUNT(*) AS count FROM page WHERE 1 GROUP BY date ORDER BY date ASC" ) newpages = {} for row in result: d = datetime.date(year=int(row[0][0:4]), month=int(row[0][5:7]), day=int(row[0][8:10])) newpages[d] = row[1] newpages_list = [[x, y] for x, y in newpages.items()] newpages_list.sort() startdate = newpages_list[0][0] enddate = newpages_list[-1:][0][0] delta = datetime.timedelta(days=1) newpages_list = [] #reset, adding all days between startdate and enddate d = startdate while d < enddate: if newpages.has_key(d): newpages_list.append([d, newpages[d]]) else: newpages_list.append([d, 0]) d += delta import pylab from matplotlib.dates import DateFormatter, rrulewrapper, RRuleLocator, drange loc = pylab.MonthLocator(bymonth=(1, 6)) formatter = DateFormatter('%Y-%m-%d') dates = drange(startdate, enddate, delta) fig = pylab.figure() ax = fig.add_subplot(1, 1, 1) ax.set_ylabel('Newpages') ax.set_xlabel('Date (YYYY-MM-DD)') print '#' * 100 print len(dates) print dates print '#' * 100 print len(pylab.array([y for x, y in newpages_list])) print pylab.array([y for x, y in newpages_list]) print '#' * 100 pylab.plot_date(dates, pylab.array([y for x, y in newpages_list]), 'o') ax.xaxis.set_major_locator(loc) ax.xaxis.set_major_formatter(formatter) ax.set_title(title) ax.grid(True) ax.set_yscale('log') labels = ax.get_xticklabels() pylab.setp(labels, rotation=30, fontsize=10)
def plotmap(df, color, cbarlabel, xaxislabel, yaxislabel, graphiclabel, filelabel): import matplotlib.dates as mdates from matplotlib import ticker import datetime import matplotlib import seaborn as sns # Set up the size/style sns.set(rc={"figure.figsize": (12, 15)}) sns.set_style("whitegrid") numberofplots = 1 fig = plt.figure() x = mdates.drange(df.index[0], df.index[-1] + datetime.timedelta(days=1), datetime.timedelta(days=1)) y = np.linspace(0, len(df.columns), len(df.columns) + 1) ax = fig.add_subplot(numberofplots, 1, 1) data = np.array(df.T) datam = np.ma.array(data, mask=np.isnan(data)) cmap = matplotlib.cm.get_cmap(color) qmesh = ax.pcolormesh(x, y, datam, cmap=cmap) cbaxes = fig.add_axes([0.15, 0.15, 0.7, 0.02]) cbar = fig.colorbar(qmesh, ax=ax, orientation='horizontal', cax=cbaxes) cbar.ax.tick_params(length=0) cbar.set_label(cbarlabel) ax.axis('tight') ax.xaxis_date() fig.autofmt_xdate() fig.subplots_adjust(hspace=.5) ax.set_xlabel(xaxislabel) ax.set_ylabel(yaxislabel) ax.set_title(graphiclabel) ax.set_yticklabels(df.columns) tick_locator = ticker.MaxNLocator(nbins=110) loc = ticker.MultipleLocator( base=1.0) # this locator puts ticks at regular intervals ax.locator_params(axis='y', nbins=100) myFmt = mdates.DateFormatter('%b') ax.xaxis.set_major_formatter(myFmt) # T=np.arange(len(df.columns))+0.5 # ax.set_yticks(T) # plt.tight_layout() plt.subplots_adjust(bottom=0.2)
def get_time_axis(data1, data2): ''' Get the time-axis to create the stem plot. It is will have a regulized time interval of 1 day. "data" - a dictornary that stores the required date info as it's values. ''' all_dates = set(data1.values()).union(set(data2.keys())) dstart = datetime.strptime(min(all_dates), "%Y-%m-%d") dend = datetime.strptime(max(all_dates), "%Y-%m-%d") + timedelta(days=1) delta = timedelta(days=1) time_axis_md = mdates.drange(dstart, dend, delta) time_axis_py = mdates.num2date(time_axis_md, tz=None) return time_axis_py
def gen_data(date_current,type,precision): data_to_process =[] #debugging delta = datetime.timedelta(minutes = precision) #debugging if type == 'dayh': date_previous = date_current - datetime.timedelta(days=1) for item in drange(date_previous,date_current + datetime.timedelta(days=1),delta): #debugging data_to_process.append({'datetimestamp':num2date(item),'Pactiva':1}) #debugging elif type == 'week': date_previous = (date_current -datetime.timedelta(days=7+date_current.weekday())) for item in drange(date_previous,date_current + datetime.timedelta(days=1),delta): #debugging data_to_process.append({'datetimestamp':num2date(item),'Pactiva':1}) #debugging elif type == 'month': if date_current.month < 2: date_previous = date_current.replace(year=date_current.year-1,month=12,day=1) else: date_previous = date_current.replace(month=date_current.month - 1,day=1) for item in drange(date_previous,date_current + datetime.timedelta(days=1),delta): #debugging data_to_process.append({'datetimestamp':num2date(item),'Pactiva':1}) #debugging elif type == 'year': date_previous = date_current.replace(year=date_current.year - 1,month=1,day=1) for item in drange(date_previous,date_current + datetime.timedelta(days=1),delta): #debugging data_to_process.append({'datetimestamp':num2date(item),'Pactiva':1}) #debugging return data_to_process
def newpagesEvolution(cursor=None, title=""): result = cursor.execute( "SELECT STRFTIME('%Y-%m-%d', page_creation_timestamp) AS date, COUNT(*) AS count FROM page WHERE 1 GROUP BY date ORDER BY date ASC" ) newpages = {} for row in result: d = datetime.date(year=int(row[0][0:4]), month=int(row[0][5:7]), day=int(row[0][8:10])) newpages[d] = row[1] newpages_list = [[x, y] for x, y in newpages.items()] newpages_list.sort() startdate = newpages_list[0][0] enddate = newpages_list[-1:][0][0] delta = datetime.timedelta(days=1) newpages_list = [] # reset, adding all days between startdate and enddate d = startdate while d < enddate: if newpages.has_key(d): newpages_list.append([d, newpages[d]]) else: newpages_list.append([d, 0]) d += delta import pylab from matplotlib.dates import DateFormatter, rrulewrapper, RRuleLocator, drange loc = pylab.MonthLocator(bymonth=(1, 6)) formatter = DateFormatter("%Y-%m-%d") dates = drange(startdate, enddate, delta) fig = pylab.figure() ax = fig.add_subplot(1, 1, 1) ax.set_ylabel("Newpages") ax.set_xlabel("Date (YYYY-MM-DD)") print "#" * 100 print len(dates) print dates print "#" * 100 print len(pylab.array([y for x, y in newpages_list])) print pylab.array([y for x, y in newpages_list]) print "#" * 100 pylab.plot_date(dates, pylab.array([y for x, y in newpages_list]), "o") ax.xaxis.set_major_locator(loc) ax.xaxis.set_major_formatter(formatter) ax.set_title(title) ax.grid(True) ax.set_yscale("log") labels = ax.get_xticklabels() pylab.setp(labels, rotation=30, fontsize=10)
def graphcoord_time(axis): time = mdates.drange(datetime.datetime(2014, 10, 21, 16), datetime.datetime(2014, 10, 25, 16), datetime.timedelta(minutes=15)) fig = plt.figure() plt.plot_date(time, vector.T[axis]/50000, 'b-') plt.ylabel(axis) # 2014-10-23T08:30:24Z plt.axvline(datetime.datetime(2014, 10, 23, 8, 30, 24)) fig.autofmt_xdate() plt.show()
def convertPythonDateTime(DateTime): # Since it looks like matplotlib.dates.formatter does not work on work in mpld3... # I have to manually make a function print DateTime delta = datetime.timedelta(days=1) startDate = datetime.date(2015,5,5)#mdates.num2epoch(0) endDate = datetime.date(2016,3,5)#mdates.num2epoch(DateTime[-1]) print delta print startDate print endDate newDate = mdates.drange(startDate, endDate, delta) print 'test' return newDate
def makeFakeRainData(): tdelta = dt.datetime(2001, 1, 1, 1, 5) - dt.datetime(2001, 1, 1, 1, 0) start = dt.datetime(2001, 1, 1, 12, 0) end = dt.datetime(2001, 1, 1, 16, 0) daterange_num = mdates.drange(start, end, tdelta) daterange = mdates.num2date(daterange_num) rain_raw = [ 0., 1., 2., 3., 4., 4., 4., 4., 4., 4., 4., 4., 0., 0., 0., 0., 0., 5., 5., 5., 5., 5., 5., 5., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 2., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0. ] return daterange, rain_raw
def makeFakeRainData(): tdelta = dt.datetime(2001, 1, 1, 1, 5) - dt.datetime(2001, 1, 1, 1, 0) start = dt.datetime(2001, 1, 1, 12, 0) end = dt.datetime(2001, 1, 1, 16, 0) daterange_num = mdates.drange(start, end, tdelta) daterange = mdates.num2date(daterange_num) rain_raw = [ 0., 1., 2., 3., 4., 4., 4., 4., 4., 4., 4., 4., 0., 0., 0., 0., 0., 5., 5., 5., 5., 5., 5., 5., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 2., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0.] return daterange, rain_raw
def graphcoord_time(axis): time = mdates.drange(datetime.datetime(2014, 10, 21, 16), datetime.datetime(2014, 10, 25, 16), datetime.timedelta(minutes=15)) fig = plt.figure() plt.plot_date(time, vector.T[axis] / 50000, 'b-') plt.ylabel(axis) # 2014-10-23T08:30:24Z plt.axvline(datetime.datetime(2014, 10, 23, 8, 30, 24)) fig.autofmt_xdate() plt.show()
def get_commit_by_date(self): numdates = drange(self.start_date, self.stop_date, timedelta(days=1)) numcommits = [0 for i in numdates] for rev, time, author in self.changesets: date = to_datetime(time, utc).date() #get index of day in the dates list index = bisect(numdates, date2num(date)) - 1 numcommits[index] += 1 return (numdates, numcommits)
def graph_orders(orders): fig = figure() ax = fig.add_subplot(111) for market, res in orders.iteritems(): dates = [r[0] for r in res] counts = [r[1] for r in res] oneday = timedelta(days=1) x = drange(min(dates), max(dates) + oneday, oneday) ax.plot_date(x, counts, '-') ax.xaxis.set_major_locator(DayLocator()) ax.xaxis.set_major_formatter(DateFormatter("%x")) show()
def Plotzerosnowdays(data,beginyear,endyear): #function does not work with python 3....maybe problem with inputs date1 = dt.date(beginyear,1,1) date2 = dt.date(endyear+1,1,1) delta = dt.timedelta(days=1) datearray = mdates.drange(date1,date2,delta) #create date array zerosnowvalues = np.zeros(len(datearray)) #store zero snow days for i in range(len(datearray)): for j in range(len(data)): m,d,y = Dateformat(data[j]) datenum = mdates.date2num(dt.date(y,m,d)) if (datearray[i] == datenum): zerosnowvalues[i] = 1 #count day as zero snow datearray = mdates.num2date(datearray) plt.plot(datearray,zerosnowvalues) plt.ylim(0,2) return()
def makeMiddlePoint(li,delta): ''' 引数: li:リスト delta:datetime 戻り値:twoの間に入れる値をyield ''' for two in list(pairwise(li)): #liの中身を2つずつにわける if two[-1]-two[0]>=delta +timedelta(minutes=1): #抜き出したタプルの要素の差がdelta上であれば print('\nLack between %s and %s'% (two[0],two[1])) print('Substract',abs(two[0]-two[1])) for i in pltd.drange(two[0]+delta,two[-1],delta): li.insert(li.index(two[-1]),pltd.num2date(i)) #タプルの要素間の場所にdeltaずつ増やした値を入れる print('insert',pltd.num2date(i)) yield pltd.num2date(i).strftime('%Y%m%d_%H%M%S') print('\nThere is No point to insert') print('makeMiddlePoint END\n')
def build(ax1, servicio, unit): fechas, consumos = zip(*sorted(servicio.items())) f = interp1d(date2num(fechas), consumos) # generate interpolation func x = drange(fechas[0], fechas[-1], tdelta(days=1)) # generate range of points ax1.plot_date(fechas, consumos, 'g-') # plot original data ax1.set_ylabel('Consumo en ' + unit, color='g') ax2 = ax1.twinx() ax2.plot(x, np.gradient(f(x)), 'b-') ax2.set_ylabel(unit + ' / dia', color='b') # plot rate of change dt = date2num((fechas[0], fechas[-1])) dc = (consumos[-1] - consumos[0]) / (date2num(fechas[-1]) - date2num(fechas[0])) ax3 = ax1.twinx() ax3.plot(dt, (dc, dc), 'r-') ax3.set_ylabel(unit + '/dia periodo', color='r') # plot rate of change
def plot_angles_from_csv_file(fnames): majorLocator = MultipleLocator(12) majorFormatter = FormatStrFormatter('%d') minorLocator = MultipleLocator(2) fig, ax = plt.subplots(nrows=4, ncols=1, sharex=True) alldays = DayLocator() date1 = datetime.datetime(2016, 3, 10) date2 = datetime.datetime(2016, 3, 14) delta = datetime.timedelta(hours=24) dates = drange(date1, date2, delta) dfs = [] for fname in fnames: df = pd.read_csv(fname) dfs.append(df) # FIXME quick kludge for getting timing wrangled between data sets if os.path.basename(fnames[0]).startswith('anglesS'): dfs[3] = dfs[3].reindex(index=dfs[3].index.union(dfs[2].index).union(dfs[1].index).union(dfs[0].index)) elif os.path.basename(fnames[0]).startswith('anglesP'): dfs[0] = dfs[0].reindex(index=dfs[0].index.union(dfs[2].index).union(dfs[1].index).union(dfs[3].index)) else: raise Exception('unexpected basename for CSV file') dfs[0].plot(ax=ax[0], x='GMT', y='Angle_deg') dfs[1].plot(ax=ax[1], x='GMT', y='Angle_deg') dfs[2].plot(ax=ax[2], x='GMT', y='Angle_deg') dfs[3].plot(ax=ax[3], x='GMT', y='Angle_deg') # set common labels for a in ax: a.set_ylabel('Angle (deg.)') a.legend().set_visible(False) print a.get_xlim() ax[3].set_xlabel('GMT') plt.show()
def print_periods( id, periods ): for k,v in periods.items(): print( id,'%02d' % k,v['id'],':', v['start_date'].strftime('%Y-%m-%d'), v['end_date'].strftime('%Y-%m-%d'), 'kms:', '% 6.1f' % v['kms'], 'time:', v['time'] ) x = [] y = [] for k,v in periods.items(): x.append(v['end_date']) y.append(v['kms']) dates = drange(x) plt.bar(dates, y, width = 1, align='center') # plt.plot(x, y) plt.show()
def analyzeStatsForGlobalClassifier(): dataToPlot=dict() for l in Utilities.iterateJsonFromFile(Settings.stats_for_global_classifier): dataToPlot[datetime.strptime(l['day'], Settings.twitter_api_time_format)]=l['value'] date1 = Settings.startTime date2 = Settings.endTime dates = drange(date1, date2, timedelta(days=1)) print len(dates), len(dataToPlot) fig=plt.figure() # plt.plot_date(dates, [1 for k in dates], '-') plt.plot_date(dates, [dataToPlot[k] for k in sorted(dataToPlot)[:-1]], 'g-', lw=2, label='Global classifier (mean:%0.2f)'%numpy.mean(dataToPlot.values())) # plt.plot_date(dates, [0 for k in dates], '-') plt.ylim((0.4,0.55)) plt.ylabel('AUCM value') plt.xlabel('Day') plt.title('AUCM values for global classifier.') plt.legend() fig.autofmt_xdate() plt.show()
def fill(li,delta): ''' 引数: li:リスト delta:intまたはdatetime 戻り値:twoの間に入れる値をyield ''' for two in list(pairwise(li)): #liの中身を2つずつにわける print(two) if two[-1]-two[0]>delta: #抜き出したタプルの要素の差がdelta上であれば if type(two[0])==datetime: for i in pltd.drange(two[0]+delta,two[-1],delta): li.insert(li.index(two[-1]),pltd.num2date(i)) #タプルの要素間の場所にdeltaずつ増やした値を入れる # print('insert',pltd.num2date(i)) yield pltd.num2date(i) else : for i in range(two[0]+delta,two[-1],delta): li.insert(li.index(two[-1]),i) #タプルの要素間の場所にdeltaずつ増やした値を入れる # print('insert',i) yield i
def plot_each_device(sc, unctrl, cntrl): t = drange(sc.t_start, sc.t_end, timedelta(minutes=1)) for d_unctrl, d_ctrl in zip(unctrl, ctrl): fig, ax = plt.subplots(2, sharex=True) ax[0].set_ylabel('P$_{el}$ [kW]') ymax = max(d_unctrl[0].max(), d_ctrl[0].max()) / 1000.0 ax[0].set_ylim(-0.01, ymax + (ymax * 0.1)) ax[0].plot_date(t, d_unctrl[0] / 1000.0, fmt='-', lw=1, label='unctrl') ax[0].plot_date(t, d_ctrl[0] / 1000.0, fmt='-', lw=1, label='ctrl') leg0 = ax[0].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=4, borderaxespad=0.0, fancybox=False) ax[1].set_ylabel('T$_{storage}$ [\\textdegree C]') ax[1].plot_date(t, d_unctrl[2] - 273.0, fmt='-', lw=1, label='unctrl') ax[1].plot_date(t, d_ctrl[2] - 273.0, fmt='-', lw=1, label='ctrl') fig.autofmt_xdate() for label in leg0.get_texts(): label.set_fontsize('x-small') fig.subplots_adjust(left=0.1, right=0.95, top=0.88, bottom=0.2)
def run(self): """ start ECG plotting """ # continue doing this method until DAQ is stopped while not self.stopPlotThread.isSet(): # call the plot method to start plotting self.parentFrame.ecgplotter.plot() # check if the thread has been stopped. if yes, no need to update endtime. if not self.stopPlotThread.isSet(): self.parentFrame.ecgplotter.endtime += datetime.timedelta(seconds = 15) # initialize the time size (nagiiba kase after every 15 seconds. needs to be extended self.parentFrame.ecgplotter.timeaxis = num2date(drange(self.parentFrame.ecgplotter.starttime, self.parentFrame.ecgplotter.endtime, datetime.timedelta(milliseconds = 10))) else: break # add slider at the end of plotting only self.parentFrame.ecgplotter.addSlider(self.parentFrame.ecgplotter.endtime) # redraw the plotting window to make the slider appear self.parentFrame.ecgplotter.canvas.draw() self.parentFrame.ecgplotter.canvas.gui_repaint()
def initPlot(self): """ redraw the canvas to set the initial x and y axes when plotting starts """ # set the reference time of plotting self.starttime = datetime.datetime.today() self.starttime_tick = time.mktime(self.starttime.timetuple()) # set the current time of plotting (located at the end point of the plotter window) self.currenttime = self.starttime + datetime.timedelta(seconds = 3) self.currenttime_tick = time.mktime(self.currenttime.timetuple()) # set the time-value array for 15-second (equivalent to a duration of 1 EDF file) self.endtime = self.starttime + datetime.timedelta(seconds = 15) self.timeaxis = num2date(drange(self.starttime, self.endtime, datetime.timedelta(milliseconds = 10))) # append samples of x and y-axes to be plotted self.xvalues.append(self.timeaxis[0]) self.yvalues.append(self.parentPanel.myECG.ecg_leadII[0]) self.ybuffer = self.yvalues # set the new data to be plotted (based from the updated values of xvalues and yvalues array) self.lines[0].set_data(self.xvalues, self.yvalues) # set the plotter window limit to 3-second self.axes.set_xlim((date2num(self.starttime),date2num(self.currenttime))) # update the x-axis ticklabels depending on the current time of plotting self.axes.xaxis.set_ticklabels(self.createXTickLabels(self.currenttime_tick), rotation = 30, ha = "right", size = 'smaller', name = 'Calibri') self.samples_counter += 1 self.ysamples_counter += 1 self.buff_counter = 1 #for filtering self.startfil = 0 self.endfil = 1500
def plot_time_data(date_in,date_end,delta,data_y): ''' plot data against detetime values, provide date_initial and final ''' date1 = date_in date2 = date_end delta= datetime.timedelta(minutes=5) dates = drange(date1, date2, delta) fig = figure() ax = fig.add_subplot(111) if (len(dates)<>len(data_y[0:len(dates)])): print "error, len dates", len(dates) print "len dati ", len(data_y[0:len(dates)]) ax.plot_date(dates, data_y[0:len(dates)],'-') ax.set_xlim( dates[0], dates[-1] ) ax.xaxis.set_major_locator( DayLocator() ) ax.xaxis.set_minor_locator( HourLocator()) ax.xaxis.set_minor_formatter( DateFormatter('%H') ) ax.xaxis.set_major_formatter( DateFormatter('%Y-%m-%d') ) ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M') fig.autofmt_xdate() show()
def time2(): import datetime import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mpldates import matplotlib.ticker as ticker date1 = datetime.date( 1952, 1, 1 ) date2 = datetime.date( 2004, 4, 12 ) delta = datetime.timedelta(days=100) dates = mpldates.drange(date1, date2, delta) s1 = np.random.rand(len(dates)) fig = plt.figure() ax = fig.add_subplot(111) ax.plot_date(dates, s1,'r.') ax.hold(True) s2 = np.random.rand(len(dates)) ax.plot_date(dates, s2,'bo') ax.legend(('s1','s2'), numpoints=1) # only write ticklabels on the decades def fmtticks(x, pos=None): dt = mpldates.num2date(x) if dt.year%10: return '' return dt.strftime('%Y') # this fizes yhe tick labels ax.xaxis.set_major_formatter(ticker.FuncFormatter(fmtticks)) # this fixes the toolbar x coord ax.fmt_xdata = mpldates.DateFormatter('%Y-%m-%d') # this rotates the ticklabels to help with overlapping fig.autofmt_xdate() plt.show()