我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pylab.legend()。
def set_nice_params(): fsize=18 params = {'axes.labelsize': fsize, # 'font.family': 'serif', 'font.family': 'Times New Roman', 'figure.facecolor': 'white', 'text.fontsize': fsize, 'legend.fontsize': fsize, 'xtick.labelsize': fsize*0.8, 'ytick.labelsize': fsize*0.8, 'ytick.minor.pad': 8, 'ytick.major.pad': 8, 'xtick.minor.pad': 8, 'xtick.major.pad': 8, 'text.usetex': False, 'lines.markeredgewidth': 0} pl.rcParams.update(params)
def hrd_key(self, key_str): """ plot an HR diagram Parameters ---------- key_str : string A label string """ pyl.plot(self.data[:,self.cols['log_Teff']-1],\ self.data[:,self.cols['log_L']-1],label = key_str) pyl.legend() pyl.xlabel('log Teff') pyl.ylabel('log L') x1,x2=pl.xlim() if x2 > x1: self._xlimrev()
def plot_prof_2(self, mod, species, xlim1, xlim2): """ Plot one species for cycle between xlim1 and xlim2 Parameters ---------- mod : string or integer Model to plot, same as cycle number. species : list Which species to plot. xlim1, xlim2 : float Mass coordinate range. """ mass=self.se.get(mod,'mass') Xspecies=self.se.get(mod,'yps',species) pyl.plot(mass,Xspecies,'-',label=str(mod)+', '+species) pyl.xlim(xlim1,xlim2) pyl.legend()
def plotRes(pre, real, test_x,l): s = set(pre) col = ['r','b','g','y','m'] fig = plt.figure() ax = fig.add_subplot(111) for i in range(0, len(s)): index1 = pre == i index2 = real == i x1 = test_x[index1, :] x2 = test_x[index2, :] ax.scatter(x1[:,0],x1[:,1],color=col[i],marker='v',linewidths=0.5) ax.scatter(x2[:,0],x2[:,1],color=col[i],marker='.',linewidths=12) plt.title('learning rating='+str(l)) plt.legend(('c1:predict','c1:true',\ 'c2:predict','c2:true', 'c3:predict','c3:true', 'c4:predict','c4:true', 'c5:predict','c5:true'), shadow = True, loc = (0.01, 0.4)) plt.show()
def plot_position(self, pos_true, pos_est): N = pos_est.shape[1] pos_true = pos_true[:, :N] pos_est = pos_est[:, :N] # Figure plt.figure() plt.suptitle("Position") # Ground truth plt.plot(pos_true[0, :], pos_true[1, :], color="red", marker="o", label="Grouth truth") # Estimated plt.plot(pos_est[0, :], pos_est[1, :], color="blue", marker="o", label="Estimated") # Plot labels and legends plt.xlabel("East (m)") plt.ylabel("North (m)") plt.axis("equal") plt.legend(loc=0)
def plot(self, track, track_cam_states, estimates): plt.figure() # Feature feature = T_global_camera * track.ground_truth plt.plot(feature[0], feature[1], marker="o", color="red", label="feature") # Camera states for cam_state in track_cam_states: pos = T_global_camera * cam_state.p_G plt.plot(pos[0], pos[1], marker="o", color="blue", label="camera") # Estimates for i in range(len(estimates)): cam_state = track_cam_states[i] cam_pos = T_global_camera * cam_state.p_G estimate = (T_global_camera * estimates[i]) + cam_pos plt.plot(estimate[0], estimate[1], marker="o", color="green") plt.legend(loc=0) plt.show()
def plot_1d(dataset, nbins, data): with sns.axes_style('white'): plt.rc('font', weight='bold') plt.rc('grid', lw=2) plt.rc('lines', lw=3) plt.figure(1) plt.hist(data, bins=np.arange(nbins+1), color='blue') plt.ylabel('Count', weight='bold', fontsize=24) xticks = list(plt.gca().get_xticks()) while (nbins-1) / float(xticks[-1]) < 1.1: xticks = xticks[:-1] while xticks[0] < 0: xticks = xticks[1:] xticks.append(nbins-1) xticks = list(sorted(xticks)) plt.gca().set_xticks(xticks) plt.xlim([int(np.ceil(-0.05*nbins)),int(np.ceil(nbins*1.05))]) plt.legend(loc='upper right') plt.savefig('plots/marginals-{0}.pdf'.format(dataset.replace('_','-')), bbox_inches='tight') plt.clf() plt.close()
def plot_1d(dataset, nbins): data = np.loadtxt('experiments/uci/data/splits/{0}_all.csv'.format(dataset), skiprows=1, delimiter=',')[:,-1] with sns.axes_style('white'): plt.rc('font', weight='bold') plt.rc('grid', lw=2) plt.rc('lines', lw=3) plt.figure(1) plt.hist(data, bins=np.arange(nbins+1), color='blue') plt.ylabel('Count', weight='bold', fontsize=24) xticks = list(plt.gca().get_xticks()) while (nbins-1) / float(xticks[-1]) < 1.1: xticks = xticks[:-1] while xticks[0] < 0: xticks = xticks[1:] xticks.append(nbins-1) xticks = list(sorted(xticks)) plt.gca().set_xticks(xticks) plt.xlim([int(np.ceil(-0.05*nbins)),int(np.ceil(nbins*1.05))]) plt.legend(loc='upper right') plt.savefig('plots/marginals-{0}.pdf'.format(dataset.replace('_','-')), bbox_inches='tight') plt.clf() plt.close()
def plot_roc(auc_score, name, tpr, fpr, label=None): pylab.clf() pylab.figure(num=None, figsize=(5, 4)) pylab.grid(True) pylab.plot([0, 1], [0, 1], 'k--') pylab.plot(fpr, tpr) pylab.fill_between(fpr, tpr, alpha=0.5) pylab.xlim([0.0, 1.0]) pylab.ylim([0.0, 1.0]) pylab.xlabel('False Positive Rate') pylab.ylabel('True Positive Rate') pylab.title('ROC curve (AUC = %0.2f) / %s' % (auc_score, label), verticalalignment="bottom") pylab.legend(loc="lower right") filename = name.replace(" ", "_") pylab.savefig( os.path.join(CHART_DIR, "roc_" + filename + ".png"), bbox_inches="tight")
def plotKChart(self, misClassDict, saveFigPath): kList = [] misRateList = [] for k, misClassNum in misClassDict.iteritems(): kList.append(k) misRateList.append(1.0 - 1.0/k*misClassNum) fig = plt.figure(saveFigPath) plt.plot(kList, misRateList, 'r--') plt.title(saveFigPath) plt.xlabel('k Num.') plt.ylabel('Misclassified Rate') plt.legend(saveFigPath) plt.grid(True) plt.savefig(saveFigPath) plt.show() ################################### PART3 TEST ######################################## # ??
def backtest(config_file, day_trade): cfg = config.Config(config_file) cfg.day_trade = day_trade dfs = load_data(config_file) trender = strategies[cfg.strategy](**cfg.strategy_parameters) res = [] for df in dfs: res.append(trender.backtest(data_frame=df)) final_panel = pd.Panel({os.path.basename(p['path']): df for p, df in zip(cfg.data_path, res)}) profit_series = final_panel.sum(axis=0)['total_profit'].cumsum() final_panel.to_excel(cfg.output_file) if cfg.show: profit_series.plot() plt.xlabel('Time') plt.ylabel('Profit') plt.legend('Profit') plt.show()
def fit_data(): data=np.loadtxt('data.dat') print(data) params = dict() params["c"] = {"min" : -np.inf,"max" : np.inf} result = qudi_fitting.make_lorentzian_fit(axis=data[:,0], data=data[:,3], add_parameters=params) print(result.fit_report()) plt.plot(data[:,0],-data[:,3]+2,"b-o",label="data mean") # plt.plot(data[:,0],data[:,1],label="data") # plt.plot(data[:,0],data[:,2],label="data") plt.plot(data[:,0],-result.best_fit+2,"r-",linewidth=2.,label="fit") # plt.plot(data[:,0],result.init_fit,label="init") plt.xlabel("time (ns)") plt.ylabel("polarization transfer (arb. u.)") plt.legend(loc=1) # plt.savefig("pol20_24repetition_pol.pdf") # plt.savefig("pol20_24repetition_pol.png") plt.show() savedata=[[data[ii,0],-data[ii,3]+2,-result.best_fit[ii]+2] for ii in range(len(data[:,0]))] np.savetxt("pol_data_fit.csv",savedata) # print(result.params) print(result.params)
def plot_classes(y, cord, names, test_error, message=""): plt.close("all") cord = np.array(cord) colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k') un = np.unique(y) fig, ax = plt.subplots() for u, col in zip(un, colors): ind = np.argwhere(y == u) x = cord[ind, :] x = x.reshape(x.shape[0], cord.shape[1]) ax.scatter(x[:, 0], x[:, 1], label="class:" + str(u), color=col) plt.legend(loc='upper right', fancybox=True, shadow=True, prop={'size': 8}) fig.suptitle( "Output prediction. Test error:" + str(test_error*100) + "%. " + message, fontsize=8) return fig
def plot_penalty_vl(debug, tag, fold_exp): plt.close("all") vl = np.array(debug["penalty"]) fig = plt.figure(figsize=(15, 10.8), dpi=300) names = debug["names"] for i in range(vl.shape[1]): if vl.shape[1] > 1: plt.plot(vl[:, i], label="layer_"+str(names[i])) else: plt.plot(vl[:], label="layer_"+str(names[i])) plt.xlabel("mini-batchs") plt.ylabel("value of penlaty") plt.title( "Penalty value over layers:" + "_".join([str(k) for k in names]) + ". tag:" + tag) plt.legend(loc='upper right', fancybox=True, shadow=True, prop={'size': 8}) plt.grid(True) fig.savefig(fold_exp+"/penalty.png", bbox_inches='tight') plt.close('all') del fig
def plot_roc(y_test, y_pred, label=''): """Compute ROC curve and ROC area""" fpr, tpr, _ = roc_curve(y_test, y_pred) roc_auc = auc(fpr, tpr) # Plot of a ROC curve for a specific class plt.figure() plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], 'k--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic' + label) plt.legend(loc="lower right") plt.show()
def plotSpeedupFigure(AllInfo, maxWorker=1, **kwargs): pylab.figure(2) xs = AllInfo['nWorker'] ts_mono = AllInfo['t_monolithic'] xgrid = np.linspace(0, maxWorker + 0.1, 100) pylab.plot(xgrid, xgrid, 'y--', label='ideal parallel') for method in getMethodNames(**kwargs): speedupRatio = ts_mono / AllInfo['t_' + method] pylab.plot(xs, speedupRatio, 'o-', label=method, color=ColorMap[method], markeredgecolor=ColorMap[method]) pylab.xlim([-0.2, maxWorker + 0.5]) pylab.ylim([0, maxWorker + 0.5]) pylab.legend(loc='upper left') pylab.xlabel('Number of Workers') pylab.ylabel('Speedup over Monolithic')
def plotBoundVsAlph(alphaVals=np.linspace(.001, 3, 1000), beta1=0.5): exactVals = cD_exact(alphaVals, beta1) boundVals = cD_bound(alphaVals, beta1) assert np.all(exactVals >= boundVals) pylab.plot(alphaVals, exactVals, 'k-', linewidth=LINEWIDTH) pylab.plot(alphaVals, boundVals, 'r--', linewidth=LINEWIDTH) pylab.xlabel("alpha", fontsize=FONTSIZE) pylab.ylabel(" ", fontsize=FONTSIZE) pylab.xlim([np.min(alphaVals) - 0.1, np.max(alphaVals) + 0.1]) pylab.ylim([np.min(exactVals) - 0.05, np.max(exactVals) + 0.05]) pylab.xticks(np.arange(np.max(alphaVals) + 1)) pylab.legend(['c_D exact', 'c_D surrogate'], fontsize=LEGENDSIZE, loc='lower right') pylab.tick_params(axis='both', which='major', labelsize=TICKSIZE)
def plot_tree_data(data, indicies_x, indicies_y, model): plt.subplot(3, 1, 1) data, indicies_x, indicies_y, model = load_tree_data() data_line, = plt.plot(data, color="blue", label="data") data_indicies_line, = plt.plot( indicies_x, indicies_y, "o", color="green", label="fitness predictors" ) model_line, = plt.plot(model, color="red", label="model") plt.title("Data and Model Output") plt.legend() return data_line, data_indicies_line, model_line
def plot_tree_data(data, indicies_x, indicies_y, model, plot_indicies=False): plt.subplot(3, 1, 1) plt.plot(data, "o", color="blue", label="data") plt.plot(model, color="red", label="model") plt.ylim([-10, 10]) if plot_indicies: plt.plot( indicies_x, indicies_y, "o", color="green", label="fitness predictors" ) plt.title("Data and Model Output") plt.legend()
def energy_profile(self,ixaxis): """ Plot radial profile of key energy generations eps_nuc, eps_neu etc. Parameters ---------- ixaxis : 'mass' or 'radius' """ mass = self.get('mass') radius = self.get('radius') * ast.rsun_cm eps_nuc = self.get('eps_nuc') eps_neu = self.get('non_nuc_neu') if ixaxis == 'mass': xaxis = mass xlab = 'Mass / M$_\odot$' else: xaxis = old_div(radius, 1.e8) # Mm xlab = 'radius / Mm' pl.plot(xaxis, np.log10(eps_nuc), 'k-', label='$\epsilon_\mathrm{nuc}>0$') pl.plot(xaxis, np.log10(-eps_nuc), 'k--', label='$\epsilon_\mathrm{nuc}<0$') pl.plot(xaxis, np.log10(eps_neu), 'r-', label='$\epsilon_\\nu$') pl.xlabel(xlab) pl.ylabel('$\log(\epsilon_\mathrm{nuc},\epsilon_\\nu)$') pl.legend(loc='best').draw_frame(False)
def hrd_new(self, input_label="", skip=0): """ plot an HR diagram with options to skip the first N lines and add a label string Parameters ---------- input_label : string, optional Diagram label. The default is "". skip : integer, optional Skip the first n lines. The default is 0. """ xl_old=pyl.gca().get_xlim() if input_label == "": my_label="M="+str(self.header_attr['initial_mass'])+", Z="+str(self.header_attr['initial_z']) else: my_label="M="+str(self.header_attr['initial_mass'])+", Z="+str(self.header_attr['initial_z'])+"; "+str(input_label) pyl.plot(self.data[skip:,self.cols['log_Teff']-1],self.data[skip:,self.cols['log_L']-1],label = my_label) pyl.legend(loc=0) xl_new=pyl.gca().get_xlim() pyl.xlabel('log Teff') pyl.ylabel('log L') if any(array(xl_old)==0): pyl.gca().set_xlim(max(xl_new),min(xl_new)) elif any(array(xl_new)==0): pyl.gca().set_xlim(max(xl_old),min(xl_old)) else: pyl.gca().set_xlim([max(xl_old+xl_new),min(xl_old+xl_new)])
def t_lumi(self,num_frame,xax): """ Luminosity evolution as a function of time or model. Parameters ---------- num_frame : integer Number of frame to plot this plot into. xax : string Either model or time to indicate what is to be used on the x-axis """ pyl.figure(num_frame) if xax == 'time': xaxisarray = self.get('star_age') elif xax == 'model': xaxisarray = self.get('model_number') else: print('kippenhahn_error: invalid string for x-axis selction. needs to be "time" or "model"') logLH = self.get('log_LH') logLHe = self.get('log_LHe') pyl.plot(xaxisarray,logLH,label='L_(H)') pyl.plot(xaxisarray,logLHe,label='L(He)') pyl.ylabel('log L') pyl.legend(loc=2) if xax == 'time': pyl.xlabel('t / yrs') elif xax == 'model': pyl.xlabel('model number')
def test_abu_evolution(self): from nugridpy import ppn, utils import matplotlib matplotlib.use('agg') import matplotlib.pylab as mpy import os # Perform tests within temporary directory with TemporaryDirectory() as tdir: # wget the data for a ppn run from the CADC VOspace os.system("wget -q --content-disposition --directory '" + tdir + "' "\ + "'http://www.canfar.phys.uvic.ca/vospace/synctrans?TARGET="\ + "vos%3A%2F%2Fcadc.nrc.ca%21vospace%2Fnugrid%2Fdata%2Fprojects%2Fppn%2Fexamples%2F"\ + "ppn_Hburn_simple%2Fx-time.dat&DIRECTION=pullFromVoSpace&PROTOCOL"\ + "=ivo%3A%2F%2Fivoa.net%2Fvospace%2Fcore%23httpget'") #nugrid_dir= os.path.dirname(os.path.dirname(ppn.__file__)) #NuPPN_dir= nugrid_dir + "/NuPPN" #test_data_dir= NuPPN_dir + "/examples/ppn_Hburn_simple/RUN_MASTER" symbs=utils.symbol_list('lines2') x=ppn.xtime(tdir) specs=['PROT','HE 4','C 12','N 14','O 16'] i=0 for spec in specs: x.plot('time',spec,logy=True,logx=True,shape=utils.linestyle(i)[0],show=False,title='') i += 1 mpy.ylim(-5,0.2) mpy.legend(loc=0) mpy.xlabel('$\log t / \mathrm{min}$') mpy.ylabel('$\log X \mathrm{[mass fraction]}$') abu_evol_file = 'abu_evolution.png' mpy.savefig(abu_evol_file) self.assertTrue(os.path.exists(abu_evol_file))
def set_nice_params(): fsize=18 params = {'axes.labelsize': fsize, # 'font.family': 'serif', 'font.family': 'Times New Roman', 'figure.facecolor': 'white', 'text.fontsize': fsize, 'legend.fontsize': fsize, 'xtick.labelsize': fsize*0.8, 'ytick.labelsize': fsize*0.8, 'text.usetex': False} pl.rcParams.update(params)
def plot_prof_1(self, mod, species, xlim1, xlim2, ylim1, ylim2, symbol=None): """ plot one species for cycle between xlim1 and xlim2 Parameters ---------- mod : string or integer Model to plot, same as cycle number. species : list Which species to plot. xlim1, xlim2 : float Mass coordinate range. ylim1, ylim2 : float Mass fraction coordinate range. symbol : string, optional Which symbol you want to use. If None symbol is set to '-'. The default is None. """ DataPlot.plot_prof_1(self,species,mod,xlim1,xlim2,ylim1,ylim2,symbol) """ tot_mass=self.se.get(mod,'total_mass') age=self.se.get(mod,'age') mass=self.se.get(mod,'mass') Xspecies=self.se.get(mod,'iso_massf',species) pyl.plot(mass,np.log10(Xspecies),'-',label=species) pyl.xlim(xlim1,xlim2) pyl.ylim(ylim1,ylim2) pyl.legend() pl.xlabel('$Mass$ $coordinate$', fontsize=20) pl.ylabel('$X_{i}$', fontsize=20) pl.title('Mass='+str(tot_mass)+', Time='+str(age)+' years, cycle='+str(mod)) """
def plot4(self, num): """ Plots the abundances of H-1, He-4, C-12 and O-16. """ self.plot_prof_1(num,'H-1',0.,5.,-5,0.) self.plot_prof_1(num,'He-4',0.,5.,-5,0.) self.plot_prof_1(num,'C-12',0.,5.,-5,0.) self.plot_prof_1(num,'O-16',0.,5.,-5,0.) pyl.legend(loc=3)
def plot_prof_sparse(self, mod, species, xlim1, xlim2, ylim1, ylim2, sparse, symbol): """ plot one species for cycle between xlim1 and xlim2. Parameters ---------- species : list which species to plot. mod : string or integer Model (cycle) to plot. xlim1, xlim2 : float Mass coordinate range. ylim1, ylim2 : float Mass fraction coordinate range. sparse : integer Sparsity factor for points. symbol : string which symbol you want to use? """ mass=self.se.get(mod,'mass') Xspecies=self.se.get(mod,'yps',species) pyl.plot(mass[0:len(mass):sparse],np.log10(Xspecies[0:len(Xspecies):sparse]),symbol) pyl.xlim(xlim1,xlim2) pyl.ylim(ylim1,ylim2) pyl.legend()
def abup_se_plot(mod,species): """ plot species from one ABUPP file and the se file. You must use this function in the directory where the ABP files are and an ABUP file for model mod must exist. Parameters ---------- mod : integer Model to plot, you need to have an ABUPP file for that model. species : string The species to plot. Notes ----- The species is set to 'C-12'. """ # Marco, you have already implemented finding headers and columns in # ABUP files. You may want to transplant that into here? species='C-12' filename = 'ABUPP%07d0000.DAT' % mod print(filename) mass,c12=np.loadtxt(filename,skiprows=4,usecols=[1,18],unpack=True) c12_se=self.se.get(mod,'iso_massf','C-12') mass_se=self.se.get(mod,'mass') pyl.plot(mass,c12) pyl.plot(mass_se,c12_se,'o',label='cycle '+str(mod)) pyl.legend()
def generate_time_plot(methods, datasets, runtimes_per_method, colors): num_methods = len(methods) num_datasets = len(datasets) x_ticks = np.linspace(0., 1., num_methods) width = 0.6 / num_methods / num_datasets spacing = 0.4 / num_methods / num_datasets fig, ax1 = plt.subplots() ax1.set_ylabel('Time [s]', color='b') ax1.tick_params('y', colors='b') ax1.set_yscale('log') fig.suptitle("Hand-Eye Calibration Method Timings", fontsize='24') handles = [] for i, dataset in enumerate(datasets): runtimes = [runtimes_per_method[dataset][method] for method in methods] bp = ax1.boxplot( runtimes, 0, '', positions=(x_ticks + (i - num_datasets / 2. + 0.5) * spacing * 2), widths=width) plt.setp(bp['boxes'], color=colors[i], linewidth=line_width) plt.setp(bp['whiskers'], color=colors[i], linewidth=line_width) plt.setp(bp['fliers'], color=colors[i], marker='+', linewidth=line_width) plt.setp(bp['medians'], color=colors[i], marker='+', linewidth=line_width) plt.setp(bp['caps'], color=colors[i], linewidth=line_width) handles.append(mpatches.Patch(color=colors[i], label=dataset)) plt.legend(handles=handles, loc=2) plt.xticks(x_ticks, methods) plt.xlim(x_ticks[0] - 2.5 * spacing * num_datasets, x_ticks[-1] + 2.5 * spacing * num_datasets) plt.show()
def onehist(x,xlabel='',fontsize=12): """ Script that plots the histogram of x with the corresponding xlabel. """ pylab.clf() pylab.rcParams.update({'font.size': fontsize}) pylab.hist(x,histtype='stepfilled') pylab.legend() #### Change the X-axis appropriately #### pylab.xlabel(xlabel) pylab.ylabel('Number') pylab.draw() pylab.show()
def threehistsx(x1,x2,x3,x1leg='$x_1$',x2leg='$x_2$',x3leg='$x_3$',fig=1,fontsize=12,bins1=10,bins2=10,bins3=10): """ Script that pretty-plots three histograms of quantities x1, x2 and x3. Arguments: :param x1,x2,x3: arrays with data to be plotted :param x1leg, x2leg, x3leg: legends for each histogram :param fig: which plot window should I use? Example: x1=Lbol(AD), x2=Lbol(JD), x3=Lbol(EHF10) >>> threehists(x1,x2,x3,38,44,'AD','JD','EHF10','$\log L_{\\rm bol}$ (erg s$^{-1}$)') Inspired by http://www.scipy.org/Cookbook/Matplotlib/Multiple_Subplots_with_One_Axis_Label. """ pylab.rcParams.update({'font.size': fontsize}) pylab.figure(fig) pylab.clf() pylab.subplot(3,1,1) pylab.hist(x1,label=x1leg,color='b',bins=bins1) pylab.legend(loc='best',frameon=False) pylab.subplot(3,1,2) pylab.hist(x2,label=x2leg,color='r',bins=bins2) pylab.legend(loc='best',frameon=False) pylab.subplot(3,1,3) pylab.hist(x3,label=x3leg,color='y',bins=bins3) pylab.legend(loc='best',frameon=False) pylab.minorticks_on() pylab.subplots_adjust(hspace=0.15) pylab.draw() pylab.show()
def demo(text=None): from nltk.corpus import brown from matplotlib import pylab tt = TextTilingTokenizer(demo_mode=True) if text is None: text = brown.raw()[:10000] s, ss, d, b = tt.tokenize(text) pylab.xlabel("Sentence Gap index") pylab.ylabel("Gap Scores") pylab.plot(range(len(s)), s, label="Gap Scores") pylab.plot(range(len(ss)), ss, label="Smoothed Gap scores") pylab.plot(range(len(d)), d, label="Depth scores") pylab.stem(range(len(b)), b) pylab.legend() pylab.show()
def plot_position(self, pos_true, pos_est, cam_states): N = pos_est.shape[1] pos_true = pos_true[:, :N] pos_est = pos_est[:, :N] # Figure plt.figure() plt.suptitle("Position") # Ground truth plt.plot(pos_true[0, :], pos_true[1, :], color="red", label="Grouth truth") # color="red", marker="x", label="Grouth truth") # Estimated plt.plot(pos_est[0, :], pos_est[1, :], color="blue", label="Estimated") # color="blue", marker="o", label="Estimated") # Sliding window cam_pos = [] for cam_state in cam_states: cam_pos.append(cam_state.p_G) cam_pos = np.array(cam_pos).reshape((len(cam_pos), 3)).T plt.plot(cam_pos[0, :], cam_pos[1, :], color="green", label="Camera Poses") # color="green", marker="o", label="Camera Poses") # Plot labels and legends plt.xlabel("East (m)") plt.ylabel("North (m)") plt.axis("equal") plt.legend(loc=0)
def plot_velocity(self, timestamps, vel_true, vel_est): N = vel_est.shape[1] t = timestamps[:N] vel_true = vel_true[:, :N] vel_est = vel_est[:, :N] # Figure plt.figure() plt.suptitle("Velocity") # X axis plt.subplot(311) plt.plot(t, vel_true[0, :], color="red", label="Ground_truth") plt.plot(t, vel_est[0, :], color="blue", label="Estimate") plt.title("x-axis") plt.xlabel("Date Time") plt.ylabel("ms^-1") plt.legend(loc=0) # Y axis plt.subplot(312) plt.plot(t, vel_true[1, :], color="red", label="Ground_truth") plt.plot(t, vel_est[1, :], color="blue", label="Estimate") plt.title("y-axis") plt.xlabel("Date Time") plt.ylabel("ms^-1") plt.legend(loc=0) # Z axis plt.subplot(313) plt.plot(t, vel_true[2, :], color="red", label="Ground_truth") plt.plot(t, vel_est[2, :], color="blue", label="Estimate") plt.title("z-axis") plt.xlabel("Date Time") plt.ylabel("ms^-1") plt.legend(loc=0)
def plot_attitude(self, timestamps, att_true, att_est): # Setup N = att_est.shape[1] t = timestamps[:N] att_true = att_true[:, :N] att_est = att_est[:, :N] # Figure plt.figure() plt.suptitle("Attitude") # X axis plt.subplot(311) plt.plot(t, att_true[0, :], color="red", label="Ground_truth") plt.plot(t, att_est[0, :], color="blue", label="Estimate") plt.title("x-axis") plt.legend(loc=0) plt.xlabel("Date Time") plt.ylabel("rad s^-1") # Y axis plt.subplot(312) plt.plot(t, att_true[1, :], color="red", label="Ground_truth") plt.plot(t, att_est[1, :], color="blue", label="Estimate") plt.title("y-axis") plt.legend(loc=0) plt.xlabel("Date Time") plt.ylabel("rad s^-1") # Z axis plt.subplot(313) plt.plot(t, att_true[2, :], color="red", label="Ground_truth") plt.plot(t, att_est[2, :], color="blue", label="Estimate") plt.title("z-axis") plt.legend(loc=0) plt.xlabel("Date Time") plt.ylabel("rad s^-1")
def test_step(self): # Step a_B_history = self.dataset.a_B w_B_history = self.dataset.w_B for i in range(30): (a_B, w_B) = self.dataset.step() a_B_history = np.hstack((a_B_history, a_B)) w_B_history = np.hstack((w_B_history, w_B)) # Plot debug = False # debug = True if debug: plt.subplot(211) plt.plot(self.dataset.time_true, a_B_history[0, :], label="ax") plt.plot(self.dataset.time_true, a_B_history[1, :], label="ay") plt.plot(self.dataset.time_true, a_B_history[2, :], label="az") plt.legend(loc=0) plt.subplot(212) plt.plot(self.dataset.time_true, w_B_history[0, :], label="wx") plt.plot(self.dataset.time_true, w_B_history[1, :], label="wy") plt.plot(self.dataset.time_true, w_B_history[2, :], label="wz") plt.legend(loc=0) plt.show()
def plot_bias_variance(data_sizes, train_errors, test_errors, name): pylab.clf() pylab.ylim([0.0, 1.0]) pylab.xlabel('Data set size') pylab.ylabel('Error') pylab.title("Bias-Variance for '%s'" % name) pylab.plot( data_sizes, train_errors, "-", data_sizes, test_errors, "--", lw=1) pylab.legend(["train error", "test error"], loc="upper right") pylab.grid() pylab.savefig(os.path.join(CHART_DIR, "bv_" + name + ".png"))
def plot_roc(auc_score, name, fpr, tpr): pylab.figure(num=None, figsize=(6, 5)) pylab.plot([0, 1], [0, 1], 'k--') pylab.xlim([0.0, 1.0]) pylab.ylim([0.0, 1.0]) pylab.xlabel('False Positive Rate') pylab.ylabel('True Positive Rate') pylab.title('Receiver operating characteristic (AUC=%0.2f)\n%s' % ( auc_score, name)) pylab.legend(loc="lower right") pylab.grid(True, linestyle='-', color='0.75') pylab.fill_between(tpr, fpr, alpha=0.5) pylab.plot(fpr, tpr, lw=1) pylab.savefig( os.path.join(CHART_DIR, "roc_" + name.replace(" ", "_") + ".png"))
def plot_bias_variance(data_sizes, train_errors, test_errors, name, title): pylab.figure(num=None, figsize=(6, 5)) pylab.ylim([0.0, 1.0]) pylab.xlabel('Data set size') pylab.ylabel('Error') pylab.title("Bias-Variance for '%s'" % name) pylab.plot( data_sizes, test_errors, "--", data_sizes, train_errors, "b-", lw=1) pylab.legend(["test error", "train error"], loc="upper right") pylab.grid(True, linestyle='-', color='0.75') pylab.savefig( os.path.join(CHART_DIR, "bv_" + name.replace(" ", "_") + ".png"), bbox_inches="tight")
def plot_k_complexity(ks, train_errors, test_errors): pylab.figure(num=None, figsize=(6, 5)) pylab.ylim([0.0, 1.0]) pylab.xlabel('k') pylab.ylabel('Error') pylab.title('Errors for for different values of $k$') pylab.plot( ks, test_errors, "--", ks, train_errors, "-", lw=1) pylab.legend(["test error", "train error"], loc="upper right") pylab.grid(True, linestyle='-', color='0.75') pylab.savefig( os.path.join(CHART_DIR, "kcomplexity.png"), bbox_inches="tight")
def print_graph(X_all, X_test, y_all, y_pred1, y_pred2): training_size = X_all.shape[0] - X_test.shape[0] x_full_limit = np.linspace(1, X_all.shape[0], X_all.shape[0]) y_pred_limit = np.linspace(training_size+1, training_size + 1 + X_test.shape[0], X_test.shape[0]) plt.plot(x_full_limit, y_all, label='actual', color='b', linewidth=1) plt.plot(y_pred_limit, y_pred1, '--', color='r', linewidth=2, label='prediction1') plt.plot(y_pred_limit, y_pred2, '--', color='g', linewidth=2, label='prediction2') plt.legend(loc=0) plt.show()
def print_graph_test(y_test, y_pred1, y_pred2, maxEntries=50): #y_pred_limit = min(maxEntries, len(y_test)) length = min(maxEntries,len(y_test)) y_pred_limit = np.linspace(1, length, length) plt.plot(y_pred_limit, y_test, label='actual', color='b', linewidth=1) plt.plot(y_pred_limit, y_pred1, '--', color='r', linewidth=2, label='prediction1') plt.plot(y_pred_limit, y_pred2, '--', color='g', linewidth=2, label='prediction2') plt.legend(loc=0) plt.show()
def display(pklfile, request=['train_data_accuracy', 'train_sample_accuracy']) : for key in request : plt.plot(pklfile[key], label=key) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=len(request), mode="expand", borderaxespad=0.) plt.show()
def N15_testing2(): """ Test direkt the implemented fit method with simulated data.""" x_axis = np.linspace(2850, 2860, 101)*1e6 mod,params = qudi_fitting.make_multiplelorentzian_model(no_of_functions=2) # print('Parameters of the model',mod.param_names) p=Parameters() p.add('l0_amplitude',value=-3e4) p.add('l0_center',value=2850*1e6+abs(np.random.random(1)*8)*1e6) # p.add('lorentz0_sigma',value=abs(np.random.random(1)*1)*1e6+0.5*1e6) p.add('l0_sigma',value=0.5*1e6) p.add('l1_amplitude',value=p['l0_amplitude'].value) p.add('l1_center',value=p['l0_center'].value+3.03*1e6) p.add('l1_sigma',value=p['l0_sigma'].value) p.add('offset',value=100.) data_nice = mod.eval(x=x_axis, params=p) data_noisy=(data_nice + 14000*np.random.normal(size=x_axis.shape)) result = qudi_fitting.make_lorentziandouble_fit(x_axis, data_noisy, estimator=qudi_fitting.estimate_lorentziandouble_N15) plt.figure() plt.plot(x_axis, data_noisy,'-b', label='data') plt.plot(x_axis, result.init_fit,'-y', label='initial values') plt.plot(x_axis, result.best_fit,'-r', label='actual fit') plt.plot(x_axis, data_nice,'-g', label='actual fit') plt.xlabel('Frequency (Hz)') plt.ylabel('Counts (#)') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.show()
def N14_testing_data2(): """ Test the N14 fit with data from file. """ # get the model of the three lorentzian peak, this gives you the # ability to get the used parameter container for the fit. mod, params = qudi_fitting.make_multiplelorentzian_model(no_of_functions=3) # you can insert the whole path with the windows separator # symbol \ just use the r in front of the string to indicated # that this is a raw input. The os package will do the rest. path = os.path.abspath(r'C:\Users\astark\Dropbox\Doctorwork\Software\QuDi-Git\qudi\pulsedODMRdata.csv') data = np.genfromtxt(path,delimiter=',') # data = np.loadtxt(path, delimiter=',') # print(data) # The data for the fit: x_axis = data[:,0]*1e8 data_noisy = data[:,1] result = qudi_fitting.make_N14_fit(x_axis, data_noisy) print(result.fit_report()) plt.plot(x_axis, data_noisy,'-b', label='data') plt.plot(x_axis,result.best_fit,'-r', label='best fit result') plt.plot(x_axis,result.init_fit,'-g',label='initial fit') # plt.plot(x_axis, data_test,'-k', label='test data') plt.xlabel('Frequency (Hz)') plt.ylabel('Counts (#)') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.show()
def gaussianpeak_testing2(): """ Test the implemented Gaussian peak fit. """ x_axis = np.linspace(0, 5, 11) ampl = 10000 center = 3 sigma = 1 offset = 10000 mod_final, params = qudi_fitting.make_gaussoffset_model() data_noisy = mod_final.eval(x=x_axis, amplitude=ampl, center=center, sigma=sigma, offset=offset) + \ 2000*abs(np.random.normal(size=x_axis.shape)) result = qudi_fitting.make_gaussoffsetpeak_fit(x_axis=x_axis, data=data_noisy) plt.figure() plt.plot(x_axis, data_noisy,'-b', label='data') plt.plot(x_axis, result.best_fit,'-r', label='best fit result') plt.plot(x_axis, result.init_fit,'-g',label='initial fit') plt.xlabel('Frequency (Hz)') plt.ylabel('Counts (#)') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.show() print(result.fit_report())
def gaussiandip_testing2(): """ Test the implemented Gaussian dip fit. """ x_axis = np.linspace(0, 5, 11) ampl = -10000 center = 3 sigma = 1 offset = 10000 mod_final, params = qudi_fitting.make_gaussoffset_model() data_noisy = mod_final.eval(x=x_axis, amplitude=ampl, center=center, sigma=sigma, offset=offset) + \ 5000*abs(np.random.normal(size=x_axis.shape)) result = qudi_fitting.make_gaussoffsetdip_fit(x_axis=x_axis, data=data_noisy) plt.figure() plt.plot(x_axis, data_noisy,'-b', label='data') plt.plot(x_axis, result.best_fit,'-r', label='best fit result') plt.plot(x_axis, result.init_fit,'-g',label='initial fit') plt.xlabel('Frequency (Hz)') plt.ylabel('Counts (#)') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.show() print(result.fit_report())
def gaussianlinearoffset_testing_data(): x = np.linspace(0, 5, 30) x_nice=np.linspace(0, 5, 101) mod_final,params = qudi_fitting.make_gaussianwithslope_model() data=np.loadtxt("./../1D_shllow.csv") data_noisy=data[:,1] data_fit=data[:,3] x=data[:,2] update=dict() update["slope"]={"min":-np.inf,"max":np.inf} update["offset"]={"min":-np.inf,"max":np.inf} update["sigma"]={"min":-np.inf,"max":np.inf} update["center"]={"min":-np.inf,"max":np.inf} update["amplitude"]={"min":-np.inf,"max":np.inf} result=qudi_fitting.make_gaussianwithslope_fit(x_axis=x, data=data_noisy, add_params=update) # ## # gaus=gaussian(3,5) # qudi_fitting.data_smooth = filters.convolve1d(qudi_fitting.data_noisy, gaus/gaus.sum(),mode='mirror') plt.plot(x,data_noisy,label="data") plt.plot(x,data_fit,"k",label="old fit") plt.plot(x,result.init_fit,'-g',label='init') plt.plot(x,result.best_fit,'-r',label='fit') plt.legend() plt.show() print(result.fit_report())