我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.errorbar()。
def plot_mean_debye(sol, ax): x = np.log10(sol[0]["data"]["tau"]) x = np.linspace(min(x), max(x),100) list_best_rtd = [100*np.sum([a*(x**i) for (i, a) in enumerate(s["params"]["a"])], axis=0) for s in sol] # list_best_rtd = [s["fit"]["best"] for s in sol] y = np.mean(list_best_rtd, axis=0) y_min = 100*np.sum([a*(x**i) for (i, a) in enumerate(sol[0]["params"]["a"] - sol[0]["params"]["a_std"])], axis=0) y_max = 100*np.sum([a*(x**i) for (i, a) in enumerate(sol[0]["params"]["a"] + sol[0]["params"]["a_std"])], axis=0) ax.errorbar(10**x[(x>-6)&(x<2)], y[(x>-6)&(x<2)], None, None, "-", color='blue',linewidth=2, label="Mean RTD", zorder=10) plt.plot(10**x[(x>-6)&(x<2)], y_min[(x>-6)&(x<2)], color='lightgray', alpha=1, zorder=-1, label="RTD range") plt.plot(10**x[(x>-6)&(x<2)], y_max[(x>-6)&(x<2)], color='lightgray', alpha=1, zorder=-1) plt.fill_between(sol[0]["data"]["tau"], 100*(sol[0]["params"]["m_"]-sol[0]["params"]["m__std"]) , 100*(sol[0]["params"]["m_"]+sol[0]["params"]["m__std"]), color='lightgray', alpha=1, zorder=-1, label="RTD SD") ax.set_xlabel("Relaxation time (s)", fontsize=14) ax.set_ylabel("Chargeability (%)", fontsize=14) plt.yticks(fontsize=14), plt.xticks(fontsize=14) plt.xscale("log") ax.set_xlim([1e-6, 1e1]) ax.set_ylim([0, 5.0]) ax.legend(loc=1, fontsize=12) # ax.set_title(title+" step method", fontsize=14)
def poisson_limits(N, kind, confidence=0.6827): alpha = 1 - confidence upper = np.zeros(len(N)) lower = np.zeros(len(N)) if kind == 'gamma': lower = stats.gamma.ppf(alpha / 2, N) upper = stats.gamma.ppf(1 - alpha / 2, N + 1) elif kind == 'sqrt': err = np.sqrt(N) lower = N - err upper = N + err else: raise ValueError('Unknown errorbar kind: {}'.format(kind)) # clip lower bars lower[N==0] = 0 return N - lower, upper - N
def myplot(self): # Plot the results plt.clf() burn=1000 x=np.arange(self.eargs['dsize'])+1 stats=[[],[]] for i,y in enumerate(self.data['y']): stats[0].append(np.mean(y)) stats[1].append(self.eargs['sigma']/np.sqrt(y.size)) plt.errorbar(x,stats[0],yerr=stats[1],fmt='.b',lw=3,ms=12,alpha=0.8) plt.errorbar(x,self.mu['alpha'],yerr=self.sigma['alpha'],fmt='.g',lw=3,ms=12,alpha=0.8) temp1=np.mean(self.chain['mu'][burn:]) plt.plot([0,self.eargs['dsize']+1],[temp1,temp1],'k--') plt.xlim([0,self.eargs['dsize']+1]) plt.ylabel(r'$\alpha_j$') plt.xlabel(r'Group $j$')
def errorbars(x, y, err, save_path='', title='', xlabel='', ylabel='', label=''): if label: plt.errorbar(x, y, yerr=err, label=label, fmt='-o') plt.legend(loc='best') else: plt.errorbar(x, y, yerr=err, fmt='-o') plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) if save_path: plt.savefig(save_path) plt.close()
def plot_shard_scaling(results, outfile): parsed_results = parse_shard_results(results) pyplot.xlabel('Number of shards') pyplot.ylabel('Average transactions / second') pyplot.grid(True) pyplot.errorbar( range(2, len(parsed_results)+2), [i[0] for i in parsed_results], [i[1] for i in parsed_results], marker='o', #color='black', ) pyplot.savefig(outfile) pyplot.close()
def plot_instcat_magnitudes(df, visit_name, component, fontsize='x-small'): """ Plot the measured - true magnitude vs true magnitude. Parameters ---------- df : pandas.DataFrame Data frame containing the true and measured coordinates and magnitudes and position offsets. visit_name : str Visit name combining the visit number and filter, e.g., 'v230-fr'. component : str Name of the component, e.g., 'R2:2' (for the full center raft), 'R:2,2 S:1,1' (for the central chip). fontsize : str or int, optional Font size to use in plots. Default: 'x-small' """ plt.errorbar(df['magnitude_true'], df['magnitude'] - df['magnitude_true'], fmt='.', label='pointSource') axis_range = plt.axis() plt.plot(axis_range[:2], [0, 0], 'k:') plt.xlabel('true magnitude', fontsize=fontsize) plt.ylabel('measured - true magnitude', fontsize=fontsize) plt.title('%(visit_name)s, %(component)s' % locals(), fontsize=fontsize)
def cvglmnetPlot(cvobject, sign_lambda = 1.0, **options): sloglam = sign_lambda*scipy.log(cvobject['lambdau']) fig = plt.gcf() ax1 = plt.gca() #fig, ax1 = plt.subplots() plt.errorbar(sloglam, cvobject['cvm'], cvobject['cvsd'], \ ecolor = (0.5, 0.5, 0.5), \ **options ) plt.hold(True) plt.plot(sloglam, cvobject['cvm'], linestyle = 'dashed',\ marker = 'o', markerfacecolor = 'r') xlim1 = ax1.get_xlim() ylim1 = ax1.get_ylim() xval = sign_lambda*scipy.log(scipy.array([cvobject['lambda_min'], cvobject['lambda_min']])) plt.plot(xval, ylim1, color = 'b', linestyle = 'dashed', \ linewidth = 1) if cvobject['lambda_min'] != cvobject['lambda_1se']: xval = sign_lambda*scipy.log([cvobject['lambda_1se'], cvobject['lambda_1se']]) plt.plot(xval, ylim1, color = 'b', linestyle = 'dashed', \ linewidth = 1) ax2 = ax1.twiny() ax2.xaxis.tick_top() atdf = ax1.get_xticks() indat = scipy.ones(atdf.shape, dtype = scipy.integer) if sloglam[-1] >= sloglam[1]: for j in range(len(sloglam)-1, -1, -1): indat[atdf <= sloglam[j]] = j else: for j in range(len(sloglam)): indat[atdf <= sloglam[j]] = j prettydf = cvobject['nzero'][indat] ax2.set(XLim=xlim1, XTicks = atdf, XTickLabels = prettydf) ax2.grid() ax1.yaxis.grid() ax2.set_xlabel('Degrees of Freedom') # plt.plot(xlim1, [ylim1[1], ylim1[1]], 'b') # plt.plot([xlim1[1], xlim1[1]], ylim1, 'b') if sign_lambda < 0: ax1.set_xlabel('-log(Lambda)') else: ax1.set_xlabel('log(Lambda)') ax1.set_ylabel(cvobject['name']) #plt.show()
def plot_microlensing(time, mag, magerr): """Plots a simulated microlensing event from an inserted flat lightcurve. :param time: the time-varying data of the lightcurve. Must be an array. :param mag: the time-varying intensity of the object. Must be an array. :param magerr: photometric error for the intensity. Must be an array. :return: the function will return a plot of the microlensing lightcurve. :rtype: plot """ intensity = simulate_microlensing(time, mag, magerr)[1] plt.errorbar(time, intensity, yerr = magerr, fmt='o') plt.gca().invert_yaxis plt.xlabel('Time') plt.ylabel('Intensity') plt.title('Simulated Microlensing') plt.show()
def main(train, test, all_tags, mink, maxk, limit, use_k=False, method='dot'): means = [] stds = [] for i in range(mink, maxk): if use_k: res = ec.evaluate_kmeans(train, test, all_tags, limit, i, method) else: res = ec.evaluate_cmeans(train, test, all_tags, limit, i, method) mean = np.mean(np.array(res)) std = np.std(np.array(res)) means.append(mean) stds.append(std) print("Trained {}, mean:{}, std: {}".format(i, mean, std)) plt.errorbar(np.r_[mink:maxk], means, stds, marker='^') plt.xlabel("Number of clusters") plt.ylabel("avg cosine_similarity") plt.show()
def plot_it(x, arr_y, labels=None, fname=None, figtext='', loc=1): if labels is not None: assert len(arr_y) == len(labels) else: labels = [None] * len(arr_y) plt.figure() plt.gca().set_position((.1, .3, .8, .7)) # to make a bit of room for extra text for y,lab in zip(arr_y, labels): plt.errorbar(x, y[:,0], yerr=y[:,1], fmt='-o', label=lab) plt.legend(loc=loc) plt.xlim((-1, 30)) #plt.figtext(0,0,figtext) #plt.plot(x, y[:,2], '-o', label='median') plt.figtext(.02, .02, figtext,fontsize=16) plt.xlabel("% skipped") if fname is not None: plt.savefig(fname, bbox_inches='tight') plt.clf() else: plt.show()
def analyze(filename): """Analyze prediction output""" dt = np.load(filename) ps = dt["pred"].transpose((0, 2, 1)) ls = dt["truevals"] print "[ANALYTIC] WER on file " + filename + " is:", compute_wer(ps, ls) sm, ttl = cmp_pos(ps, ls) # sm[i] is no. times the i-th char is predicted correctly # ttl[i] is no. times the i-th char is ever predicted (i.e. before eos) ind = ttl.tolist().index(0)-10 if 0 in ttl else None err = 1 - sm[:ind] / ttl[:ind] var = err * (1 - err) leng = err.shape[0] for i in range(leng): if ttl[i] == 1: var[i] = 1 else: var[i] /= (ttl[i]-1) # more to add here: error bar stddev = np.sqrt(var) plt.errorbar(range(leng), err, yerr = stddev, fmt = 'b-') set_plot("Error rates at different indices in the sentence", "Index", "Error rate") plt.axis([0, ind, 0, 1]) plt.show() len_err(ps, ls) plot_correct(ps, ls)
def update_plot(fig, ax, times, avg, err, interfaceDict): ax.clear() ax.set_title('Wifi Signal over Time') plt.xlabel('Time [s]') if platform.system() == 'Linux': plt.ylabel('Signal Level [dBm]') elif platform.system() == 'Windows': plt.ylabel('Signal Level [%]') else: raise Exception('reached else of if statement') for key, value in interfaceDict.items(): plt.errorbar(times[:], avg[value, :], yerr=err[value, :], label=key) plt.legend() print('\n\n') plt.pause(0.0001) plt.show()
def plot_runtime(ex, fname, func_xvalues, xlabel, func_title=None): results = glo.ex_load_result(ex, fname) value_accessor = lambda job_results: job_results['time_secs'] vf_pval = np.vectorize(value_accessor) # results['job_results'] is a dictionary: # {'test_result': (dict from running perform_test(te) '...':..., } times = vf_pval(results['job_results']) repeats, _, n_methods = results['job_results'].shape time_avg = np.mean(times, axis=0) time_std = np.std(times, axis=0) xvalues = func_xvalues(results) #ns = np.array(results[xkey]) #te_proportion = 1.0 - results['tr_proportion'] #test_sizes = ns*te_proportion line_styles = func_plot_fmt_map() method_labels = get_func2label_map() func_names = [f.__name__ for f in results['method_job_funcs'] ] for i in range(n_methods): te_proportion = 1.0 - results['tr_proportion'] fmt = line_styles[func_names[i]] #plt.errorbar(ns*te_proportion, mean_rejs[:, i], std_pvals[:, i]) method_label = method_labels[func_names[i]] plt.errorbar(xvalues, time_avg[:, i], yerr=time_std[:,i], fmt=fmt, label=method_label) ylabel = 'Time (s)' plt.ylabel(ylabel) plt.xlabel(xlabel) plt.xlim([np.min(xvalues), np.max(xvalues)]) plt.xticks( xvalues, xvalues ) plt.legend(loc='best') plt.gca().set_yscale('log') title = '%s. %d trials. '%( results['prob_label'], repeats ) if func_title is None else func_title(results) plt.title(title) #plt.grid() return results
def plotEndtoendSq(weightedEndtoendSq,weightedEndtoendSqStd,fittedWeightedEndtoendSq,popSize): x = np.linspace(1,c.nBeads, c.nBeads); # Plot the end-to-end distance squared plt.figure(5) plt.xlabel('Number of beads') plt.xlim(0,c.nBeads) plt.ylabel('End-to-end distance squared') plt.errorbar(x,weightedEndtoendSq,yerr=weightedEndtoendSqStd, label='Data') plt.plot(x,fittedWeightedEndtoendSq,color = "r", label='Fit') plt.plot(popSize, color = "g", label='Population') plt.xscale('log') plt.yscale('log') plt.xlim([3,c.nBeads]) plt.legend(loc='best')
def plotGyradiusSq(weightedGyradiusSq,weightedGyradiusSqStd,fittedGyradius,popSize): x = np.linspace(1,c.nBeads, c.nBeads); # Plot the gyradius plt.figure(6) plt.xlabel('Number of beads') plt.xlim(0,c.nBeads) plt.ylabel('Ensemble average $R_g^2$') plt.errorbar(x,weightedGyradiusSq,yerr=weightedGyradiusSqStd, label='Data') plt.plot(x,fittedGyradius,color = "r", label='Fit') plt.plot(popSize, color = "g", label='Population') plt.xscale('log') plt.yscale('log') plt.xlim([3,c.nBeads]) plt.legend(loc='best')
def plot_results(main_dir, target_dir): mean_std_tuples = [read_files(join(main_dir, folder)) for folder in listdir(main_dir) if isdir(join(main_dir, folder))] mean, std_dev = zip(*mean_std_tuples) mus = range(0,11) plt.gca().set_color_cycle(['black', 'orange', 'deeppink', 'green', 'blue']) fmts = ['>-', 'o-', 'x-', 'D-', 'p-'] exps = [folder for folder in listdir(main_dir) if isdir(join(main_dir, folder))] for i in range(len(mean)): plt.errorbar(mus, mean[i], yerr=std_dev[i], fmt=fmts[i]) plt.legend(exps, loc='lower right') plt.xlim((-0.2,10.2)) #plt.axis((0,11, 0.1, 0.8)) plt.grid(True) x_ticks = ['0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9','1'] plt.xticks(mus, x_ticks) plt.xlabel('mu') plt.ylabel('Log Probability') #plt.show() plt.savefig(join(target_dir, "mu_relu.png"), bbox_inches='tight')
def plot_performance_quantiles(): folder_path = 'logs/searcher_comparison' searchers = ['rand', 'mcts', 'mcts_bi', 'smbo'] search_space_type = 'deepconv' num_repeats = 5 for searcher_type in searchers: # load all the pickles rs = [] for i in xrange(num_repeats): file_name = '%s_%s_%d.pkl' % (search_space_type, searcher_type, i) file_path = os.path.join(folder_path, file_name) with open(file_path, 'rb') as f: r = pickle.load(f) rs.append(r) percents = np.linspace(0.0, 1.0, num=100) srch_scores = [compute_percentiles(r['scores'], percents) for r in rs] mean = np.mean(srch_scores, axis=0) std = np.std(srch_scores, axis=0) plt.errorbar(percents, mean, yerr=std / np.sqrt(num_repeats), label=searcher_type) plt.legend(loc='best') plt.xlabel('Validation performance') plt.ylabel('Fraction of models better or equal') #plt.title('') # plt.axis([0, 64, 0.6, 1.0]) # plt.show() plt.savefig(figs_folderpath + 'quants.pdf', bbox_inches='tight') plt.close()
def meanSwapsErrorBars(datafile): df = pd.read_csv(datafile, delimiter=" ") grouped = df.groupby("num_words", as_index=True) idx = grouped.groups.keys() plt.errorbar(idx, grouped.mean()["swap"], yerr=grouped.std(ddof=0)["swap"], fmt='o') plt.show() plt.close()
def plot_debye(s, ax): x = np.log10(s["data"]["tau"]) x = np.linspace(min(x), max(x),100) y = 100*np.sum([a*(x**i) for (i, a) in enumerate(s["params"]["a"])], axis=0) # ax.errorbar(10**x[(x>-6)&(x<2)], y[(x>-6)&(x<2)], None, None, "-", color='lightgray',linewidth=1, label="RTD estimations (%d)"%len(sol)) ax.set_xlabel("Relaxation time (s)", fontsize=14) ax.set_ylabel("Chargeability (%)", fontsize=14) plt.yticks(fontsize=14), plt.xticks(fontsize=14) plt.xscale("log") ax.set_xlim([1e-6, 1e1]) ax.set_ylim([0, 5.0])
def plot_data(sol, ax): data = sol["data"] f = data["freq"] Zr0 = max(abs(data["Z"])) zn_dat = old_div(data["Z"],Zr0) zn_err = old_div(data["Z_err"],Zr0) # Real-Imag plt.axes(ax[1]) # plt.errorbar(f, -zn_dat.imag, zn_err.imag, None, '.b', label='Synthetic data\n(%d mrad noise)'%noise,zorder=2) plt.errorbar(f, -zn_dat.imag, zn_err.imag, None, '.b', label='Laboratory data',zorder=2) plt.axes(ax[0]) plt.errorbar(f, zn_dat.real, zn_err.real, None, '.b', label='Laboratory data',zorder=2)
def plot_pull(data, func): import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator ax, bx = make_split(0.8) plt.sca(ax) x, y, norm = histpoints(data) lower, upper = ax.get_xlim() xs = np.linspace(lower, upper, 200) plt.plot(xs, norm * func(xs), 'b-') #plt.gca().yaxis.set_major_locator(MaxNLocator(prune='lower')) plt.sca(bx) resid = y[1] - norm * func(x) err = np.zeros_like(resid) err[resid >= 0] = y[0][resid >= 0] err[resid < 0] = y[2][resid < 0] pull = resid / err plt.errorbar(x, pull, yerr=1, color='k', fmt='o') plt.ylim(-5, 5) plt.axhline(0, color='b') plt.sca(ax) return ax, bx
def stat_plots(self, start_time, end_time): """Make 3 plots with different levels of zoom and save them as PNG files.""" t = np.arange(DUOTONE_START, DUOTONE_END, dtype=float) / FAST_BITRATE min_delta = self.stats['mean'] - self.stats['min'] max_delta = self.stats['max'] - self.stats['mean'] title = ('Mean DuoTone Signal, {}, near Zero Crossing\n' 'with Max/Min Values and Std. Dev.').format(self.channel) xlabel = r'Time since start of second ($\mu s$)' fname_fmt_fmt = '{}-DuoTone-Statistics-{}-from-{}-to-{}.png' fname_fmt = fname_fmt_fmt.format(self.channel.replace(':', '..'), '{}', start_time, end_time) # first figure, full view plt.close(1) plt.figure(1) plt.plot(t, self.stats['mean'], 'k') plt.errorbar(t*NS_PER_SEC, self.stats['mean'], yerr=[min_delta, max_delta], fmt='k') plt.errorbar(t*NS_PER_SEC, self.stats['mean'], yerr=self.stats['sigma'], fmt='go', linewidth=4) plt.title(title) plt.xlabel(xlabel) plt.grid(b=True, which='major', color='#262626', linestyle='--') plt.savefig(fname_fmt.format('full')) # second file, zoomed on zero-crossing best fit line plt.xlim(49.5, 52.) plt.ylim(-50, 50) plt.title(title + ' at zero crossing') plt.savefig(fname_fmt.format('zero-crossing-zoom')) # third file, zoomed on data point nearest zero-crossing plt.title(title + ', Error Bars Emphasized') plt.xlim(61, 61.1) plt.ylim(250, 260) plt.savefig(fname_fmt.format('super-zoom'))
def myplot(self,chain): # optional for plotting plt.clf() x = np.linspace(0,10) burn=self.chain['m'].size/2 vals=self.best_fit(burn=burn) plt.errorbar(self.args['x'], self.args['y'], yerr=self.args['sigma_y'], fmt=".k") plt.errorbar(self.args['x'][self.ind], self.args['y'][self.ind], yerr=self.args['sigma_y'][self.ind], fmt=".r") plt.plot(x,vals[0]*x+vals[1], color="g", lw=2, alpha=0.5) for i,key in enumerate(self.names0): print key plt.text(0.5,0.3-i*0.06,self.descr[key][3]+'='+bmcmc.stat_text(self.chain[key][burn:]),transform=plt.gca().transAxes) vals1=[] burn1=chain['m'].size/2 for i,key in enumerate(['m','c']): print key plt.text(0.05,0.5-i*0.05,self.descr[key][3]+'='+bmcmc.stat_text(chain[key][burn1:]),transform=plt.gca().transAxes) vals1.append(np.mean(chain[key][burn1:])) plt.plot(x,vals1[0]*x+vals1[1], 'g--', lw=2, alpha=0.5) plt.xlabel(r'$x$') plt.ylabel(r'$y$') plt.axis([0,10,5,40,]) # Expected values are #('m','c','p_b','mu_b','sigma_b')=(2.0, 10.0, 0.2, 30, 5.0')
def main(): # loop over the submission file names in sys.argv # for each file, plot the attributes in 'series' fig,ax = setup_plot(YNAME) fxticks,fxlabels,fxticks2,fxlabels2 = [],[],[],[] for i,submission_file in enumerate(sys.argv[1:]): print('processing submission: {}'.format(submission_file)) color = COLORS[i] score = classAP(submission_file) baseline = np.mean([x[1] for x in score.iteritems()]) xticks,xlabels,xticks2,xlabels2,count = [],[],[],[],1 for j,serie in enumerate(series): print(' processing attribute: {}'.format(serie['title'])) title,groups,attributetype,header = serie['title'],serie['groups'],serie['type'],serie['header'] newdata = make_data(title,groups,attributetype,submission_file,baseline) pos,count = update_locs(groups,j,count,header) if newdata==[]: continue plt.plot([pos[0],pos[-1]],[baseline]*2,color=color,marker=None,linestyle=":",linewidth=1) error = [x[2] for x in newdata] if ERRORBARS=='none': error=None h=plt.errorbar(pos, [x[1] for x in newdata],color=color,marker=None, linestyle="-",linewidth=3,yerr=error,clip_on=False) xticks += [x for x in pos] xlabels += TICKNAMES[len(groups)] xticks2 += [(pos[0]+pos[-1])/2.] xlabels2 += [title] if i==0: fxticks,fxlabels,fxticks2,fxlabels2 = xticks,xlabels,xticks2,xlabels2 handles.append(h) finalize_plot(ax,fxticks,fxlabels,fxticks2,fxlabels2) plt.savefig(plotname+'.pdf',bbox_inches='tight') plt.show()
def plot_results(self, plot_path=None, ylim=None): # Plotting parameters label_size = 18 mpl.rcParams['xtick.labelsize'] = label_size mpl.rcParams['ytick.labelsize'] = label_size plot_params = dict() plot_params['ms'] = 10 plot_params['linewidth'] = 3 # Plot training bound on the perplexity f = plt.figure(figsize=[12, 12]) plt.errorbar(self.epochs_eval, [self.lower_bound_train_all[i] for i in self.epochs_eval], [self.lower_bound_train_all_std[i] for i in self.epochs_eval], marker='d', color='b', label='Train', **plot_params) plt.plot(self.epochs_eval, self.lower_bound_valid_all, "-rh", label="Valid", **plot_params) plt.plot(self.epochs_eval, self.lower_bound_test_all, "-k^", label="Test", **plot_params) plt.xlabel('Epochs', fontsize=20) plt.grid('on') plt.title('ELBO', fontsize=24, y=1.01) plt.legend(loc="lower right", handlelength=3, fontsize=20) if ylim is not None: plt.ylim(ylim) if plot_path is not None: plt.savefig(plot_path + "_epochs.png", format='png', bbox_inches='tight', dpi=200) plt.close(f) # Plot norm of the updates f = plt.figure(figsize=[12, 12]) plt.errorbar(self.epochs_eval, [self.mean_norm_all[i] for i in self.epochs_eval], [self.std_norm_all[i] for i in self.epochs_eval], marker='d', color='m', **plot_params) plt.grid('on') plt.title('Norm of the updates', fontsize=24, y=1.01) if plot_path is not None: plt.savefig(plot_path + "_norm.png", format='png', bbox_inches='tight', dpi=200) plt.close(f)
def plot_results(self, plot_path=None, ylim=None): # Plotting parameters label_size = 18 mpl.rcParams['xtick.labelsize'] = label_size mpl.rcParams['ytick.labelsize'] = label_size plot_params = dict() plot_params['ms'] = 10 plot_params['linewidth'] = 3 # Plot training bound on the perplexity f = plt.figure(figsize=[12, 12]) plt.errorbar(self.epochs_eval, [self.elbo_seq_train_all[i] for i in self.epochs_eval], [self.elbo_seq_train_all_std[i] for i in self.epochs_eval], marker='d', color='b', label='Train', **plot_params) plt.plot(self.epochs_eval, self.elbo_seq_valid_all, "-rh", label="Valid", **plot_params) plt.plot(self.epochs_eval, self.elbo_seq_test_all, "-k^", label="Test", **plot_params) plt.xlabel('Epochs', fontsize=20) # plt.ylabel('log()', fontsize=20) plt.grid('on') plt.title('ELBO sequence', fontsize=24, y=1.01) plt.legend(loc="upper right", handlelength=3, fontsize=20) if ylim is not None: plt.ylim(ylim) if plot_path is not None: plt.savefig(plot_path + "_epochs.png", format='png', bbox_inches='tight', dpi=200) plt.close(f) # Plot norm of the updates f = plt.figure(figsize=[12, 12]) plt.errorbar(self.epochs_eval, [self.mean_norm_all[i] for i in self.epochs_eval], [self.std_norm_all[i] for i in self.epochs_eval], marker='d', color='m', **plot_params) plt.grid('on') plt.title('Norm of the updates', fontsize=24, y=1.01) if plot_path is not None: plt.savefig(plot_path + "_norm.png", format='png', bbox_inches='tight', dpi=200) plt.close(f)
def plotter(self): """ Plots the data and the fit. """ plt.title('Efficiency Curve') plt.xlabel('Energy (keV)') plt.ylabel('Efficiency') plt.errorbar(self.energy, self.values, fmt=None, yerr=self.unc) plt.plot(self.energy, self.values, 'ro') plt.grid() plt.plot(self.space, self.new_fit) plt.legend(('Data Points', 'Fitted Curve'), loc='upper right') plt.ylim(0, 0.002) plt.show()
def plot_input_scaling(results, outfile): parsed_results = parse_shard_results(results) pyplot.xlabel('Number of inputs per transaction') pyplot.ylabel('Average transactions / second') pyplot.grid(True) pyplot.errorbar( range(1, len(parsed_results)+1), [i[0] for i in parsed_results], [i[1] for i in parsed_results], marker='o', ) pyplot.savefig(outfile) pyplot.close()
def plot_node_scaling(results, outfile, step): parsed_results = parse_shard_results(results) pyplot.xlabel('Number of replicas per shard') pyplot.ylabel('Average transactions / second') pyplot.grid(True) pyplot.errorbar( range(4, 4+len(parsed_results)*step, step), [i[0] for i in parsed_results], [i[1] for i in parsed_results], marker='o', ) pyplot.savefig(outfile) pyplot.close()
def plot_coherence(xdata, ydata, std_error, fit, fit_function, xunit, exp_str, qubit_label): """Plot coherence data. Args: xdata ydata std_error fit fit_function xunit exp_str qubit_label """ plt.errorbar(xdata, ydata, std_error, marker='.', markersize=9, c='b', linestyle='') plt.plot(xdata, fit_function(xdata, *fit), c='r', linestyle='--', label=(exp_str + '= %s %s' % (str(round(fit[1])), xunit))) plt.xticks(fontsize=14, rotation=70) plt.yticks(fontsize=14) plt.xlabel('time [%s]' % (xunit), fontsize=16) plt.ylabel('P(1)', fontsize=16) plt.title(exp_str + ' measurement of Q$_{%s}$' % (str(qubit_label)), fontsize=18) plt.legend(fontsize=12) plt.grid(True) plt.show()
def plot_rb_data(xdata, ydatas, yavg, yerr, fit, survival_prob, ax=None, show_plt=1): """Plot randomized benchmarking data. xdata = list of subsequence lengths ydatas = list of lists of survival probabilities for each sequence yavg = mean of the survival probabilities at each sequence length yerr = error of the survival fit = fit parameters survival_prob = function that computes survival probability ax: plot axis (if passed in) """ if ax is None: plt.figure() ax = plt.gca() # Plot the result for each sequence for ydata in ydatas: ax.plot(xdata, ydata, color='gray', linestyle='none', marker='x') # Plot the mean with error bars ax.errorbar(xdata, yavg, yerr=yerr, color='r', linestyle='--', linewidth=3) # Plot the fit ax.plot(xdata, survival_prob(xdata, *fit), color='blue', linestyle='-', linewidth=2) ax.tick_params(labelsize=14) #ax.tick_params(axis='x',labelrotation=70) ax.set_xlabel('Clifford Length', fontsize=16) ax.set_ylabel('Z', fontsize=16) ax.grid(True) if show_plt: plt.show()
def plot_instcat_overlay(df, visit_name, component, fontsize='x-small'): """ Overlay the measured and instance catalog object sky positions. Parameters ---------- df : pandas.DataFrame Data frame containing the true and measured coordinates and magnitudes and position offsets. visit_name : str Visit name combining the visit number and filter, e.g., 'v230-fr'. component : str Name of the component, e.g., 'R2:2' (for the full center raft), 'R:2,2 S:1,1' (for the central chip). fontsize : str or int, optional Font size to use in plots. Default: 'x-small' Returns ------- (float, float, float, float) Axis (xmin, xmax, ymin, ymax) values in data coordinates. """ plt.errorbar(df['coord_ra'], df['coord_dec'], fmt='.', label='measured position') plt.scatter(df['coord_ra_true'], df['coord_dec_true'], s=60, label='true position', facecolors='none', edgecolors='r') plt.xlabel('RA (deg)', fontsize=fontsize) plt.ylabel('Dec (deg)', fontsize=fontsize) plt.legend(fontsize=fontsize) plt.title('%(visit_name)s, %(component)s' % locals(), fontsize=fontsize) return plt.axis()
def plot_errorbars(x, y, yerrlow, yerrhigh, plot_kws=None, err_kws=None, *args, **kwargs): yerr = [yerrlow, yerrhigh] err_kws_final = kwargs.copy() err_kws_final.update(err_kws) err_kws_final.update({'marker': "", 'fmt':'none', 'label':'', "zorder":3}) plot_kws_final = kwargs.copy() plot_kws_final.update(plot_kws) plt.plot(x, y, **plot_kws_final) plt.errorbar(x, y, yerr, **err_kws_final) return None
def plot_pair_by_relation_distance_wrt_layer(labels, diffs_2_1, diffs_3_1, diffs_4_1, diffs_2_1_std, diffs_3_1_std, diffs_4_1_std, proportions, fignum, filename, title, plot_lines=False): xs = np.arange(1, len(labels)+1) #matplotlib.rcParams.update({'font.family': 'sans-serif'}) fig = plt.figure(fignum) #default_size = fig.get_size_inches() #fig.set_size_inches( (default_size[0]*1.3, default_size[1]*1.3) ) if plot_lines: plt.errorbar(xs, diffs_2_1, yerr=diffs_2_1_std, label='Layer 2', alpha=0.7, marker='', color=plt.cm.Greens(.8)) plt.errorbar(xs, diffs_3_1, yerr=diffs_3_1_std, label='Layer 3', alpha=0.7, marker='', color=plt.cm.Reds(.8)) plt.errorbar(xs, diffs_4_1, yerr=diffs_4_1_std, label='Layer 4', alpha=0.7, marker='', color=plt.cm.Blues(.8)) else: plt.scatter(xs, diffs_2_1, c=proportions, s=100, cmap='Greens', edgecolors='black', linewidths=1, label='Layer 2', alpha=0.7) plt.scatter(xs, diffs_3_1, c=proportions, s=100, cmap='Reds', edgecolors='black', linewidths=1, label='Layer 3', alpha=0.7) plt.scatter(xs, diffs_4_1, c=proportions, s=100, cmap='Blues', edgecolors='black', linewidths=1, label='Layer 4', alpha=0.7) plt.xticks(xs, labels) plt.ylabel('Increase in accuracy w.r.t layer 1', fontsize='large') plt.xlabel('Relation distance', fontsize='large') plt.legend(loc='upper left', markerscale=1, fontsize='medium', frameon=True, title='Legend', edgecolor='black', labelspacing=1) ax = plt.gca() legend = ax.get_legend() legend.legendHandles[0].set_color(plt.cm.Greens(.8)) legend.legendHandles[1].set_color(plt.cm.Reds(.8)) legend.legendHandles[2].set_color(plt.cm.Blues(.8)) if plot_lines: pass #legend.legendHandles[0]._legmarker.set_color(plt.cm.Greens(.8)) #legend.legendHandles[1]._legmarker.set_color(plt.cm.Reds(.8)) #legend.legendHandles[2]._legmarker.set_color(plt.cm.Blues(.8)) #legend.get_frame().set_alpha(0.5) plt.title(title, fontsize='large') plt.tight_layout() plt.savefig(filename, dpi=(200))
def plot_learning_function(xdata, ydata, yerr, order, aplot, poly): with sns.axes_style('whitegrid'): sns.set_context('paper') xp = np.linspace(np.min(xdata), np.max(xdata), 1000)[:, None] plt.figure() plt.errorbar(xdata, ydata, yerr, label='Nearest similarity', marker='s') plt.plot(xp, poly(xp), '-', label='Learning function (poly of order {})'.format(order)) # plt.plot(xp, least_squares_mdl(res.x, xp), '-', label='least squares') plt.xlabel(r'Mutation level') plt.ylabel(r'Average similarity (not normalised)') plt.legend(loc='lower left') plt.savefig(aplot, transparent=True, bbox_inches='tight') plt.close()
def plot(self, samples, title): """ Plot core process time of chainer and pytorch. """ batch_sizes = [2**m for m in range(self.max_batch_index + 1)] process_time = {'chainer': {'mean': [], 'std': []}, 'pytorch': {'mean': [], 'std': []}} for batch_size in tqdm(batch_sizes, desc='batch size'): for name, process in tqdm(self.process.items(), desc='testers'): # set batch size. process.set_batch_size(batch_size) compute_time = [] # get compute time. for index in trange(samples, desc='samples'): start = time.time() process.run(self.only_inference) compute_time.append(time.time() - start) # calculate mean and std. process_time[name]['mean'].append(np.mean(compute_time)) process_time[name]['std'].append(np.std(compute_time)) # plot core process time of each batch size. for name, p_t in process_time.items(): plt.errorbar(batch_sizes, p_t['mean'], yerr=p_t['std'], label=name) # plot settings. plt.title(title) plt.legend(loc='lower right') plt.xlabel('batch size') plt.ylabel('core process time [sec]') # save plot. if self.debug: plt.show() else: filename = '_'.join(title.split(' ')) + '.png' plt.savefig(os.path.join(self.output, filename))
def plot_interpolation(box_array, metric, resource, experiment_type='changeme!', service='changeme!', container_id='changeme!'): median_box = [numpy.median(increment_result) for increment_result in box_array] x = [0, 20, 40, 60, 80] # x = [0, 50] # TESTING std_dev = [numpy.std(increment_result) for increment_result in box_array] plt.xlim(-5, 85) font = {'family':'serif','serif':['Times']} if len(service) < 15: plt.title('Exp: \"{}\" Service: \"{}...\" Container: \"{}\"'.format(experiment_type, service, container_id), fontname="Times New Roman", size=18) else: plt.title('Exp: \"{}\" Service: \"{}...\" Container: \"{}\"'.format(experiment_type, service[:15], container_id), fontname="Times New Roman", size=18) plt.ylabel('{} (ms)'.format(metric), fontname="Times New Roman", size=16) plt.xlabel('Percentage Resource Stressed', fontname="Times New Roman", size=16) if resource == 'CPU': line_color = '#990000' error_length = 1 elif resource == 'Disk': line_color = 'black' error_length = 1.5 elif resource == 'Network': line_color = '#999999' error_length = 2 line, = plt.plot(x, median_box, lw=3, label=resource, color=line_color) # plt.legend(handles=[line]) plt.errorbar(x, median_box, std_dev, lw=error_length, color=line_color) return line
def plot_psuedotime_uncertainty(self, **kwargs): yerr = 2 * np.sqrt(self.time_model.X.variance) plt.errorbar(self.s['pseudotime'], self.s['pseudotime'], yerr=yerr, fmt='none') plt.scatter(self.s['pseudotime'], self.s['pseudotime'], zorder=2, **kwargs)
def draw_error_bars(pltnum, x, mean, ulimit, llimit, x_label, y_label=None, do_log=True): ax = plt.subplot(pltnum) plt.xlabel(x_label, fontsize=18) if y_label is not None: plt.ylabel(y_label, fontsize=18) if do_log: ax.set_yscale('log') plt.errorbar(x, mean, yerr=[llimit, ulimit], ms=5, mew=2, fmt='--o')
def Display(curvelist): """ Take a list of curve and plot it according to its type @type curvelist: list of curve @param curvelist: list of curve for plotting @todo: improve the display with legend, color... """ plt.figure(figsize=(12,8)) # sets figure size axes = plt.gca() # Something for astronomers only : we invert the y axis direction ! axes.set_ylim(axes.get_ylim()[::-1]) # Astronomers like minor tick marks : minorxLocator = MultipleLocator(100) for curve in curvelist: if curve.type=="purelightcurve": plt.plot(linspace(0,curve.length,curve.length*curve.res),curve.data) if curve.type=="simlightcurve": if curve.name=="A": plt.plot(np.linspace(0,curve.originalcurve.length,curve.originalcurve.length*curve.originalcurve.res),curve.originalcurve.data+curve.dmag,color="black",label="Original curve") plt.errorbar(curve.datatime,curve.datamagoff(),curve.dataerr,ls='None',marker='.',ecolor="#BBBBBB", color=curve.plotcolor,label=str(curve.name)+str(curve.shift)) plt.plot(np.linspace(0,curve.originalcurve.length,curve.originalcurve.length*curve.originalcurve.res),curve.mlcurve.data+curve.dmag,color=curve.plotcolor)#,label="microlensing for "+str(curve.name)) plt.xlabel('time [j]') plt.ylabel('Magnitude ') plt.legend( numpoints = 1, prop = fm.FontProperties(size = 10)) plt.show()
def plot_data(self): # Plot results fplot, = plt.plot(self.t, self.fit, 'ro-', label='y(t|B)') splot, = plt.plot(self.t, self.y, 'go-', label="y(t)") tplot = plt.errorbar(self.t, self.yt, yerr=self.perts, fmt='bo-', label="data") plt.legend(handles = [fplot, splot, tplot]) plt.ylabel('z') plt.xlabel('time(days)') plt.show()
def ratingsOverAge(df): df = df[np.isfinite(df['Rating'])] df = df.loc[df['Submission Age'] <= 30] gendered = df.groupby(['Submission Gender']) for gender, group in gendered: ageRatings = collections.defaultdict(list) perSubmission = group.groupby(['Folder']) for submission, group in perSubmission: submissionMean = [] for index, row in group.iterrows(): submissionMean.append(int(row["Rating"])) ageRatings[int(row['Submission Age'])].append(np.mean(reject_outliers(np.array(submissionMean)))) X = [] Y = [] std = [] for age in ageRatings: X.append(age) Y.append(np.mean(ageRatings[age])) std.append(np.std(ageRatings[age])) title = genderName[gender] + " Attractiveness Over Age" plt.errorbar(X, Y, yerr=std, fmt='-', color=genderColor[gender]) # plt.plot(X,Y) plt.title(title, fontproperties=titleFont) plt.ylim(0,10) plt.savefig(title) plt.clf()
def errorbar(first, *args, **kwargs): """ Wrapper around matplotlib.pyplot.errorbar that also takes TH1 and TGraph see TH1.__errorbar__, TGraph.__errorbar__, or matplotlib.pyplot.errorbar for details """ if isinstance(first, gbl.TH1) or isinstance(first, gbl.TGraph): kwargs["axes"] = plt.gca() return first.__errorbar__(*args, **kwargs) else: return plt.errorbar(first, *args, **args)
def display_graph(self, file=None): if file: self.results = read_yaml(file) plt.close("all") plt.ioff() logging.info("profile graphs:{}".format(self.profile_graphs)) n = len(self.profile_graphs) plt.subplots(nrows=n, ncols=1) i = 1 for profile in self.profile_graphs: plt.subplot(n, 1, i) x_metric_id = profile['input_metric'] y_metric_id = profile['output_metric'] x_metrics = self._find_metrics(x_metric_id, self.results) x_values = [m['average'] for m in x_metrics] x_err_high = [m['CI_high']-m['average'] for m in x_metrics] x_err_low = [abs(m['CI_low']-m['average']) for m in x_metrics] x_unit = x_metrics[0]['unit'] y_metrics = self._find_metrics(y_metric_id, self.results) y_values = [m['average'] for m in y_metrics] y_err_high = [m['CI_high']-m['average'] for m in y_metrics] y_err_low = [abs(m['CI_low']-m['average']) for m in y_metrics] y_unit = y_metrics[0]['unit'] plt.xlabel('{0}({1})'.format(x_metric_id,x_unit)) plt.ylabel('{0}({1})'.format(y_metric_id, y_unit)) plt.title(profile['name']) plt.grid(b=True, which='both', color='lightgrey', linestyle='--') plt.errorbar(x_values, y_values, xerr=[x_err_low, x_err_high], yerr=[y_err_low, y_err_high], fmt='--o', capsize=2) i += 1 plt.tight_layout() plt.show()
def plotAverages(d,f): global MAXIMUMY y = [average(d[x]) for x in xs ] e = [standardError(d[x]) for x in xs ] plot.errorbar(xs,y,fmt = f,yerr = e) MAXIMUMY = max(y + [MAXIMUMY])
def plotBernoulli(d,f): global MAXIMUMY d = [ [ (1 if z == 1 else 0) for z in d[x] ] for x in xs ] y = [average(z) for z in d ] e = [ bernoulliStandardError(z) for z in d ] plot.errorbar(xs,y,fmt = f,yerr = e) MAXIMUMY = max(y + [MAXIMUMY])
def plot_degree_poly_l(Y): """ Same than plot_degree_poly, but for a list of random graph ie plot errorbar.""" x, y, yerr = random_degree(Y) plt.xscale('log'); plt.yscale('log') fit = np.polyfit(np.log(x), np.log(y), deg=1) plt.plot(x,np.exp(fit[0] *np.log(x) + fit[1]), 'm:', label='model power %.2f' % fit[1]) leg = plt.legend(loc='upper right',prop={'size':10}) plt.errorbar(x, y, yerr=yerr, fmt='o') plt.xlim(left=1) plt.ylim((.9,1e3)) plt.xlabel('Degree'); plt.ylabel('Counts')