def plot_contrast(self,moneyrecord1,moneyrecord2,date_ls,startdate,enddate): startdate=self.datetransfer(startdate) date_ls_change=[] for i in date_ls: if int(i)>=int(startdate) and int(i)<=int(enddate): date_ls_change.append(i) mondays = WeekdayLocator(MONDAY) months = MonthLocator(range(1, 13), bymonthday=1, interval=3) monthsFmt = DateFormatter("%b '%y") print(date_ls_change) #print(date_ls) date = [str(e) for e in date_ls_change] date_ls = [datetime.datetime.strptime(d,'%Y%m%d').date() for d in date] algo_pv=moneyrecord1['money'].tolist() print(algo_pv) bench_pv=moneyrecord2['moneybenchmark'].tolist() fig, ax = plt.subplots() plt.gca().set_color_cycle(['blue', 'red']) ax.plot_date(date_ls, algo_pv,'-') ax.plot_date(date_ls, bench_pv,'-') months.MAXTICKS=5000 mondays.MAXTICKS=5000 ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(monthsFmt) ax.xaxis.set_minor_locator(mondays) ax.autoscale_view() ax.grid(True) fig.autofmt_xdate() plt.title('P&L') plt.legend(['strategy', 'benchmark'], loc='upper left') plt.show()
def formatAxticks(ax): days = DayLocator() # every month months = MonthLocator() # every month months.MAXTICKS = 3000 yearsFmt = DateFormatter('%d/%m/%Y') ax.xaxis.set_major_locator(months) ax.xaxis.set_minor_locator(days) ax.xaxis.set_major_formatter(yearsFmt) ax.autoscale_view() ticks = ax.get_xticks() n = len(ticks)/4 ax.set_xticks(ticks[::n]) return ax
def scale_ave_timeseries2D(scale_ave1, scale_ave2, time1, time2, scales_bin): """plotting WaveTransform scale averaged power for selected bins""" fig = plt.figure(5) ax1 = plt.subplot(1, 1, 1) p1 = ax1.plot(time1, scale_ave1, 'k', time2, scale_ave2, 'r--') ax1.set_xlim([time1.min(), time1.max()]) ax1.grid(True) ax1.set_ylabel('Average power between scales ' + str(scales_bin[0]) + ' and ' + str(scales_bin[1]) + '') ax1.set_xlabel('Time (UTC)') ax1.xaxis.set_minor_locator(MonthLocator(bymonthday=(1, 15))) ax1.xaxis.set_major_locator(MonthLocator(bymonthday=1, interval=2)) ax1.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) #plt.show() DefaultSize = fig.get_size_inches() fig.set_size_inches((DefaultSize[0] * 2, DefaultSize[1])) return (plt, fig)
def on_year_changed(self, combo): """ Re-plot the statistics for the year selected by the user. """ # Clear figure self.items["YEARLY_STATISTICS"].clf() self.items["YEARLY_STATISTICS"].canvas.draw() # Get year to show statistics for. year = combo.get_active_text() try: year = int(year) except ValueError: # Empty year string. return # Number of contacts made each month contact_count_plot = self.items["YEARLY_STATISTICS"].add_subplot(121) contact_count = self.get_annual_contact_count(year) # x-axis formatting based on the date contact_count_plot.bar(list(contact_count.keys()), list(contact_count.values()), color="k", width=15, align="center") formatter = DateFormatter("%b") contact_count_plot.xaxis.set_major_formatter(formatter) month_locator = MonthLocator() contact_count_plot.xaxis.set_major_locator(month_locator) contact_count_plot.set_ylabel("Number of QSOs") # Set x-axis upper limit based on the current month. contact_count_plot.xaxis_date() contact_count_plot.set_xlim( [date(year - 1, 12, 16), date(year, 12, 15)] ) # Make a bit of space either side of January and December of the selected year. # Pie chart of all the modes used. mode_count_plot = self.items["YEARLY_STATISTICS"].add_subplot(122) mode_count = self.get_annual_mode_count(year) (patches, texts, autotexts) = mode_count_plot.pie(list(mode_count.values()), labels=mode_count.keys(), autopct='%1.1f%%', shadow=False) for p in patches: # Make the patches partially transparent. p.set_alpha(0.75) mode_count_plot.set_title("Modes used") self.items["YEARLY_STATISTICS"].canvas.draw() return
def display(self, fig, ax, attr, mindate=DATETIME_MIN, maxdate=DATETIME_MAX): """Displays an iterable of clusters in a given datetime range. Parameters ---------- fig : Figure A MatPlotLib figure that will be used for plotting. ax : Axes MatPlotLib axes that will be used for plotting. attr : str The attribute of the cluster that will be plotted. mindate : datetime, optional The minimal datetime that will be displayed. maxdate : datetime, optional The maximal datetime that will be displayed. """ ax.xaxis.set_major_locator(MonthLocator()) ax.xaxis.set_major_formatter(DateFormatter("%Y-%m-%d")) ax.grid(True) ax.set_ylabel(attr) lineformats = cycle(product(LINES, [(r/255., g/255., b/255.) for (r, g, b) in COLORS])) latest_values = {} for cluster in self.clusters: individuals = [ individual for individual in cluster if individual.getDatetime() >= mindate and individual.getDatetime() <= maxdate] dates, values = list(zip(*( (individual.getDatetime(), individual.__dict__[attr]) for individual in individuals if attr in individual.__dict__))) or ([], []) if not values: continue cluster_name = cluster.getName() if len(cluster_name) <= LABEL_MAX_LENGTH: label = cluster_name else: label = cluster_name[:LABEL_MAX_LENGTH - 1] + "…" linefmt, linecolor = next(lineformats) ax.plot_date( dates, values, fmt=linefmt, linewidth=LINEWIDTH, c=linecolor, label=label) latest_values[label] = values[-1] sorted_handles = [ (handle, cluster_name) for handle, cluster_name, _ in sorted([ (handle, label, latest_values[label]) for handle, label in zip(*ax.get_legend_handles_labels()) ], key=lambda x: x[2], reverse=True)] ax.legend( [handle for handle, _ in sorted_handles], [label for _, label in sorted_handles], loc="upper left", bbox_to_anchor=(1, 1)) fig.autofmt_xdate()
def plot_yearly(m, ax=None, uncertainty=True, yearly_start=0, figsize=(10, 6), name='yearly'): """Plot the yearly component of the forecast. Parameters ---------- m: Prophet model. ax: Optional matplotlib Axes to plot on. One will be created if this is not provided. uncertainty: Optional boolean to plot uncertainty intervals. yearly_start: Optional int specifying the start day of the yearly seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts by 1 day to Jan 2, and so on. figsize: Optional tuple width, height in inches. name: Name of seasonality component if previously changed from default 'yearly'. Returns ------- a list of matplotlib artists """ artists = [] if not ax: fig = plt.figure(facecolor='w', figsize=figsize) ax = fig.add_subplot(111) # Compute yearly seasonality for a Jan 1 - Dec 31 sequence of dates. days = (pd.date_range(start='2017-01-01', periods=365) + pd.Timedelta(days=yearly_start)) df_y = seasonality_plot_df(m, days) seas = m.predict_seasonal_components(df_y) artists += ax.plot(df_y['ds'].dt.to_pydatetime(), seas[name], ls='-', c='#0072B2') if uncertainty: artists += [ ax.fill_between(df_y['ds'].dt.to_pydatetime(), seas[name + '_lower'], seas[name + '_upper'], color='#0072B2', 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(name) if m.seasonalities[name]['mode'] == 'multiplicative': ax = set_y_as_percent(ax) return artists
def plot_data(title, region, axe, dates, y): axe.set(title=title) axe.set(xlabel="day from first 100 of Italy") axe.xaxis.set_major_locator(MonthLocator()) locator = DayLocator(range(0, 31, 1)) locator.MAXTICKS = 400 axe.xaxis.set_minor_locator(locator) axe.xaxis.set_major_formatter(DateFormatter('%B')) axe.fmt_xdata = DateFormatter('%B') axe.plot_date(dates, y, label=region, ls='-', marker='.', ms=1)
def dashboardQuery(self): selectedFilter = self.filterSelector.model().data(self.filterSelector.selectedIndexes()[0]) print("Updating dashboard query with Filter " + selectedFilter) figure2 = figure() figure2.clear() ax = figure2.add_subplot(1, 1, 1) ax.xaxis.set_major_locator(YearLocator()) ax.xaxis.set_major_formatter(DateFormatter('%Y')) ax.xaxis.set_minor_locator(MonthLocator()) datalist = [] if selectedFilter == "Basic cumulative": for account in self.account_list: itemsum = 0 for datapoint in self.data_list: if (datapoint[9] == account): itemdate = datetime.strptime(datapoint[2],"%d.%m.%Y") itemsum += datapoint[4] if ((itemdate > self.dabTimeBegin.date()) & (itemdate < self.dabTimeEnd.date())): datalist.append((itemdate, itemsum)) ax.plot([x[0] for x in datalist],[x[1] for x in datalist]) datalist = [] elif selectedFilter == "Basic category shares income": catlist = [] catvaluelist = [] for datapoint in self.data_list: itemdate = datetime.strptime(datapoint[2],"%d.%m.%Y") if ((itemdate > self.dabTimeBegin.date()) & (itemdate < self.dabTimeEnd.date())): if datapoint[4] >=0: if(datapoint[5] not in catlist): catlist.append(datapoint[5]) catvaluelist.append(datapoint[4]) else: catvaluelist[catlist.index(datapoint[5])] += datapoint[4] ax.pie(catvaluelist, labels=catlist) elif selectedFilter == "Basic category shares expenditures": catlist = [] catvaluelist = [] for datapoint in self.data_list: itemdate = datetime.strptime(datapoint[2],"%d.%m.%Y") if ((itemdate > self.dabTimeBegin.date()) & (itemdate < self.dabTimeEnd.date())): if datapoint[4] <=0: if(datapoint[5] not in catlist): catlist.append(datapoint[5]) catvaluelist.append(abs(datapoint[4])) else: catvaluelist[catlist.index(datapoint[5])] += abs(datapoint[4]) ax.pie(catvaluelist, labels=catlist) canvas = FigureCanvasQTAgg(figure2) canvas.draw() for i in range(self.dabQueryCanvas.count()): self.dabQueryCanvas.itemAt(i).widget().close() self.dabQueryCanvas.addWidget(canvas) self.show()
def plot_graph(ax, sd, ed, xlabel, ylabel, title, figname): # ax.set_fontsize(15) ax.xaxis.set_major_locator(MonthLocator()) ax.xaxis.set_major_formatter(DateFormatter('%Y-%b')) plt.gcf().autofmt_xdate() plt.xlim(sd, ed) plt.legend(loc=0) plt.xlabel(xlabel, fontsize=15) plt.ylabel(ylabel, fontsize=15) plt.title(title, fontsize=15) plt.show() plt.savefig(figname)
def wykres_top_60(sumy_przypisu_60, nazwiska_60): plt.style.use('ggplot') fig, ax = plt.subplots() fig.autofmt_xdate() mloc = MonthLocator() ax.tick_params(axis='both', which='major', labelsize=8) ax.xaxis.set_minor_locator(mloc) plt.title('Klienci "Top 60" wg. przypisu w złotych od 2014 roku') plt.plot(nazwiska_60, sumy_przypisu_60, color='#2E8B57', label='zysk = ') plt.show()
def make_date_ticks(ax, fs=12): from matplotlib.dates import YearLocator, MonthLocator, DateFormatter years = YearLocator() months = MonthLocator(range(1, 13), bymonthday=1, interval=2) yearsFmt = DateFormatter('%Y') monthsFmt = DateFormatter("%b") ax.tick_params(axis='x', which='major', labelsize=fs, pad=20) ax.tick_params(axis='x', which='minor', pad=7) ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(yearsFmt) ax.xaxis.set_minor_locator(months) ax.xaxis.set_minor_formatter(monthsFmt)
def create_drop_plot(run_dates, metric, title_string): cmap = plt.cm.get_cmap('Set1') # moving_avg = pd.DataFrame({'dates':run_dates, 'ma':participant_data.mean_metric.rolling(window=7).mean()}) # moving_avg.dates = pd.to_datetime(moving_avg.dates) # moving_avg = moving_avg.set_index(['dates']) # upsampled = moving_avg.resample('D') # interpolated = upsampled.interpolate(method='spline', order = 5) ##upsampled_dates = interpolated.index.values # upsampled_vals = interpolated.ma.values ylims = [0, max([np.nanmax(metric) + 2.5, 15])] xlims = [ min(run_dates) - np.timedelta64(5, "D"), max(run_dates) + np.timedelta64(5, "D") ] mondays = WeekdayLocator(MONDAY) months = MonthLocator(range(1, 13), bymonthday=1) monthsFmt = DateFormatter("%d %b %Y") fig, ax = plt.subplots() #ax.fill_between(xlims, 0, 12, facecolor=cmap(2), alpha=0.5) #ax.fill_between(xlims, 12, 20, facecolor=cmap(4), alpha=0.5) #ax.fill_between(xlims, 20, 100, facecolor=cmap(0), alpha=0.5) ax.axhline(12, color='black', alpha=0.5, linestyle='-.', zorder=0) ax.bar(run_dates, metric, color=cmap(1), edgecolor="white", linewidth=0.1) # ax.plot(upsampled_dates, upsampled_vals) # ax.axhline(np.mean(metric), color = cmap(3), alpha = 0.2) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_major_formatter(monthsFmt) ax.xaxis.set_minor_locator(mondays) ax.set_ylim(ylims[0], ylims[1]) ax.set_xlim(xlims[0], xlims[1]) ax.set_title(title_string, fontsize=14, color='grey') fig.autofmt_xdate() ax.margins(0.01) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) fig.set_size_inches(6, 3.54331) plt.xticks(fontsize=6) if not os.path.exists(FILE_DIR + '/' + str(PARTICIPANT_ID) + '/tmp/images'): os.makedirs(FILE_DIR + '/' + str(PARTICIPANT_ID) + '/tmp/images') plt.savefig(FILE_DIR + '/' + str(PARTICIPANT_ID) + '/tmp/images/drop.png', bbox_inches='tight', dpi=300) fig.autofmt_xdate() plt.show return (fig)
def plot_runoff(ax, crcm5_manager, areas2d, model_data, mask=None): """ model_data - is a Timeseries object of data at i0,j0 grid point """ assert isinstance(ax, Axes) assert isinstance(crcm5_manager, Crcm5ModelDataManager) model_ts = model_data.get_ts_of_daily_means() if mask is None: i_model0, j_model0 = model_data.metadata["ix"], model_data.metadata[ "jy"] mask = crcm5_manager.get_mask_for_cells_upstream(i_model0, j_model0) ts_surf = crcm5_manager.get_daily_means_over_points( mask, "TRUN", level=5, areas2d=areas2d, start_date=model_ts.time[0], end_date=model_ts.time[-1]) ts_dr = crcm5_manager.get_daily_means_over_points( mask, "TDR", level=5, areas2d=areas2d, start_date=model_ts.time[0], end_date=model_ts.time[-1]) # /= 1000.0 -> transfom units mm/s -> m/s ax.plot(ts_surf.time, np.array(ts_surf.data) / 1000.0, color="k", label="Surface") ax.plot(ts_dr.time, np.array(ts_dr.data) / 1000.0, "r", lw=1, label="Subsurface") ax.annotate("r = {0:.2f}".format( float(np.corrcoef([ts_surf.data, ts_dr.data])[0, 1])), xy=(0.1, 0.8), xycoords="axes fraction", zorder=5) ax.set_ylabel("Integrated runoff (m^3/s)") ax.xaxis.set_major_formatter(DateFormatter("%y/%m")) ax.xaxis.set_major_locator(MonthLocator(bymonth=list(range(1, 13, 2)))) ax.legend() pass
def plot_alpha(self, alpha, date_ls, startdate, enddate): startdate = self.datetransfer(startdate) date_ls_change = [] for i in date_ls: if int(i) >= int(startdate) and int(i) <= int(enddate): date_ls_change.append(i) mondays = WeekdayLocator(MONDAY) months = MonthLocator(range(1, 13), bymonthday=1, interval=3) monthsFmt = DateFormatter("%b '%y") #print(date_ls) date = [str(e) for e in date_ls_change] date_ls = [ datetime.datetime.strptime(d, '%Y%m%d').date() for d in date ] algo_pv = alpha['alpha'].tolist() #print(algo_pv) fig, ax = plt.subplots() plt.gca().set_color_cycle(['blue', 'red']) ax.plot_date(date_ls, algo_pv, '-') months.MAXTICKS = 5000 mondays.MAXTICKS = 5000 ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(monthsFmt) ax.xaxis.set_minor_locator(mondays) ax.autoscale_view() ax.grid(True) fig.autofmt_xdate() plt.title('Alpha') plt.legend(['alpha'], loc='upper left') plt.show() #KJ_profit_df=pd.DataFrame(columns=[i/10 for i in range(1,121)]) #for K in list_K: #for J in list_J: #KJ=B(cash,account,startdate,enddate,K,J) #KJ_total_portfolio=KJ.test(startdate,enddate,K,J,cash) #KJ_profit_df.loc[10*J-1,K]=KJ_total_portfolio #KJ_profit_df.to_csv('KJ_finalprofit.csv')
def plot_alpha(self,alpha,date_ls,startdate,enddate): startdate=self.datetransfer(startdate) date_ls_change=[] for i in date_ls: if int(i)>=int(startdate) and int(i)<=int(enddate): date_ls_change.append(i) mondays = WeekdayLocator(MONDAY) months = MonthLocator(range(1, 13), bymonthday=1, interval=3) monthsFmt = DateFormatter("%b '%y") #print(date_ls) date = [str(e) for e in date_ls_change] date_ls = [datetime.datetime.strptime(d,'%Y%m%d').date() for d in date] algo_pv=alpha['alpha'].tolist() #print(algo_pv) fig, ax = plt.subplots() plt.gca().set_color_cycle(['blue', 'red']) ax.plot_date(date_ls, algo_pv,'-') months.MAXTICKS=5000 mondays.MAXTICKS=5000 ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(monthsFmt) ax.xaxis.set_minor_locator(mondays) ax.autoscale_view() ax.grid(True) fig.autofmt_xdate() plt.title('Alpha') plt.legend(['alpha'], loc='upper left') plt.show() #KJ_profit_df=pd.DataFrame(columns=[i/10 for i in range(1,121)]) #for K in list_K: #for J in list_J: #KJ=B(cash,account,startdate,enddate,K,J) #KJ_total_portfolio=KJ.test(startdate,enddate,K,J,cash) #KJ_profit_df.loc[10*J-1,K]=KJ_total_portfolio #KJ_profit_df.to_csv('KJ_finalprofit.csv')
def plot_hydrographs(ax, station, sim_name_to_station_to_model_point, day_stamps=None, sim_names=None): """ Plot climatological hydrographs """ assert isinstance(station, Station) assert isinstance(ax, Axes) years = station.get_list_of_complete_years() #initialize day stamps if it is not passed if day_stamps is None: day_stamps = Station.get_stamp_days(2001) if len(years) < 6: return handles = [] labels = [] dates, obs_data = station.get_daily_climatology_for_complete_years_with_pandas(stamp_dates=day_stamps, years=years) obs_ann_mean = np.mean(obs_data) label = "Obs: ann.mean = {0:.1f}".format(obs_ann_mean) h = ax.plot(dates, obs_data, "k", lw=2, label=label) handles.append(h[0]) labels.append(label) mp = None for sim_name in sim_names: if station in sim_name_to_station_to_model_point[sim_name]: continue mps = sim_name_to_station_to_model_point[sim_name][station] for mp in mps: assert isinstance(mp, ModelPoint) dates, values = mp.get_daily_climatology_for_complete_years(stamp_dates=day_stamps, varname="STFL") label = "{0}: {1:.2f} \n ann.mean = {2:.1f}".format(sim_name, mp.mean_upstream_lake_fraction, np.mean(values)) h = ax.plot(dates, values, label=label, lw=3) handles.append(h[0]) labels.append(label) ax.xaxis.set_major_formatter(DateFormatter("%d\n%b")) ax.xaxis.set_major_locator(MonthLocator(bymonth=list(range(1, 13, 3)), bymonthday=15)) if mp is None: return ax.set_title("{0}: point lake fr.={1:.2f}".format(station.id, mp.lake_fraction)) return labels, handles
def plot_nightly(timecut, blocks=None, prior=None, source='Fact-Source', as_block=False): plt.figure(figsize=(10, 4)) plot_dataframe(timecut, source, alpha=0.6) if as_block: plot_dataframe_as_block(blocks) else: plot_blocks(timecut, blocks, prior=prior) ax = plt.gca() ax.xaxis.set_minor_locator(MonthLocator(bymonth=(3, 5, 9, 11), bymonthday=(1, 1, 1, 1))) ax.xaxis.set_major_locator(MonthLocator(bymonth=(1, 7), bymonthday=(1, 1))) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m')) plt.grid(True, which='major') plt.grid(True, which='minor', linewidth=0.2, linestyle="--") plt.xlabel("Time") plt.ylabel("Excess rate Evts/h") plt.legend() #plt.grid() plt.tight_layout()
def SetDateAxis(ax, form): if "year" in form: formatter = DateFormatter('%Y') rule = rrulewrapper(YEARLY, byeaster=1, interval=5) loc = RRuleLocator(rule) if "month" in form: formatter = DateFormatter('%Y-%m') loc = MonthLocator(interval=4) ax.xaxis.set_major_locator(loc) ax.xaxis.set_major_formatter(formatter) plt.xticks(rotation=20) plt.tight_layout()
def plot_with_dates_no_show(dates, data): fig, ax = plt.subplots() ax.plot_date(dates, data) ax.xaxis.set_major_locator(YearLocator()) ax.xaxis.set_major_formatter(DateFormatter('%Y')) ax.xaxis.set_minor_locator(MonthLocator()) ax.autoscale_view() fig.autofmt_xdate() ax.fmt_xdata = DateFormatter('%Y-%m-%d') ax.grid(True)
def extraPlots(): import datetime from matplotlib.dates import MONDAY, MonthLocator, WeekdayLocator, DateFormatter #converts dates to format matplotlib understands... time = P.date2num(data[:, dict['DateTimeUT']]) mondays = WeekdayLocator(MONDAY) months = MonthLocator(range(1, 13, 2), bymonthday=2) monthsFmt = DateFormatter("%b '%y") y2007 = datetime.date(2007, 1, 1) y2008 = datetime.date(2008, 1, 1) y2007plot = P.date2num(y2007) y2008plot = P.date2num(y2008) widening = 5. fig = P.figure() P.subplots_adjust(hspace=0.1) ax = fig.add_subplot(211) P.title('ALFOSC focus pyramid data') ax.plot_date(time, telfocusOld, 'wo', xdate=True) ax.plot_date(time, telfocusCorrected, 'bo') ax.axhline(medianNew, color='b', label='New Median', lw=1., ls='-') ax.axhline(medianOld, color='r', label='Old Median', lw=1., ls='--') ax.axvline(y2007plot, color='k') ax.axvline(y2008plot, color='k') ax.legend(shadow=True, loc='best') P.ylabel('Telescope Focus + Median Offset') P.xlim(min(time) - widening, max(time) + widening) P.ylim(23300., 23500.) ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(monthsFmt) ax.xaxis.set_minor_locator(mondays) fig.autofmt_xdate() bx = fig.add_subplot(212) bx.plot_date(time, data[:, dict['TempInAirDegC']], fmt='ro', xdate=True) bx.axhline(0.) bx.axvline(y2007plot, color='k') bx.axvline(y2008plot, color='k') bx.xaxis.set_major_locator(months) bx.xaxis.set_major_formatter(monthsFmt) bx.xaxis.set_minor_locator(mondays) P.xlim(min(time) - widening, max(time) + widening) P.ylabel('Temperature In Air (DegC)') fig.autofmt_xdate() fig.savefig('foc-pyr_time.png') P.close()
def plot(self, db_path, label='time', ax=None, title=True, y='timing', ylabel='miliseconds'): import matplotlib.pyplot as plt from matplotlib.dates import MonthLocator, DateFormatter results = self.get_results(db_path) if ax is None: fig = plt.figure() ax = fig.add_subplot(111) timing = results[y] if self.start_date is not None: timing = timing.truncate(before=self.start_date) timing.plot(ax=ax, style='b-', label=label) ax.set_xlabel('Date') ax.set_ylabel(ylabel) if self.logy: ax2 = ax.twinx() try: timing.plot(ax=ax2, label='%s (log scale)' % label, style='r-', logy=self.logy) ax2.set_ylabel(ylabel + ' (log scale)') ax.legend(loc='best') ax2.legend(loc='best') except ValueError: pass ylo, yhi = ax.get_ylim() if ylo < 1: ax.set_ylim([0, yhi]) formatter = DateFormatter("%b %Y") ax.xaxis.set_major_locator(MonthLocator()) ax.xaxis.set_major_formatter(formatter) ax.autoscale_view(scalex=True) if title: ax.set_title(self.name) return ax
def example3(): """Customize major tick and minor tick """ ### generate data date1 = date(1995, 1, 1) date2 = date(2004, 4, 12) total_days = (date2 - date1).days dates = [date1 + i * timedelta(1) for i in range(total_days)] opens = np.random.randn(total_days) fig, ax = plt.subplots() ax.plot_date(dates, opens, "-") # format the ticks years = YearLocator() # every year months = MonthLocator( [4, 7, 10]) # range(1,13) = everymonth, [4,7,10] means draw a tick at # 3, 6, 9 = every quarter yearsFmt = DateFormatter("%Y") # the text on time axis major ticker monthFmt = DateFormatter("%m") # the text on time axis minor ticker ax.xaxis.set_major_locator(years) # set major locator ax.xaxis.set_major_formatter(yearsFmt) # set major formatter ax.xaxis.set_minor_locator(months) # set minor locator ax.xaxis.set_minor_formatter(monthFmt) # set minor formatter ax.autoscale_view() # format the coords message box def price(x): return "$%1.2f" % x ax.fmt_xdata = DateFormatter("%Y-%m-%d") ax.fmt_ydata = price # fig.autofmt_xdate() # automatically format x axis plt.ylim([-10, 10]) # set y axis limit # 只打开x的grid ax.grid(which="major", axis="x", color="gray", linestyle="-", linewidth=2) # set major grid ax.grid(which="minor", axis="x", color="black", linestyle="--", linewidth=1) # set minor grid # plt.xticks(rotation="vertical") # if you only have major tick to rotate, you can use this plt.setp(ax.xaxis.get_majorticklabels(), rotation=90) plt.setp(ax.xaxis.get_minorticklabels(), rotation=90) plt.show()
def plot(self, xdata=None, ydata=None, ydata2=None, ydata3=None, ylabel=None, ylabel2=None, ylabel3=None, **kwargs): fig = plt.figure(1) ax1 = plt.subplot2grid((3, 1), (0, 0), colspan=1, rowspan=1) p1 = ax1.plot(xdata, ydata, self.plotstyle, markersize=2) ax1.set_ylim([np.nanmin(ydata), np.nanmax(ydata)]) ax1.set_xlim([np.nanmin(xdata), np.nanmax(xdata)]) plt.ylabel(ylabel) ax1.xaxis.set_major_locator(MonthLocator()) ax1.xaxis.set_minor_locator(MonthLocator(bymonthday=15)) ax1.xaxis.set_major_formatter(ticker.NullFormatter()) ax1.xaxis.set_minor_formatter(DateFormatter('%b %y')) ax1.tick_params(axis='both', which='minor', labelsize=self.labelsize) ax1.tick_params(axis='x', which='both', bottom='off', labelbottom='off') ax1.spines['bottom'].set_visible(False) ax2 = plt.subplot2grid((3, 1), (1, 0), colspan=1, rowspan=1) p2 = ax2.plot(xdata, ydata2, self.plotstyle, markersize=2) ax2.set_ylim([np.nanmin(ydata2), np.nanmax(ydata2)]) ax2.set_xlim([np.nanmin(xdata), np.nanmax(xdata)]) plt.ylabel(ylabel2) ax2.xaxis.set_major_locator(MonthLocator()) ax2.xaxis.set_minor_locator(MonthLocator(bymonthday=15)) ax2.xaxis.set_major_formatter(ticker.NullFormatter()) ax2.xaxis.set_minor_formatter(DateFormatter('%b %y')) ax2.tick_params(axis='both', which='minor', labelsize=self.labelsize) ax2.tick_params(axis='x', which='both', top='off', bottom='off', labelbottom='off') ax2.spines['top'].set_visible(False) ax2.spines['bottom'].set_visible(False) ax3 = plt.subplot2grid((3, 1), (2, 0), colspan=1, rowspan=1) p2 = ax3.plot(xdata, ydata3, self.plotstyle, markersize=2) ax3.set_ylim([np.nanmin(ydata3), np.nanmax(ydata3)]) ax3.set_xlim([np.nanmin(xdata), np.nanmax(xdata)]) plt.ylabel(ylabel3) ax3.xaxis.set_major_locator(MonthLocator()) ax3.xaxis.set_minor_locator(MonthLocator(bymonthday=15)) ax3.xaxis.set_major_formatter(ticker.NullFormatter()) ax3.xaxis.set_minor_formatter(DateFormatter('%b %y')) ax3.tick_params(axis='both', which='minor', labelsize=self.labelsize) ax3.tick_params(axis='x', which='both', top='off') ax3.spines['top'].set_visible(False) return plt, fig
def plot_timeline_table(gf): ''' Timeline with summary table ''' dfA = gf.query('platform == "Sentinel-1A"') dfAa = dfA.query(' flightDirection == "ASCENDING" ') dfAd = dfA.query(' flightDirection == "DESCENDING" ') dfB = gf.query('platform == "Sentinel-1B"') dfBa = dfB.query(' flightDirection == "ASCENDING" ') dfBd = dfB.query(' flightDirection == "DESCENDING" ') # summary table dfS = pd.DataFrame(index=gf.relativeOrbit.unique()) dfS['Start'] = gf.groupby('relativeOrbit').sceneDateString.min() dfS['Stop'] = gf.groupby('relativeOrbit').sceneDateString.max() dfS['Dates'] = gf.groupby('relativeOrbit').sceneDateString.nunique() dfS['Frames'] = gf.groupby('relativeOrbit').sceneDateString.count() dfS['Direction'] = gf.groupby('relativeOrbit').flightDirection.first() dfS['UTC'] = gf.groupby('relativeOrbit').utc.first() dfS.sort_index(inplace=True, ascending=False) dfS.index.name = 'Orbit' # Same colors as map orbits = gf.relativeOrbit.unique() colors = plt.cm.jet(np.linspace(0,1, orbits.size)) fig,ax = plt.subplots(figsize=(11,8.5)) #plt.scatter(dfA.timeStamp.values, dfA.orbitCode.values, c=dfA.orbitCode.values, cmap='jet', s=60, label='S1A') #plt.scatter(dfB.timeStamp.values, dfB.orbitCode.values, c=dfB.orbitCode.values, cmap='jet', s=60, marker='d',label='S1B') plt.scatter(dfAa.timeStamp.values, dfAa.orbitCode.values, c=colors[dfAa.orbitCode.values], cmap='jet', s=60, facecolor='none', label='S1A') plt.scatter(dfBa.timeStamp.values, dfBa.orbitCode.values, c=colors[dfBa.orbitCode.values], cmap='jet', s=60, facecolor='none', marker='d',label='S1B') plt.scatter(dfAd.timeStamp.values, dfAd.orbitCode.values, c=colors[dfAd.orbitCode.values], cmap='jet', s=60, label='S1A') plt.scatter(dfBd.timeStamp.values, dfBd.orbitCode.values, c=colors[dfBd.orbitCode.values], cmap='jet', s=60, marker='d',label='S1B') plt.yticks(gf.orbitCode.unique(), gf.relativeOrbit.unique()) #plt.axvline('2016-04-22', color='gray', linestyle='dashed', label='Sentinel-1B launch') # Add to plot! as a custom legend table(ax, dfS, loc='top', zorder=10, fontsize=12, cellLoc = 'center', rowLoc = 'center', bbox=[0.1, 0.7, 0.6, 0.3] )#[left, bottom, width, height]) ax.xaxis.set_minor_locator(MonthLocator()) ax.xaxis.set_major_locator(YearLocator()) plt.legend(loc='upper right') plt.ylim(-1,orbits.size+3) plt.ylabel('Orbit Number') fig.autofmt_xdate() plt.title('Sentinel-1 timeline') plt.savefig('timeline_with_table.pdf', bbox_inches='tight')
def plot_yearly(m, comp_name="yearly", yearly_start=0, quick=True, ax=None, figsize=(10, 6)): """Plot the yearly component of the forecast. Args: m (NeuralProphet): fitted model. ax (matplotlib axis): matplotlib Axes to plot on. One will be created if this is not provided. yearly_start (int): specifying the start day of the yearly seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts by 1 day to Jan 2, and so on. quick (bool): use quick low-evel call of model. might break in future. figsize (tuple): width, height in inches. Ignored if ax is not None. default: (10, 6) comp_name (str): Name of seasonality component if previously changed from default 'yearly'. Returns: a list of matplotlib artists """ artists = [] if not ax: fig = plt.figure(facecolor="w", figsize=figsize) ax = fig.add_subplot(111) # Compute yearly seasonality for a Jan 1 - Dec 31 sequence of dates. days = pd.date_range(start="2017-01-01", periods=365) + pd.Timedelta(days=yearly_start) df_y = pd.DataFrame({"ds": days}) if quick: predicted = predict_season_from_dates(m, dates=df_y["ds"], name=comp_name) else: predicted = m.predict_seasonal_components(df_y)[comp_name] artists += ax.plot(df_y["ds"].dt.to_pydatetime(), predicted, ls="-", c="#0072B2") 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("Seasonality: {}".format(comp_name)) return artists
def create_figure(df, DF, inps): ''' Graphical representation of pairs to make ''' #Neater dfA = df.query('satellite == "S1A"').drop_duplicates('date').reset_index( drop=True) dfB = df.query('satellite == "S1B"').drop_duplicates('date').reset_index( drop=True) print('S1A acquisitions: ', len(dfA)) print('S1B acquisitions: ', len(dfB)) fig, ax = plt.subplots(figsize=(12, 4)) plt.plot(dfA.date, dfA.ones, 'mo', label='S1A') plt.plot(dfB.date, dfB.ones, 'co', label='S1B') plt.legend() plt.yticks([ 1, ], ['']) plt.ylim(0, 2) #NOTE: could annotate full dates with vertical text ''' for i,row in DF.iterrows(): #print(row.date, row.date.strftime('%Y-%m-%d')) plt.text(row.date, 0.9, row.date.strftime('%m-%d'), ha='center', rotation=90) ''' #show connections n = len(DF) for i in range(n - inps.separation): # Sequential (e.g. 12 day) ann = ax.annotate( '', xy=(DF.date.iloc[i], 1.), xycoords='data', xytext=(DF.date.iloc[i + inps.separation], 1), textcoords='data', arrowprops=dict(arrowstyle="-", connectionstyle="arc3,rad=0.8"), ) ax = plt.gca() ax.xaxis.set_minor_locator(MonthLocator()) ax.xaxis.set_major_locator(YearLocator()) ax.fmt_xdata = DateFormatter('%Y-%m-%d') fig.autofmt_xdate() plt.title('Acquisitions={}, Pairs={}'.format(n, n - inps.separation)) plt.savefig('acquisition_timeline.pdf', bbox_inches='tight')
def plot_common(ax1, subtit): ax1.set_title(subtit, fontsize=13, x=0, ha='left') ax1.xaxis.set_major_formatter(DateFormatter("%Y\n%b")) ax1.xaxis.set_minor_locator(MonthLocator()) ax1.set_ylim(-2.5, 3.5) ax1.yaxis.set_minor_locator(AutoMinorLocator(2)) ax1.set_ylabel('RMM PC1', fontsize=11) ax1.grid() ax1.axhline(y=0, c='k', lw=0.8) ax1.tick_params(axis='both', labelsize=10) return
def plot2dvar(data, x, y): """ For plotting imshow of adcp data """ fig = plt.figure(33) ax = plt.subplot(1, 1, 1) csf = plt.imshow(data.T, cmap='jet', aspect='auto', origin='lower', extent=[x.min(), x.max(), y.min(), y.max()]) ax.set_ylim(ax.get_ylim() [::-1]) #this reverses the yaxis (i.e. deep at the bottom) cbar = plt.colorbar() ax.xaxis.set_minor_locator(MonthLocator(bymonthday=(1, 15))) ax.xaxis.set_major_locator(MonthLocator(bymonthday=1, interval=2)) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) fig.autofmt_xdate() DefaultSize = fig.get_size_inches() fig.set_size_inches((DefaultSize[0] * 2, DefaultSize[1])) return (plt, fig)
def apply_date_xticks(self, ax=None, major_unit='week', minor_unit='day', major_format="%Y-%m-%d", xdata=None): """ Params: major_unit: major locator unit, could be {month, day, week, hour, minute} minor_unit: minor locator unit, """ locators = { "month": MonthLocator(), "month3": MonthLocator(bymonth=[1,4,7,10]), "week": WeekdayLocator(MONDAY), "day": DayLocator(), "hour": HourLocator(), "minute": MinuteLocator } ax = plt.gca() if ax is None else ax ax.xaxis.set_major_locator(locators[major_unit]) if minor_unit is not None: ax.xaxis.set_minor_locator(locators[minor_unit]) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) ax.margins(x=0) plt.setp(plt.gca().get_xticklabels(), fontsize=self.fontsize, rotation=30, horizontalalignment='right') if xdata is not None: return self.__try_convert_as_mdate(xdata)
def getDatasForOneRouteForOneDepartureDate(route, departureDate): X = getOneRouteData(datas, route) minDeparture = np.amin(X[:, 8]) maxDeparture = np.amax(X[:, 8]) print minDeparture print maxDeparture # get specific departure date datas X = X[np.where(X[:, 8] == departureDate)[0], :] # get the x values xaxis = X[:, 9] # observed date state print xaxis xaxis = departureDate - 1 - xaxis print xaxis tmp = xaxis startdate = "20151109" xaxis = [ pd.to_datetime(startdate) + pd.DateOffset(days=state) for state in tmp ] print xaxis # get the y values yaxis = X[:, 12] # every monday mondays = WeekdayLocator(MONDAY) # every 3rd month months = MonthLocator(range(1, 13), bymonthday=1, interval=01) days = WeekdayLocator(byweekday=1, interval=2) monthsFmt = DateFormatter("%b. %d, %Y") fig, ax = plt.subplots() ax.plot_date(xaxis, yaxis, 'r--') ax.plot_date(xaxis, yaxis, 'bo') ax.xaxis.set_major_locator(days) ax.xaxis.set_major_formatter(monthsFmt) #ax.xaxis.set_minor_locator(mondays) ax.autoscale_view() #ax.xaxis.grid(False, 'major') #ax.xaxis.grid(True, 'minor') ax.grid(True) plt.xlabel('Date') plt.ylabel('Price in Euro') fig.autofmt_xdate() plt.show() """
def to_datenum2(s): d,m,y = s.split('-') y = int(y) if y>10: y+=1900 else: y+= 2000 return date2num(datetime.date(y, months[m], int(d))) ## snippet 3 - customizing a plot # grids, labels and titles ax1.grid(True) ax2.grid(True) ax1.set_ylabel('Closing price') ax2.set_ylabel('Daily volume') ax1.set_title('Closing prices of %s'%self.dailydata.ticker) # use nicer tick locating and formatting from matplotlib.dates import DateFormatter, MonthLocator from matplotlib.ticker import FuncFormatter, ScalarFormatter #tickloc = MonthLocator() tickloc = MonthLocator((1,4,7,10)) tickfmt = DateFormatter('%b %Y') ax2.xaxis.set_major_formatter(tickfmt) ax2.xaxis.set_major_locator(tickloc) def fmt_millions(x, pos=None): return '%d'%int(x/1e6) class PriceFormatter(ScalarFormatter): def __call__(self, x, pos): if pos==0: return '' else: return ScalarFormatter.__call__(self, x, pos) ax1.yaxis.set_major_formatter(PriceFormatter()) ax2.yaxis.set_major_formatter(FuncFormatter(fmt_millions)) # fix the toolbar formatting ax1.fmt_xdata = DateFormatter('%Y-%m-%d') ax2.fmt_xdata = DateFormatter('%Y-%m-%d') # make the upper ticks invisible, the lower ticks rotated, and # adjust the subplot params for label in ax1.xaxis.get_ticklabels(): label.set_visible(False) for label in ax2.xaxis.get_ticklabels(): label.set_rotation(40) fig.subplots_adjust(bottom=0.15, hspace=0.05)
def eg9_16(): """ 9.16 动手实践:根据条件进行着色 假设你想对股票曲线图进行着色,并将低于均值和高于均值的收盘价填充为不同颜色。 fill_between函数是完成这项工作的最佳选择。我们仍将省略下载一年以来历史数据、提取日 期和收盘价数据以及创建定位器和日期格式化器的步骤。 """ # (1) 加载苹果的股票信息,并转化成numpy df_stock = pd.read_csv('output/AAPL.csv', header=0, index_col=None) quotes = [] for i in range(df_stock.shape[0]): # 遍历每行,shape为dataframe大小(x,y),表示x行y列 if i == 0: # 将交易日期日期转为数字 date_num = date2num(datetime.strptime(df_stock.ix[[i]].values[0][0], '%Y-%m-%d')) # 1表示第一列,为交易日 date_plt = date_num else: date_plt = date_num + i # 由于csv文件中日期为升序排序,这里为加号 open = df_stock.ix[[i]].values[0][1] # 开盘价: i行第2列 close = df_stock.ix[[i]].values[0][2] # 收盘价:i行第3列 high = df_stock.ix[[i]].values[0][3] # 最高价:i行第4列 low = df_stock.ix[[i]].values[0][4] # 最低价:i行第5列 datas = (date_plt, open, close, high, low) quotes.append(datas) quotes = np.array(quotes) dates = quotes.T[0] close = quotes.T[2] alldays = DayLocator() months = MonthLocator() month_formatter = DateFormatter("%b %Y") # (2) 创建一个Matplotlib的figure对象。 fig = plt.figure() # (3) 在图像中添加一个子图。 ax = fig.add_subplot(111) # (4) 绘制收盘价数据。 ax.plot(dates, close) # (5) 对收盘价下方的区域进行着色,依据低于或高于平均收盘价使用不同的颜色填充。 plt.fill_between(dates, close.min(), close, where=close > close.mean(), facecolor="green", alpha=0.4) plt.fill_between(dates, close.min(), close, where=close < close.mean(), facecolor="red", alpha=0.4) # (6) 现在,我们将设置定位器并将x轴格式化为日期,从而完成绘制。 ax.xaxis.set_major_locator(months) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(month_formatter) ax.grid(True) fig.autofmt_xdate() plt.show()
def plot(self,transactions=None,months=6): """Plot balance v. time""" print('months',months) self.figure.clf() if transactions is None: transactions=self.transactions #ax=pyfin.linePlot(transactions) ax=self.figure.add_subplot(111) #self.figure.axes.append(ax) if False: dates,data=[[],{}] month,year=[datetime.datetime.today().month,datetime.datetime.today().year] for q in transactions.types: data[q]=[] for i in range(month-months+1,month+1): dates.append(datetime.datetime(year-int((i%12-i)/12),int(i%12),1)) rawd=list(zip(*transactions.analyzeMonth(year-int((i%12-i)),int(i%12))['totals'])) for c in transactions.types: if rawd!=[] and c in rawd[1]: data[c].append(abs(rawd[0][rawd[1].index(c)])) else: data[c].append(0) dates,data=transactions.getMonthlyExpenditures(months) dath,datl=[{},{}] # bin data into high (>threshold), low (<threshold), and get rid of zeros for q in data: if sum(data[q])>100: dath[q]=data[q] elif sum(data[q])<100: datl[q]=data[q] months=MonthLocator(range(1,13),bymonthday=1,interval=1) monthsFmt=DateFormatter('%b %y') for l in dath: #fig,ax=plt.subplots() ax.plot_date(dates,dath[l],'-',label=l) ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(monthsFmt) ax.autoscale_view() ax.grid(True) ax.legend() self.figure.autofmt_xdate() #plt.show() self.draw() return