我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.axvline()。
def data_visualization(co_price, pcb_price): """ ??????? """ x_co_values = co_price.index y_co_values = co_price.price / 100 x_pcb_values = pcb_price.index y_pcb_values = pcb_price.price plt.figure(figsize=(10, 6)) plt.title('copper price(100rmb/t) vs. pcb price(rmb/sq.m.)') plt.xlabel('date') plt.ylabel('history price') plt.plot(x_co_values, y_co_values, '-', label='co price') plt.plot(x_pcb_values, y_pcb_values, '-', label='pcb price') plt.axvline('2015-04-23', linewidth=1, color='r', linestyle='dashed') plt.axvline('2015-10-23', linewidth=1, color='r', linestyle='dashed') plt.axvline('2016-04-23', linewidth=1, color='r', linestyle='dashed') plt.axvline('2016-10-23', linewidth=1, color='r', linestyle='dashed') plt.legend(loc='upper right') plt.show()
def get_reward(new_state, time_step, action, xdata, signal, terminal_state, eval=False, epoch=0): reward = 0 signal.fillna(value=0, inplace=True) if eval == False: bt = twp.Backtest(pd.Series(data=[x for x in xdata[time_step-2:time_step]], index=signal[time_step-2:time_step].index.values), signal[time_step-2:time_step], signalType='shares') reward = ((bt.data['price'].iloc[-1] - bt.data['price'].iloc[-2])*bt.data['shares'].iloc[-1]) if terminal_state == 1 and eval == True: #save a figure of the test set bt = twp.Backtest(pd.Series(data=[x for x in xdata], index=signal.index.values), signal, signalType='shares') reward = bt.pnl.iloc[-1] plt.figure(figsize=(3,4)) bt.plotTrades() plt.axvline(x=400, color='black', linestyle='--') plt.text(250, 400, 'training data') plt.text(450, 400, 'test data') plt.suptitle(str(epoch)) plt.savefig('plt/'+str(epoch)+'.png', bbox_inches='tight', pad_inches=1, dpi=72) plt.close('all') #print(time_step, terminal_state, eval, reward) return reward
def plotNucProfile(values, output): plt.figure(figsize=(16, 4)) plt.plot(values) plt.xlim([0,292]) center = 147-1 plt.xticks([0,center-93, center-73,center, center+73,center+93, 292],['\nUpstream','93','73\nStart','0\nCenter','73\nEnd','93','\nDownstream']) plt.axvline(x=center-93, linewidth=1, ls='--', color = 'k') plt.axvline(x=center-73, linewidth=1, ls='--', color = 'k') plt.axvline(x=center, linewidth=1, ls='--', color = 'k') plt.axvline(x=center+73, linewidth=1, ls='--', color = 'k') plt.axvline(x=center+93, linewidth=1, ls='--', color = 'k') plt.title("Nucleosome Profile") plt.xlabel("Nucleosome BP Position") plt.ylabel("Ratio") plt.savefig(output, dpi=400)
def plotGPGO(gpgo, param): param_value = list(param.values())[0][1] x_test = np.linspace(param_value[0], param_value[1], 1000).reshape((1000, 1)) hat = gpgo.GP.predict(x_test, return_std=True) y_hat, y_std = hat[0], np.sqrt(hat[1]) l, u = y_hat - 1.96 * y_std, y_hat + 1.96 * y_std fig = plt.figure() r = fig.add_subplot(2, 1, 1) r.set_title('Fitted Gaussian process') plt.fill_between(x_test.flatten(), l, u, alpha=0.2) plt.plot(x_test.flatten(), y_hat, color='red', label='Posterior mean') plt.legend(loc=0) a = np.array([-gpgo._acqWrapper(np.atleast_1d(x)) for x in x_test]).flatten() r = fig.add_subplot(2, 1, 2) r.set_title('Acquisition function') plt.plot(x_test, a, color='green') gpgo._optimizeAcq(method='L-BFGS-B', n_start=1000) plt.axvline(x=gpgo.best, color='black', label='Found optima') plt.legend(loc=0) plt.tight_layout() plt.savefig(os.path.join(os.getcwd(), 'mthesis_text/figures/chapter3/sine/{}.pdf'.format(i))) plt.show()
def plotGPGO(gpgo, param, index, new=True): param_value = list(param.values())[0][1] x_test = np.linspace(param_value[0], param_value[1], 1000).reshape((1000, 1)) y_hat, y_var = gpgo.GP.predict(x_test, return_std=True) std = np.sqrt(y_var) l, u = y_hat - 1.96 * std, y_hat + 1.96 * std if new: plt.figure() plt.subplot(5, 1, 1) plt.fill_between(x_test.flatten(), l, u, alpha=0.2) plt.plot(x_test.flatten(), y_hat) plt.subplot(5, 1, index) a = np.array([-gpgo._acqWrapper(np.atleast_1d(x)) for x in x_test]).flatten() plt.plot(x_test, a, color=colors[index - 2], label=acq_titles[index - 2]) gpgo._optimizeAcq(method='L-BFGS-B', n_start=1000) plt.axvline(x=gpgo.best) plt.legend(loc=0)
def plot_coefficient(self, feature): from scipy.stats import t import matplotlib.pyplot as plt x = np.linspace(-5.0, 5.0) t_score = self.t[self.features.index(feature)] # At what point is the 5% percentile? t_05 = t.ppf(0.05, self.df) # At what point is the 95% percentile? t_95 = t.ppf(0.95, self.df) plt.axvline(x=t_05) plt.axvline(x=t_95) plt.scatter(t_score, t.pdf(t_score, self.df), marker='o', color='red') plt.plot(x, t.pdf(x, self.df), color='gray', lw=5, alpha=0.6) plt.title('t-distribtion for {0} coefficient'.format(feature)) plt.show()
def plot_rss(cm, t1, t2, t3): """Plot the memory profile.""" f = plt.figure(figsize=(8, 6)) plt.plot(range(cm.cpu.shape[0]), cm.rss / 1000000) plt.axvline(t1 - 3, color='darkcyan', linestyle='--', linewidth=1.0, label='load data') plt.axvline(t2, color='blue', linestyle='--', linewidth=1.0, label='fit start') plt.axvline(t3, color='blue', linestyle='-.', linewidth=1.0, label='fit end') plt.xticks([i for i in [0, 50, 100, 150, 200, 250]], [i for i in [0, 5, 10, 15, 20, 25]]) # plt.ylim(120, 240) plt.title("ML-Ensemble memory profile (working set)") plt.ylabel("Working set memory (MB)") plt.xlabel("Time (s)") plt.legend() plt.show() if PRINT: try: f.savefig("dev/img/memory_profile.png", dpi=600) except: f.savefig("memory_profile.png", dpi=600)
def plot_cpu(cm, t1, t2, t3): """Plot the CPU profile.""" f = plt.figure() plt.plot(range(cm.cpu.shape[0]), cm.cpu) plt.axvline(t1 - 3, color='darkcyan', linestyle='--', linewidth=1.0, label='load data') plt.axvline(t2, color='blue', linestyle='--', linewidth=1.0, label='fit start') plt.axvline(t3, color='blue', linestyle='-.', linewidth=1.0, label='fit end') plt.xticks([i for i in [0, 50, 100, 150, 200, 250]], [i for i in [0, 5, 10, 15, 20, 25]]) plt.title("ML-Ensemble CPU profile") plt.ylabel("CPU utilization (%)") plt.xlabel("Time (s)") plt.legend() if PRINT: try: f.savefig("dev/cpu_profile.png", dpi=600) except: f.savefig("cpu_profile.png", dpi=600)
def plot(self, title_comment=""): """ plot inner variables that to be optimized Args: title_comment (str) : string for title """ plt.figure() plt.title("OpenGoddard inner variables" + title_comment) plt.plot(self.p, "o") plt.xlabel("variables") plt.ylabel("value") for section in range(self.number_of_section): for line in self.div[section]: plt.axvline(line, color="C%d" % ((section+1) % 6), alpha=0.5) plt.grid()
def runobsplot(self): """ A quick histogram to see that intrinsic variance compared to the initial estimate """ tdmin = self.iniest.td - 3.0*self.iniest.tderr tdmax = self.iniest.td + 3.0*self.iniest.tderr fig = plt.figure(figsize=(6, 3)) fig.subplots_adjust(top=0.95, bottom=0.2) if len(self.obsmesdelays) != 0: plt.hist(self.obsmesdelays, range=(tdmin, tdmax), bins=200, color="green", lw=0) plt.xlim(tdmin, tdmax) plt.xlabel("Delay [day]") plt.ylabel("Counts") #ax = plt.gca() plt.figtext(0.15, 0.8, "Intrinsic/initial error ratio: %.2f" % self.intrinsicratio) plt.axvline(self.iniest.td - self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axvline(self.iniest.td + self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axvline(self.outest.td, color="red", linestyle="-", zorder=20) plt.savefig(os.path.join(self.plotdir, "intrinsic_variance.png")) plt.close()
def hist_plot(hist_out): #Visualize histogram. plt.figure() df = pd.read_csv(hist_out,sep='\t',header=0,names=['Distance from TSS','Coverage','+ Tags','- Tags']) plt.plot(df['Distance from TSS'],df['+ Tags'],label='+ Tags') plt.plot(df['Distance from TSS'],df['- Tags'],label='- Tags') plt.xlim([-500,500]) plt.xlabel('Distance from TSS') plt.ylabel('Reads per bp per TSS') plt.axvline(x=0,c='k') plt.legend(loc='upper right') plt.savefig(os.path.splitext(hist_out)[0]+'.png') # if __name__ == '__main__': # import glob # hists = glob.glob('/data/shangzhong/TSS/fq/f03_tags/*/hist.txt') # for h in hists: # plt.figure() # hist_plot(h)
def sdss_plot_velocity(wave, interest_wave, flux, name, target): # define the velocity scale vel_aas = (wave/(1+z) - interest_wave) * c / interest_wave # convert to [km / s] vel_kms = vel_aas.to('km/s') #define parameters for the x and y axes ax.set_xlim(xmin, xmax) ax.xaxis.set_minor_locator(minorLocator) ax.tick_params(axis='x', labelsize=7) ax.set_ylim(0., 15.) # make the plot ax.plot(vel_kms, flux) # include the name of the line plt.text(xmin+0.03*(xmax-xmin), 0.15, name) # mark the approximate velocities of interest plt.axvline(x=target, ymin=0., ymax = 15., linewidth=1, color='k', linestyle='dotted') plt.axvline(x=target +30., ymin=0., ymax = 15., linewidth=0.5, color='k') plt.axvline(x=target -30., ymin=0., ymax = 15., linewidth=0.5, color='k')
def plot_profile(wave, flux, line, name): # define the velocity scale [AA / s] vel_aas = (wave - line*(1+zem[i])) / (line*(1+zem[i])) * c # convert to [km / s] vel_kms = vel_aas.to('km/s') # define parameters for the x and y axes ax.set_xlim(xmin, xmax) ax.xaxis.set_minor_locator(minorLocator) ax.tick_params(axis='x', labelsize=xls) ax.set_ylim(0., 1.5) # make the plot ax.plot(vel_kms, flux) # include the name of the line plt.text(xmin+0.03*(xmax-xmin), 0.15, name) # mark the approximate centroid velocity plt.axvline(x=vcen[i], ymin=0., ymax = 1.5, linewidth=1, color='k', linestyle='dotted') plt.axvline(x=vcen[i]+30., ymin=0., ymax = 1.5, linewidth=0.5, color='k') plt.axvline(x=vcen[i]-30., ymin=0., ymax = 1.5, linewidth=0.5, color='k') # label other lines for clarity for k in range(0, len(lines)): vel_off_aas = (lines[k] - line) / line * c vel_off_kms = vel_off_aas.to('km/s') / (u.km / u.s) plt.axvline(x=vcen[i]+vel_off_kms, ymin=0., ymax = 1.5, linewidth=1, color='k', linestyle='dotted') # define the data directory
def plot_2D_contour(states,p,labels,inter=False): import pylab as pl from pyme.statistics import expectation as EXP exp = EXP((states,p)) X = np.unique(states[0,:]) Y = np.unique(states[1,:]) X_len = len(X) Y_len = len(Y) Z = np.zeros((X.max()+1,Y.max()+1)) for i in range(len(p)): Z[states[0,i],states[1,i]] = p[i] Z = np.where(Z < 1e-8,0.0,Z) pl.clf() XX, YY = np.meshgrid(X,Y) pl.contour(range(X.max()+1),range(Y.max()+1),Z.T) pl.axhline(y=exp[1]) pl.axvline(x=exp[0]) pl.xlabel(labels[0]) pl.ylabel(labels[1]) if inter == True: pl.draw() else: pl.show()
def showFigure(y): plot.xlabel('# objects') plot.ylabel(y) plot.xticks(xs, ['1'] + ['']*10 + ['12'] + ['']*11 + ['24'] + ['']*10 + ['36']) ys = range(-1,int(MAXIMUMY + 1)) print MAXIMUMY plot.ylim(ymin = -1) #plot.axvline(x = 12,ymin = 0,ymax = 24,color = 'k') # plot.annotate("Within-sample generalization", # rotation = 90, # xytext = (11.5,10), # xy = (7,10), # arrowprops = dict(facecolor = 'black',shrink = 0.05)) # plot.annotate("out-of-sample generalization", # rotation = 90, # xytext = (12.5,10), # xy = (12 + 5,10), # arrowprops = dict(facecolor = 'black',shrink = 0.05)) plot.legend(['SMC+NN (100 particles)','NN (10 particles)','SMC (1000 particles)','LSTM (1000 particles)'], loc = 0, fontsize = 9) plot.show()
def plot_note_dist(mat, name="", show_octaves=True): f = plt.figure(figsize=(20,5)) f.canvas.set_window_title(name) plt.imshow(mat.T, origin="lower", interpolation="nearest", cmap=my_cmap) plt.xticks( np.arange(0,4*(constants.WHOLE//constants.RESOLUTION_SCALAR),(constants.QUARTER//constants.RESOLUTION_SCALAR)) ) plt.xlabel('Time (beat/12)') plt.ylabel('Note') plt.colorbar() if show_octaves: for y in range(0,36,12): plt.axhline(y + 1.5, color='c') for x in range(0,4*(constants.WHOLE//constants.RESOLUTION_SCALAR),(constants.QUARTER//constants.RESOLUTION_SCALAR)): plt.axvline(x-0.5, color='k') for x in range(0,4*(constants.WHOLE//constants.RESOLUTION_SCALAR),(constants.WHOLE//constants.RESOLUTION_SCALAR)): plt.axvline(x-0.5, color='c') plt.show()
def axvlines(xs, **plot_kwargs): """ Draw vertical lines on plot :param xs: A scalar, list, or 1D array of horizontal offsets :param plot_kwargs: Keyword arguments to be passed to plot :return: The plot object corresponding to the lines. """ xs = np.array((xs, ) if np.isscalar(xs) else xs, copy=False) lims = plt.gca().get_ylim() x_points = np.repeat(xs[:, None], repeats=3, axis=1).flatten() y_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(xs), axis=0).flatten() plot = plt.plot(x_points, y_points, scaley = False, **plot_kwargs) return plot # return [plt.axhline(y, **specs) for y in ys] # return [plt.axvline(x, **specs) for x in xs]
def process(aif, sample_rate=48000): file = read_wave_file(aif) # loop_start, loop_size = window_match(file) # loop_start, loop_size = zero_crossing_match(file) loop_start, loop_end = find_loop_points(file) loop_size = loop_end - loop_start file = file[0] print 'start, end', loop_start, loop_end plt.plot(file[loop_start:loop_end]) plt.plot(file[loop_end:loop_start + (2 * loop_size)]) plt.show() plt.plot(file[ loop_start - (sample_rate * 2): loop_start + (sample_rate * 2) ]) plt.axvline(sample_rate * 2) plt.axvline((sample_rate * 2) + loop_size) plt.show()
def plotVline(order): """ @Summary: Plots vertical lines for buy and sell orders @param order: Series, consists of the values -2, -1, 0, 1, 2 denoting buying/selling of 200 or 400 shares or just holding @returns nothing """ for date in order.index[order == 1]: # for dates corr. to buy 200 shares plt.axvline(date, color = 'g', linestyle = '--') for date in order.index[order == -1]: # for dates corr. to sell 200 shares plt.axvline(date, color = 'r', linestyle = '--') for date in order.index[order == 2]: # for dates corr. to buy 400 shares plt.axvline(date, color = 'g') for date in order.index[order == -2]: # for dates corr. to sell 400 shares plt.axvline(date, color = 'r')
def plotDailyHist(df, symbol, title="Selected data"): """Plot the desired columns over index values in the given range.""" df_plot = ind.daily_returns(df)[symbol] """Plot stock prices with a custom title and meaningful axis labels.""" df_plot.hist(bins=20) ax = plt.axvline(df_plot.mean(), color='w', linestyle='dashed',linewidth=2) std = df_plot.std() plt.axvline(std, color='r', linestyle='dashed',linewidth=2) plt.axvline(-std, color='r', linestyle='dashed',linewidth=2) #ax.set_xlabel("Daily returns") #ax.set_ylabel("Frequency") plt.show() # Borrowed code from : http://matplotlib.org/examples/pylab_examples/finance_demo.
def draw_timeline(self): plt.axhspan(0.97, 0.98, 0.1, 0.9, facecolor='#808080', linewidth=0) for year in range(2006, 2017): plt.text(0.1 + 0.75*(year-2006)/10.0, 0.96, "%d" % year, size = 10, weight='bold', color='white', horizontalalignment='left', verticalalignment='top', transform=plt.gca().transAxes) cur = self.current_date * self.ticks_in_week + self.tick top = len(self.dates) * self.ticks_in_week pos = 0.1 + 0.8 * (float(cur) / float(top)) plt.axvline(pos, 0.963, 0.987, color='orange', linewidth=3) plt.text(0.95, 0.01, "http://0x0fff.com", size=8, weight='bold', style='italic', color='white', horizontalalignment='center', transform=plt.gca().transAxes) return
def display_convw2(w, s, r, c, fig, title='conv_filters'): """w: num_filters X sizeX**2 * num_colors.""" num_f, num_d = w.shape assert s**2 * 3 == num_d pvh = np.zeros((s*r, s*c, 3)) for i in range(r): for j in range(c): pvh[i*s:(i+1)*s, j*s:(j+1)*s, :] = w[i*c + j, :].reshape(3, s, s).T mx = pvh.max() mn = pvh.min() pvh = 255*(pvh - mn) / (mx-mn) pvh = pvh.astype('uint8') plt.figure(fig) plt.suptitle(title) plt.imshow(pvh, interpolation="nearest") scale = 1 xmax = s * c ymax = s * r color = 'k' for x in range(0, c): plt.axvline(x=x*s/scale, ymin=0, ymax=ymax/scale, color=color) for y in range(0, r): plt.axhline(y=y*s/scale, xmin=0, xmax=xmax/scale, color=color) plt.draw() return pvh
def visualize_document_topics_heatmap(self, outfile, set_topics=False): self.sort_doctopics_groups() doctopics_raw_hm = numpy.rot90(self.document_topics_raw) rows, columns = doctopics_raw_hm.shape rownames = self.topic_labels columnnames = self.document_names pyplot.pcolor(doctopics_raw_hm, norm=None, cmap='Blues') pyplot.gca().invert_yaxis() if self.group_names: ticks_groups = [] bounds = [] current_group = False start = 0 for i,doc in enumerate(self.document_names): group = self.document_group_dict[doc] if group != current_group: if i != 0: bounds.append(i-1) ticks_groups[start+int((i-start)/2)] = current_group current_group = group start=i ticks_groups.append('') ticks_groups[start+int((i-start)/2)] = current_group pyplot.xticks(numpy.arange(columns)+0.5,ticks_groups, fontsize=11) if set_topics: for index in set_topics: pyplot.axhline(y=index) topic_names = self.return_topic_names(set_topics) pyplot.yticks(set_topics,topic_names,fontsize=8) else: pyplot.yticks(numpy.arange(rows)+0.5, rownames, fontsize=8) for bound in bounds: pyplot.axvline(x=bound) pyplot.colorbar(cmap='Blues') pyplot.savefig(outfile) pyplot.clf()
def extinction_figure(wave, a_lambda, residual_from, residual_lims=(-0.1, 0.4), title_text='$R_V = 3.1$'): names = list(a_lambda.keys()) # consistent ordering between panels fig = plt.figure(figsize=(8.5, 6.)) ax = plt.axes() for name in names: plt.plot(wave, a_lambda[name], label=name) plt.axvline(x=2700., ls=':', c='k') plt.axvline(x=3030.3030, ls=':', c='k') plt.axvline(x=9090.9091, ls=':', c='k') plt.axvspan(wave[0], 1150., fc='0.8', ec='none', zorder=-1000) plt.axvspan(1150., 1250., fc='0.9', ec='none', zorder=-1000) plt.text(0.65, 0.95, title_text, transform=ax.transAxes, va='top', ha='right', size='x-large') plt.ylabel('Extinction ($A(\lambda)$ / $A_V$)') plt.legend() plt.setp(ax.get_xticklabels(), visible=False) divider = make_axes_locatable(ax) axresid = divider.append_axes("bottom", size=2.0, pad=0.2, sharex=ax) for name in names: plt.plot(wave, a_lambda[name] - a_lambda[residual_from]) plt.axvline(x=2700., ls=':', c='k') plt.axvline(x=3030.3030, ls=':', c='k') plt.axvline(x=9090.9091, ls=':', c='k') plt.axvspan(wave[0], 1150., fc='0.8', ec='none', zorder=-1000) plt.axvspan(1150., 1250., fc='0.9', ec='none', zorder=-1000) plt.xlim(wave[0], wave[-1]) plt.ylim(ymin=residual_lims[0], ymax=residual_lims[1]) plt.ylabel('residual from ' + residual_from) plt.xlabel(r'Wavelength ($\mathrm{\AA}$)') ax.set_xscale('log') axresid.set_xscale('log') plt.tight_layout() return fig
def plot_grid(): plt.axvline(x=0, color="#999999", linestyle="-") plt.axhline(y=0, color="#999999", linestyle="-")
def plot_ic_criterion(model, name, color): alpha_ = model.alpha_ alphas_ = model.alphas_ criterion_ = model.criterion_ plt.plot(-np.log10(alphas_), criterion_, '--', color=color, linewidth=3, label='%s criterion' % name) plt.axvline(-np.log10(alpha_), color=color, linewidth=3, label='alpha: %s estimate' % name) plt.xlabel('-log(alpha)') plt.ylabel('criterion')
def printSilhouette(self, output_dir, assigned_clusters): num_clusters = len(set(assigned_clusters)) plt.clf() y_lower = 10 all_colors = colors_tools.colors(num_clusters) for i in range(num_clusters): # Aggregate the silhouette scores for samples belonging to # cluster i, and sort them ith_cluster_silhouette_values = \ self.sample_silhouette_values[assigned_clusters == i] ith_cluster_silhouette_values.sort() size_cluster_i = ith_cluster_silhouette_values.shape[0] y_upper = y_lower + size_cluster_i color = all_colors[i] plt.fill_betweenx(np.arange(y_lower, y_upper), 0, ith_cluster_silhouette_values, facecolor=color, edgecolor=color, alpha=0.7) # Label the silhouette plots with their cluster numbers at the middle plt.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i)) # Compute the new y_lower for next plot y_lower = y_upper + 10 # 10 for the 0 samples plt.title('The silhouette plot for the various clusters.') plt.xlabel('The silhouette coefficient values') plt.ylabel('Cluster label') # The vertical line for average silhoutte score of all the values plt.axvline(x=self.silhouette_avg, color='red', linestyle='--') plt.yticks([]) # Clear the yaxis labels / ticks plt.xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1]) plt.savefig(output_dir + 'silhouette.png') plt.clf()
def weibull_contour(Y, U, is_discrete, true_alpha, true_beta, logx=True, samples=200, lines=True): xlist = np.linspace(true_alpha / np.e, true_alpha * np.e, samples) ylist = np.linspace(true_beta / np.e, true_beta * np.e, samples) x_grid, y_grid = np.meshgrid(xlist, ylist) loglik = x_grid * 0 if is_discrete: fun = weibull.discrete_loglik else: fun = weibull.continuous_loglik for i in xrange(len(Y)): loglik = loglik + \ fun(Y[i], x_grid, y_grid, U[i]) z_grid = loglik / len(Y) plt.figure() if logx: x_grid = np.log(x_grid) true_alpha = np.log(true_alpha) xlab = r'$\log(\alpha)$' else: xlab = r'$\alpha$' cp = plt.contourf(x_grid, y_grid, z_grid, 100, cmap='jet') plt.colorbar(cp) if lines: plt.axvline(true_alpha, linestyle='dashed', c='black') plt.axhline(true_beta, linestyle='dashed', c='black') plt.xlabel(xlab) plt.ylabel(r'$\beta$')
def test_inject_and_recover(self, freq, use_double, mag_bins, phase_bins, mag_overlap, phase_overlap, use_fast, t0, balanced_magbins, weighted, shmem_lc, freq_batch_size): kwargs = dict(use_double=use_double, mag_bins=mag_bins, phase_bins=phase_bins, phase_overlap=phase_overlap, mag_overlap=mag_overlap, use_fast=use_fast, balanced_magbins=balanced_magbins, weighted=weighted) proc = ConditionalEntropyAsyncProcess(**kwargs) t, y, err = data(freq=freq, t0=t0) df = 1. / (max(t) - min(t)) / 10 max_freq = 1.1 * freq min_freq = 0.9 * freq nf = int((max_freq - min_freq) / df) freqs = min_freq + df * np.arange(nf) run_kw = dict(shmem_lc=shmem_lc, freq_batch_size=freq_batch_size) results = proc.large_run([(t, y, err)], freqs=freqs, **run_kw) proc.finish() frq, p = results[0] best_freq = frq[np.argmin(p)] if self.plot: import matplotlib.pyplot as plt f, ax = plt.subplots() ax.plot(frq, p) ax.axvline(freq, ls='-', color='k') ax.axvline(best_freq, ls=':', color='r') plt.show() # print best_freq, freq, abs(best_freq - freq) / freq assert(not any(np.isnan(p))) assert(abs(best_freq - freq) / freq < 3E-2)
def bayes_opt(f, initial_x, all_x, acquisition, max_iter=100, debug=False, random_state=None): """The actual bayesian optimization function. f is the very expensive function we want to minimize. initial_x is a matrix of at least two data points (preferrably more, randomly sampled). acquisition is the acquisiton function we want to use to find query points.""" X, y = list(), list() for x in initial_x: if not np.isinf(f(x)): y.append(f(x)) X.append(x) best_x = X[np.argmin(y)] best_f = y[np.argmin(y)] gp = gaussian_process.GaussianProcessRegressor(random_state=random_state) if debug: print("iter", -1, "best_x", best_x, best_f) for i in range(max_iter): gp.fit(np.array(X)[:, None], np.array(y)) new_x = all_x[acquisition(gp, best_f, all_x).argmin()] new_f = f(new_x) if not np.isinf(new_f): X.append(new_x) y.append(new_f) if new_f < best_f: best_f = new_f best_x = new_x if debug: print("iter", i, "best_x", best_x, best_f) if debug: import matplotlib.pyplot as plt scale = 1e6 sort_idx = np.argsort(X) plt.plot(np.array(X)[sort_idx] * scale, np.array(y)[sort_idx] * scale, 'bo-') plt.axvline(best_x * scale, linestyle='--') plt.show() return best_x, best_f
def show_fit(filename, ax=None): """Util function. Show a gaussian fit on nearest distances. Usage example: np.mean([show_fit(f) for f in list_naive_npy]) """ from sklearn.mixture import GMM X = np.load("{}".format(filename)) dist2nearest = np.array(X).reshape(-1, 1) if dist2nearest.shape[0] < 2: print("Cannot fit a Gaussian with two distances.") return dist2nearest_2 = -(np.array(sorted(dist2nearest)).reshape(-1, 1)) dist2nearest = np.array(list(dist2nearest_2) + list(dist2nearest)).reshape(-1, 1) gmm = GMM(n_components=3) gmm.fit(dist2nearest) plt.hist(dist2nearest, bins=50, normed=True) linspace = np.linspace(-1, 1, 1000)[:, np.newaxis] plt.plot(linspace, np.exp(gmm.score_samples(linspace)[0]), 'r') lin = np.linspace(0, 1, 10000)[:, np.newaxis] pred = gmm.predict(linspace) argmax = np.argmax(gmm.means_) idx = np.min(np.where(pred == argmax)[0]) plt.axvline(x=lin[idx], linestyle='--', color='r') plt.show() return lin[idx] # threshold
def _gaussian_fit(array): if array.shape[0] < 2: logging.error("Cannot fit a Gaussian with two distances.") return 0 array_2 = -(np.array(sorted(array)).reshape(-1, 1)) array = np.array(list(array_2) + list(array)).reshape(-1, 1) try: # new sklearn GMM gmm = mixture.GaussianMixture(n_components=3, covariance_type='diag') gmm.fit(array) # gmmmean = np.max(gmm.means_) # gmmsigma = gmm.covariances_[np.argmax(gmm.means_)] except AttributeError: # use old sklearn method gmm = mixture.GMM(n_components=3) gmm.fit(array) # gmmmean = np.max(gmm.means_) # gmmsigma = gmm.covars_[np.argmax(gmm.means_)] # Extract optimal threshold plt.hist(array, bins=50, normed=True) # debug, print lin = np.linspace(0, 1, 10000)[:, np.newaxis] # plt.plot(lin, np.exp(gmm.score_samples(lin)[0]), 'r') pred = gmm.predict(lin) try: idx = np.min(np.where(pred == np.argmax(gmm.means_))[0]) except ValueError: # print("Error", np.unique(pred)) idx = 0 plt.axvline(x=lin[idx], linestyle='--', color='r') # plt.gcf().savefig("threshold_naive{}.png".format(k)) plt.close() threshold = lin[idx][0] # threshold # np.save("threshold_naive", threshold) return threshold
def plotGPGO(gpgo, param): param_value = list(param.values())[0][1] x_test = np.linspace(param_value[0], param_value[1], 1000).reshape((1000, 1)) fig = plt.figure() a = np.array([-gpgo._acqWrapper(np.atleast_1d(x)) for x in x_test]).flatten() r = fig.add_subplot(1, 1, 1) r.set_title('Acquisition function') plt.plot(x_test, a, color='green') gpgo._optimizeAcq(method='L-BFGS-B', n_start=25) plt.axvline(x=gpgo.best, color='black', label='Found optima') plt.legend(loc=0) plt.tight_layout() plt.show()
def compare(st, **kwargs): from seis_tools.seispy.data import phase_window plt.style.use('mystyle') window = kwargs.get('window',(-10,100)) phase = kwargs.get('phase',['P']) phase_list = kwargs.get('phase_list',['P']) taup_model = kwargs.get('taup_model','none') plot_all = kwargs.get('plot_all',False) phase_name = phase[0] if taup_model == 'none': taup_model = model if plot_all == True: arrs = taup_model.get_travel_times(source_depth_in_km = st[0].stats.sac['evdp'], distance_in_degree = st[0].stats.sac['gcarc'], phase_list=phase_list) i = 0 for tr in st: if plot_all == False: windowed_trace = phase_window(tr,phases=phase,window_tuple=window,taup_model=taup_model) label_str = tr.stats.station+tr.stats.channel time = np.linspace(window[0],window[1],len(windowed_trace.data)) plt.plot(time, windowed_trace.data,label=label_str) i += 1 else: t_0 = 0.0 t_e = tr.stats.npts * (1/tr.stats.sampling_rate) time = np.linspace(t_0,t_e,tr.stats.npts) plt.plot(time,tr.data) if plot_all == True: for arr in arrs: print arr plt.axvline(arr.time,label=arr.phase.name) plt.legend() plt.xlabel('time (s), windowed on '+phase_name) plt.show()
def plot_f_distrib_for_many_coefficients(self, features): from scipy.stats import f # Remove a particular subset of features X = np.delete(self.X, [self.features.index(_) for _ in features], 1) # Prediction from reduced model XT = X.T std_error_matrix = inv(XT.dot(X)) beta = std_error_matrix.dot(XT).dot(self.y) y_hat = X.dot(beta) rss_reduced_model = np.sum((self.y - y_hat)**2) dfn = len(features) dfd = self.df # This should be distributed as chi squared # with degrees of freedom equal to number # of dropped features rss_diff = (rss_reduced_model - self.rss) chi_1 = rss_diff / dfn chi_2 = self.pop_var f_score = chi_1 / chi_2 # 5% and 95% percentile f_05, f_95 = f.ppf([0.05, 0.95], dfn, dfd) x = np.linspace(0.001, 5.0) plt.axvline(x=f_05) plt.axvline(x=f_95) plt.scatter(f_score, f.pdf(f_score, dfn, dfd), marker='o', color='red') plt.plot(x, f.pdf(x, dfn, dfd), color='gray', lw=5, alpha=0.6) plt.title('f-distribtion for dropping features: {0}'.format(features)) plt.show()
def plot(soa0, residuals, discontinuities, avg_snr=None): s2m = 3e8 / 2.4e6 # FIXME avg_snr_db = 10 * np.log10(avg_snr) print("residuals: std dev = {:.01f} m; max = {:.01f} m; " "avg corr snr = {:.01f}" .format(np.std(residuals) * s2m, np.max(np.abs(residuals)) * s2m, avg_snr_db)) plt.figure(figsize=(11, 6)) plt.subplot(1, 2, 1) plt.plot(soa0, residuals * S2M, '.-') plt.title("Residuals") plt.xlabel("RX sample") plt.ylabel("Residual (samples)") plt.grid() # plt.ylim([-0.5, 0.5]) for discontinuity in discontinuities: plt.axvline(discontinuity, color='k') plt.subplot(1, 2, 2) plt.hist(residuals, 20) plt.title("Histogram: residuals") plt.grid() plt.suptitle("Clock sync (stddev = {:.01f} m; max = {:.01f} m; " "avg corr SNR: {:.01f} dB)" .format(np.std(residuals) * s2m, np.max(np.abs(residuals)) * s2m, avg_snr_db)) plt.tight_layout() plt.subplots_adjust(top=0.90)
def plotIndividualData(data, idx = 0, cls = -1): """Plots the individual data including the markers for the different developmetnal stages""" p = plt.plot(data[:,idx]); ## add developmental stages # detect switches stages = stageIndex(data, cls = cls); for s in stages: plt.axvline(s, linewidth = 1, color = 'k'); return p;
def runsimplot(self): """ Viz of the MC results """ tdmin = self.iniest.td - 3.0*self.iniest.tderr tdmax = self.iniest.td + 3.0*self.iniest.tderr fig = plt.figure(figsize=(6, 3)) fig.subplots_adjust(top=0.95, bottom=0.2) plt.scatter(self.simtruedelays, self.simmesdelays - self.simtruedelays) plt.xlim(tdmin, tdmax) plt.xlabel("True delay [day]") plt.ylabel("Measurement error [day]") plt.axvline(self.iniest.td - self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axvline(self.iniest.td + self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axhline(0, color="black", linestyle="-", zorder=20) plt.axhline(- self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axhline(+ self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axhspan(-self.outest.tderr, self.outest.tderr, xmin=0, xmax=1, lw=0, color="red", alpha=0.2) #plt.ylim(- 2.0*self.iniest.tderr, + 2.0*self.iniest.tderr) plt.figtext(0.15, 0.8, "Total/initial error ratio: %.2f" % self.totalratio) #ax = plt.gca() #plt.figtext(0.15, 0.8, "Intrinsic/initial error ratio: %.2f" % self.intrinsicratio) #plt.axvline(self.iniest.td - self.iniest.tderr, color="gray", linestyle="-", zorder=20) #plt.axvline(self.iniest.td + self.iniest.tderr, color="gray", linestyle="-", zorder=20) #plt.axvline(self.outest.td, color="red", linestyle="-", zorder=20) plt.savefig(os.path.join(self.plotdir, "measvstrue.png")) plt.close()
def maxPplot(estslist, N, filepath=None): """ Give me a list of estimate-lists, I plot P as a function of f N is the total number of curves (e.g. 56 for tdc0) (defines f=1) """ for ests in estslist: estscp = ests[:] # Important, we work on a copy, do not modify the original ! for e in estscp: if e.td == 0.0: # We want to avoid that... #print e e.td = 0.1 ests = sortbyP(estscp) fs = [] Ps = [] for n in range(len(ests)): subests = ests[n:] fs.append(f(subests, N)) Ps.append(P(subests)) plt.plot(fs, Ps, ".-", label=ests[0].method) plt.xlabel("f") plt.ylabel("Approximation of P") plt.xlim(0.0, 0.8) plt.ylim(0.0, 0.8) plt.axvline(0.3, color="black") plt.axhline(0.15, color="black") if len(estslist) > 1: plt.legend() plt.grid() if filepath: plt.savefig(filepath) else: plt.show() ############## Here, we work with the database from analyse_results ##############
def _periodogram_plot(title, column, data, trend, peaks): """display periodogram results using matplotlib""" periods, power = periodogram(data) plt.figure(1) plt.subplot(311) plt.title(title) plt.plot(data, label=column) if trend is not None: plt.plot(trend, linewidth=3, label="broad trend") plt.legend() plt.subplot(312) plt.title("detrended") plt.plot(data - trend) else: plt.legend() plt.subplot(312) plt.title("(no detrending specified)") plt.subplot(313) plt.title("periodogram") plt.stem(periods, power) for peak in peaks: period, score, pmin, pmax = peak plt.axvline(period, linestyle='dashed', linewidth=2) plt.axvspan(pmin, pmax, alpha=0.2, color='b') plt.annotate("{}".format(period), (period, score * 0.8)) plt.annotate("{}...{}".format(pmin, pmax), (pmin, score * 0.5)) plt.tight_layout() plt.show()
def plot_arrays(self, data_map, title="", xlab="", ylab="", marker='.', legend_loc='best', legend=True, vlines=None, vlcolor='green', vlwitdh=0.5): """Plot multiple pairs of data arrays. :param self: object. :param data_map: A dictionary with labels as keys and tupples of data arrays (x,y) as values. :param title: Figure title. :param xlab: X axis label. :param ylab: Y axis label. :param marker: Marker passed to the plot function. :param legend_loc: Location of legend. :param legend: Plot legend if True :param vlines: Dictionary with labels and positions of vertical lines to draw. :param vlcolor: Color of vertical lines drawn. :param vlwidth: Width of vertical lines drawn. :returns: None :rtype: object """ fig = plt.figure() for label, data_arrays in six.iteritems(data_map): plt.plot(data_arrays[0], data_arrays[1], marker, label=label) if vlines is not None: for label, pos in six.iteritems(vlines): plt.axvline(x=pos, label=label, color=vlcolor, lw=vlwitdh) if legend: plt.legend(loc=legend_loc) self._set_properties_and_close(fig, title, xlab, ylab)
def plot_histograms(self, data_map, title="", xlab="", ylab="", bins=50, alpha=0.7, legend_loc='best', legend=True, vlines=None): """Plot histograms of multiple data arrays. :param self: object. :param data_map: A dictionary with labels as keys and data arrays as values. :param title: Figure title. :param xlab: X axis label. :param ylab: Y axis label. :param bins: Number of bins. :param alpha: Transparency value for histograms. :param legend_loc: Location of legend. :param legend: Plot legend if True. :param vlines: Dictionary with labels and positions of vertical lines to draw. :returns: None :rtype: object """ fig = plt.figure() for label, data in six.iteritems(data_map): if len(data) > 0: plt.hist(data, bins=bins, label=label, alpha=alpha) if vlines is not None: for label, pos in six.iteritems(vlines): plt.axvline(x=pos, label=label) if legend: plt.legend(loc=legend_loc) self._set_properties_and_close(fig, title, xlab, ylab)
def plot_vline(): plt.axvline(x=vcen[i], ymin=0., ymax = 1.5, linewidth=1, color='k', linestyle='dotted') plt.axvline(x=vcen[i]+30., ymin=0., ymax = 1.5, linewidth=0.5, color='k') plt.axvline(x=vcen[i]-30., ymin=0., ymax = 1.5, linewidth=0.5, color='k') # define the data directory
def sdss_plot_wavelength(wavelengths, name): # define parameters for the x and y axes ax.set_xlim(xmin, xmax) ax.xaxis.set_minor_locator(minorLocator) ax.tick_params(axis='x', labelsize=7) ax.set_ylim(0., 15.) # make the plot ax.plot(wavelength, flux) # include the name of the line plt.text(xmin+0.03*(xmax-xmin), 0.15, name) # mark the approximate centroid velocity plt.axvline(x=wavelengths, ymin=0., ymax = 15., linewidth=1, color='k', linestyle='dotted') plt.axvline(x=wavelengths + 30., ymin=0., ymax = 15., linewidth=0.5, color='k') plt.axvline(x=wavelengths - 30., ymin=0., ymax = 15., linewidth=0.5, color='k')
def plot_profile(wave, flux, line, name, fosc): # define the velocity scale [AA / s] vel_aas = (wave - line*(1+zem[i])) / (line*(1+zem[i])) * c # convert to [km / s] vel_kms = vel_aas.to('km/s') # define parameters for the x and y axes ax.set_xlim(xmin, xmax) ax.xaxis.set_minor_locator(minorLocator) ax.tick_params(axis='x', labelsize=xls) ymax = 3.e12 ax.set_ylim(0., ymax) # make the plot (using equations 5 and 8 from Savage & Sembach 1991) ax.plot(vel_kms, np.log(1/flux) / 2.654e-15 / (fosc * line)) # include the name of the line plt.text(xmin+0.03*(xmax-xmin), ymax*0.6, name) # mark the approximate centroid velocity plt.axvline(x=vcen[i], ymin=0., ymax = 1.5, linewidth=1, color='k', linestyle='dotted') plt.axvline(x=vcen[i]+30., ymin=0., ymax = 1.5, linewidth=0.5, color='k') plt.axvline(x=vcen[i]-30., ymin=0., ymax = 1.5, linewidth=0.5, color='k') # label other lines for clarity for k in range(0, len(lines)): vel_off_aas = (lines[k] - line) / line * c vel_off_kms = vel_off_aas.to('km/s') / (u.km / u.s) plt.axvline(x=vcen[i]+vel_off_kms, ymin=0., ymax = 1.5, linewidth=1, color='k', linestyle='dotted') # define the data directory
def bubble(data,x,y,hue,bsize,palette='Reds',xscale='linear',yscale='linear',title='',suptitle=0): if suptitle == 0: suptitle = bsize sns.set(style="whitegrid") sns.set_context("notebook", font_scale=3, rc={"lines.linewidth": 0.3}) sns.set_color_codes("bright") size = (1500 / float(data[bsize].max())) size = data[bsize] * size g = sns.PairGrid(data, hue=hue, palette=palette, y_vars=y, x_vars=x, size=12, aspect=3) g.map(plt.scatter, s=size); g.set(xscale=xscale) g.set(yscale=yscale) g.add_legend(title=hue, bbox_to_anchor=(0.9, 0.6)) plt.title(title, fontsize=48, y=1.12, color="gray"); plt.suptitle("size = " + suptitle, verticalalignment='top', fontsize=35, y=1.01, x=0.48, color="gray") plt.xlabel(x, fontsize=38, labelpad=30, color="gray"); plt.ylabel(y, fontsize=38, labelpad=30, color="gray"); plt.tick_params(axis='both', which='major', pad=25) plt.axhline(linewidth=2.5, color="black"); plt.axvline(linewidth=2.5, color="black"); plt.ylim(0,); plt.xlim(0,);
def plot_marginals(state_space,p,name,t,labels = False): import matplotlib #matplotlib.use("PDF") #matplotlib.rcParams['figure.figsize'] = 5,10 import matplotlib.pyplot as pl pl.suptitle("time: "+ str(t)+" units") print("time : "+ str(t)) D = state_space.shape[1] for i in range(D): marg_X = np.unique(state_space[:,i]) A = np.where(marg_X[:,np.newaxis] == state_space[:,i].T[np.newaxis,:],1,0) marg_p = np.dot(A,p) pl.subplot(int(D/2)+1,2,i+1) pl.plot(marg_X,marg_p) pl.axvline(np.sum(marg_X*marg_p),color= 'r') pl.axvline(marg_X[np.argmax(marg_p)],color='g') if labels == False: pl.xlabel("Specie: " + str(i+1)) else: pl.xlabel(labels[i]) #pl.savefig("Visuals/marginal_"+name+".pdf",format='pdf') pl.show() pl.clf() ##Simple Compress : best N-term approximation under the ell_1 norm #@param state_space the state space shape: (Number of Species X Number of states) #@param p probability vector #@param eps the ell_1 error to remove #@return -Compressed state space # -Compressed Probs
def plot_marginals(state_space,p,name,t,labels = False,interactive = False): import matplotlib import matplotlib.pyplot as pl if interactive == True: pl.ion() pl.clf() pl.suptitle("time: "+ str(t)+" units") #print("time : "+ str(t)) D = state_space.shape[1] for i in range(D): marg_X = np.unique(state_space[:,i]) A = np.where(marg_X[:,np.newaxis] == state_space[:,i].T[np.newaxis,:],1,0) marg_p = np.dot(A,p) pl.subplot(int(D/2)+1,2,i+1) pl.plot(marg_X,marg_p) pl.yticks(np.linspace(np.amin(marg_p), np.amax(marg_p), num=3)) pl.axvline(np.sum(marg_X*marg_p),color= 'r') pl.axvline(marg_X[np.argmax(marg_p)],color='g') if labels == False: pl.xlabel("Specie: " + str(i+1)) else: pl.xlabel(labels[i]) if interactive == True: pl.draw() else: pl.tight_layout() pl.show()