我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.grid()。
def calc_auc(y_pred_proba, labels, exp_run_folder, classifier, fold): auc = roc_auc_score(labels, y_pred_proba) fpr, tpr, thresholds = roc_curve(labels, y_pred_proba) curve_roc = np.array([fpr, tpr]) dataile_id = open(exp_run_folder+'/data/roc_{}_{}.txt'.format(classifier, fold), 'w+') np.savetxt(dataile_id, curve_roc) dataile_id.close() plt.plot(fpr, tpr, label='ROC curve: AUC={0:0.2f}'.format(auc)) plt.xlabel('1-Specificity') plt.ylabel('Sensitivity') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.grid(True) plt.title('ROC Fold {}'.format(fold)) plt.legend(loc="lower left") plt.savefig(exp_run_folder+'/data/roc_{}_{}.pdf'.format(classifier, fold), format='pdf') return auc
def plot_axes_scaling(self, iabscissa=1): from matplotlib import pyplot if not hasattr(self, 'D'): self.load() dat = self if np.max(dat.D[:, 5:]) == np.min(dat.D[:, 5:]): pyplot.text(0, dat.D[-1, 5], 'all axes scaling values equal to %s' % str(dat.D[-1, 5]), verticalalignment='center') return self # nothing interesting to plot self._enter_plotting() pyplot.semilogy(dat.D[:, iabscissa], dat.D[:, 5:], '-b') # pyplot.hold(True) pyplot.grid(True) ax = array(pyplot.axis()) # ax[1] = max(minxend, ax[1]) pyplot.axis(ax) pyplot.title('Principle Axes Lengths') # pyplot.xticks(xticklocs) self._xlabel(iabscissa) self._finalize_plotting() return self
def _plot_epc(scores_dev, scores_eval, colors, labels, title, fontsize=10, position=None): if position is None: position = 'upper center' # open new page for current plot figure = pyplot.figure() # plot the DET curves for i in range(len(scores_dev)): x,y = bob.measure.epc(scores_dev[i][0], scores_dev[i][1], scores_eval[i][0], scores_eval[i][1], 100) pyplot.plot(x, y, color=colors[i], label=labels[i]) # change axes accordingly pyplot.xlabel('alpha') pyplot.ylabel('HTER') pyplot.title(title) pyplot.axis([-0.01, 1.01, -0.01, 0.51]) pyplot.grid(True) pyplot.legend(loc=position, prop = {'size':fontsize}) pyplot.title(title) return figure
def save_fft(fil,audio_in): samples = len(audio_in) fft_size = 2**int(floor(log(samples)/log(2.0))) freq = fft(audio_in[0:fft_size]) s_data = numpy.zeros(fft_size/2) x_data = numpy.zeros(fft_size/2) peak = 0; for j in xrange(fft_size/2): if (abs(freq[j]) > peak): peak = abs(freq[j]) for j in xrange(fft_size/2): x_data[j] = log(2.0*(j+1.0)/fft_size); if (x_data[j] < -10): x_data[j] = -10 s_data[j] = 10.0*log(abs(freq[j])/peak)/log(10.0) plt.ylim([-50,0]) plt.plot(x_data,s_data) plt.title('fft log power') plt.grid() fields = fil.split('.') plt.savefig(fields[0]+'_fft.png', bbox_inches="tight") plt.clf() plt.close()
def plot_color_data(x,y,z=None, axh=None, show = True, cieobs =_cieobs, cspace = _cspace, formatstr = 'k-', **kwargs): """ Plot data. """ if 'grid' in kwargs.keys(): plt.grid(kwargs['grid']);kwargs.pop('grid') if z is not None: plt.plot(x,y,z,formatstr, linewidth = 2) plt.xlabel(_cspace_axes[cspace][0], kwargs) else: plt.plot(x,y,formatstr,linewidth = 2) plt.xlabel(_cspace_axes[cspace][1], kwargs) plt.ylabel(_cspace_axes[cspace][2], kwargs) if show == True: plt.show() else: return plt.gca()
def plot_axes_scaling(self, iabscissa=1): if not hasattr(self, 'D'): self.load() dat = self self._enter_plotting() pyplot.semilogy(dat.D[:, iabscissa], dat.D[:, 5:], '-b') pyplot.hold(True) pyplot.grid(True) ax = array(pyplot.axis()) # ax[1] = max(minxend, ax[1]) pyplot.axis(ax) pyplot.title('Principle Axes Lengths') # pyplot.xticks(xticklocs) self._xlabel(iabscissa) self._finalize_plotting() return self
def boll(): #??tushare?????? df=ts.get_k_data('300580',start='2017-01-12',end='2017-05-26') #????? closed=df['close'].values upper,middle,lower=talib.BBANDS(closed,matype=talib.MA_Type.SMA) print upper,middle,lower plt.plot(upper) plt.plot(middle) plt.plot(lower) plt.grid() plt.show() diff1=upper-middle diff2=middle-lower print diff1 print diff2
def hist_test(): mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) # ?????? n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75) plt.xlabel('Smarts') plt.ylabel('Probability') #???? plt.title('Histogram of IQ') #???? plt.text(60, .025, r'$mu=100, sigma=15$') plt.axis([40, 160, 0, 0.03]) plt.grid(True) plt.show()
def distribution(y, title='',xLabel='',yLabel='',savePath='../visual/visualization/p1'): fig, ax1 = plt.subplots(1, 1, figsize=(8, 6), sharex=True) #sns.set(style="white") x = np.linspace(0, len(y), len(y)) y.sort(reverse = True) plt.plot(x, y, color='green') ax1.set_xlabel(xLabel, fontsize=16) ax1.set_ylabel(yLabel, fontsize=16) ax1.set_xlim(0, len(y)) # ax1.set_ylim(0,25000) ax1.set_title(title, fontsize=20) ax1.tick_params(axis='x', labelsize=16) ax1.tick_params(axis='y', labelsize=16) plt.grid(True) plt.savefig(savePath,bbox_inches='tight') #plt.show() plt.close('all')
def scatter(x, y, color, title='',xLabel='',yLabel='',savePath='../visual/visualization/p2'): fig, ax1 = plt.subplots(1, 1, figsize=(8, 6), sharex=True) # sns.set(style="white") ax1.set_ylim(-10, max(y) + 20) ax1.set_xlim(-10, max(x) + 20) ax1.set_title(title, fontsize=20) ax1.set_xlabel(xLabel, fontsize=16) ax1.set_ylabel(yLabel, fontsize=16) ax1.tick_params(axis='x', labelsize=16) ax1.tick_params(axis='y', labelsize=16) plt.scatter(x, y, c=color, alpha=0.7, ) plt.grid(True) plt.savefig(savePath,bbox_inches='tight') #plt.show() plt.close('all')
def hist(x,y, bins, color,title='',xLabel='',yLabel='',savePath='../visual/visualization/p3'): fig, ax1 = plt.subplots(1, 1, figsize=(8, 6)) #sns.set(style="white") ax1.grid(True) ax1.set_title(title, fontsize=20) ax1.set_xlabel(xLabel, fontsize=16) ax1.set_ylabel(yLabel, fontsize=16) ax1.tick_params(axis='x', labelsize=16) ax1.tick_params(axis='y', labelsize=16) ind = np.arange(0,1,1.0/len(x)) ax1.set_xticks(ind+1.0/(2*len(x))) ax1.set_xticklabels(x) ax1.hist(y, bins, color=color) plt.savefig(savePath,bbox_inches='tight') #plt.show() plt.close('all')
def draw(self): if not os.path.isdir(self.txt_folder): print "Folder not exist!" return False txt_file_list = os.listdir(self.txt_folder) for i in range(len(txt_file_list)): log_data_list = self.logparse(self.txt_folder + txt_file_list[i]) for j in range(len(log_data_list)): plt.figure() input_data = log_data_list[j]["data"] plt.hist(input_data) plt.grid() title_str = "epoch:%d, block:%d, layer:%d" % (log_data_list[j]["epoch"], log_data_list[j]["block"], log_data_list[j]["layer"]) plt.title(title_str) save_path = self.fig_folder + "epoch_%d_block_%d_layer_%d.png" % (log_data_list[j]["epoch"], log_data_list[j]["block"], log_data_list[j]["layer"]) plt.savefig(save_path, format="png") plt.close()
def model_visualization(y_true, y_pred): """ ??????? """ x = range(1, len(y_true) + 1) plt.figure(figsize=(10, 6)) plt.title('copper price forecast model evaluating') plt.xlabel('samples') plt.ylabel('actual price vs. predict price') plt.grid(x) plt.plot(x, y_true, '-', label='actual price') plt.plot(x, y_pred, '-', label='predict price') plt.legend(loc='upper right') plt.show()
def plot_loss(loss, val_loss): """ ????epochs?loss?val_loss """ x = range(1, len(loss) + 1) plt.figure(figsize=(10, 6)) plt.title('loss and val_loss of model') plt.xlabel('epochs') plt.ylabel('loss and val_loss') plt.grid(x) plt.plot(x, loss, '-', label='loss') plt.plot(x, val_loss, '-', label='val_loss') plt.legend(loc='upper right') plt.show()
def plot_gradients(self, foo=False): ''' Shows the difference between the computed gradients in the ANN modul and the numerically calculated gradients. ''' fig = plt.gcf() fig.canvas.set_window_title('Comparison of the computed gradients') numgrad, grad, qua, ok = ngc.compare_gradients(self.Net, self.inputdata_tr, self.outputdata_tr) print(qua, ok) y = numgrad-grad y2 = np.absolute(y) plt.bar(np.arange(1,len(y)+1), y) plt.grid(1) plt.xlabel('Gradient') plt.ylabel('Difference') plt.show() if foo: print('numgrad: ', numgrad) print('grad: ', grad) print('difference: ', y)
def plot_times(lab, element, time_slices=[0, 1, 2, 3, 4]): plt.figure() ax = plt.subplot(111) if element == 'Temperature': plt.title('Temperature profile') plt.xlabel('Temperature, C') else: plt.title(element + ' concentration') plt.xlabel('Concentration') plt.ylabel('Depth, cm') for tms in time_slices: lbl = 'at time: %.2f ' % (tms) plt.plot(lab.species[element]['concentration'][ :, int(tms / lab.dt)], -lab.x, lw=3, label=lbl) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), ncol=2) ax.grid(linestyle='-', linewidth=0.2) return ax
def plot_profile(lab, element): plt.figure() plt.plot(lab.profiles[element], -lab.x, sns.xkcd_rgb["denim blue"], lw=3, label=element) if element == 'Temperature': plt.title('Temperature profile') plt.xlabel('Temperature, C') elif element == 'pH': plt.title('pH profile') plt.xlabel('pH') else: plt.title('%s concentration' % (element, )) plt.xlabel('Concentration') plt.ylabel('Depth') ax = plt.gca() ax.ticklabel_format(useOffset=False) ax.grid(linestyle='-', linewidth=0.2) plt.legend() plt.tight_layout() return ax
def about_biographies_count(corpus): """ Finds how many items have/don't have a biography """ count = with_bio = characters = 0 for doc in load_scraped_items(corpus): count += 1 if doc.get('bio') and len(doc['bio']) > 5: with_bio += 1 characters += len(doc['bio']) print 'Total number of items:', count print 'Items with a biography %d (%.2f %%)' % (with_bio, 100. * with_bio / count) print 'Cumulative length of biographies: %d characters' % characters try: import matplotlib.pyplot as plt except ImportError: logger.warn('Cannot import matplotlib, skipping chart') return plt.bar([0, 1], [count - with_bio, with_bio], width=0.75) plt.xticks([0.375, 1.375], ['Without Biography', 'With Biography']) plt.grid(True, axis='y') plt.xlim((-0.5, 2.25)) plt.show()
def plot_loss(loss_list, log_dir, iter_id): def running_mean(x, N): cumsum = np.cumsum(np.insert(x, 0, 0)) return (cumsum[N:] - cumsum[:-N]) / N plt.figure() plt.semilogy(loss_list, '.', alpha=0.2, label="Loss") plt.semilogy(running_mean(loss_list,100), label="Average Loss") plt.xlabel('Iterations') plt.ylabel('Loss') plt.legend() plt.grid() ax = plt.subplot(111) ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), ncol=3, fancybox=True, shadow=True) plt.savefig(log_dir + "/fig_loss_iter_" + str(iter_id) + ".pdf") print("figure plotted") plt.close()
def generate_hills(width, height, nhills): ''' @param width float, terrain width @param height float, terrain height @param nhills int, #hills to gen. #hills actually generted is sqrt(nhills)^2 ''' # setup coordinate grid xmin, xmax = -width/2.0, width/2.0 ymin, ymax = -height/2.0, height/2.0 x, y = np.mgrid[xmin:xmax:STEP, ymin:ymax:STEP] pos = np.empty(x.shape + (2,)) pos[:, :, 0] = x; pos[:, :, 1] = y # generate hilltops xm, ym = np.mgrid[xmin:xmax:width/np.sqrt(nhills), ymin:ymax:height/np.sqrt(nhills)] mu = np.c_[xm.flat, ym.flat] sigma = float(width*height)/(nhills*8) for i in range(mu.shape[0]): mu[i] = multivariate_normal.rvs(mean=mu[i], cov=sigma) # generate hills sigma = sigma + sigma*np.random.rand(mu.shape[0]) rvs = [ multivariate_normal(mu[i,:], cov=sigma[i]) for i in range(mu.shape[0]) ] hfield = np.max([ rv.pdf(pos) for rv in rvs ], axis=0) return x, y, hfield
def save_texture(x, y, hfield, fname, path=None): ''' @param path, str (optional). If not provided, DEFAULT_PATH is used. Make sure this matches the <texturedir> of the <compiler> element in the env XML ''' path = _checkpath(path) plt.figure() plt.contourf(x, y, -hfield, 100, cmap=TERRAIN_CMAP) xmin, xmax = x.min(), x.max() ymin, ymax = y.min(), y.max() # for some reason plt.grid does not work here, so generate gridlines manually for i in np.arange(xmin,xmax,0.5): plt.plot([i,i], [ymin,ymax], 'k', linewidth=0.1) for i in np.arange(ymin,ymax,0.5): plt.plot([xmin,xmax],[i,i], 'k', linewidth=0.1) plt.savefig(os.path.join(path, fname), bbox_inches='tight') plt.close()
def iqplot(data, spec='.', labels=None): """Plot signal points. :param data: complex baseband signal points :param spec: plot specifier (see :func:`matplotlib.pyplot.plot`) :param labels: label for each signal point >>> import arlpy >>> arlpy.comms.iqplot(arlpy.comms.psk(8)) >>> arlpy.comms.iqplot(arlpy.comms.qam(16), 'rx') >>> arlpy.comms.iqplot(arlpy.comms.psk(4), labels=['00', '01', '11', '10']) """ import matplotlib.pyplot as plt data = _np.asarray(data) if labels is None: plt.plot(data.real, data.imag, spec) else: if labels == True: labels = range(len(data)) for i in range(len(data)): plt.text(data[i].real, data[i].imag, str(labels[i])) plt.axis([-2, 2, -2, 2]) plt.grid() plt.show()
def plot_training(history): """Plot the training curve. Parameters: history -- numpy array/list of cost values over all training iterations Returns: Plot of the cost for each iteration of training """ plt.plot(range(1, len(history)+1), history) plt.grid(True) plt.xlim(1, len(history)) plt.ylim(min(history), max(history)) plt.title("Training Curve") plt.xlabel("Iteration") plt.ylabel("Cost")
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_client_latency(results, outfile, start_tps, step): parsed_results = parse_client_latency_results(results) pyplot.xlabel('Client-perceived latency (ms)') pyplot.ylabel('Probability') pyplot.grid(True) for i, tps in enumerate(parsed_results): tps = [x*1000 for x in tps] pyplot.plot( tps, [j/float(len(tps)) for j in range(len(tps))], label=str(start_tps+i*step) + ' t/s', marker=markers.MarkerStyle.filled_markers[i], markevery=500, ) pyplot.legend() pyplot.savefig(outfile) pyplot.close()
def extract_grid_scores(model): ''' Extract grid scores from a model or pipeline. Parameters ---------- model : Estimator or Pipeline must end in sklearn.model_selection.GridSearchCV Returns ------- scores : list See Also -------- unpack_grid_scores ''' model = utils.model_from_pipeline(model) return model.grid_scores_
def plot_grid_scores(model, x, y=None, hue=None, row=None, col=None, col_wrap=None, **kwargs): ''' Wrapper around seaborn.factorplot. Parameters ---------- model : Pipeline or Estimator x, hue, row, col : str parameters grid searched over y : str the target of interest, default `'mean_'` Returns ------- g : seaborn.FacetGrid ''' scores = unpack_grid_scores(model) y = y or 'mean_' return sns.factorplot(x=x, y=y, hue=hue, row=row, col=col, data=scores, col_wrap=col_wrap, **kwargs)
def plot_hist(runornot): while runornot: plt.figure(1) timelist = ['year','month','day','hour','dayofweek'] layoutlist = [231,232,234,235,236] for timeiterm in timelist: plt.subplot(layoutlist[timelist.index(timeiterm)]) plt.hist(blog[timeiterm].values, bins = len(set(blog[timeiterm].values)), facecolor='blue', alpha=0.5) #plt.xlabel() plt.ylabel('freq') plt.title(timeiterm) #plt.text(60, .025, r'$\mu=100,\ \sigma=15$') #plt.axis([40, 160, 0, 0.03]) #plt.grid(True) plt.show() #.title('Histogram') plt.show()
def plot_numvisc(diagfile): plt.figure() nc = Dataset(diagfile) t=nc.variables['t'][:] ke=nc.variables['ke'][:] dkdt=np.diff(ke)/np.diff(t) ens=nc.variables['enstrophy'][:] ensm=0.5*(ens[1:]+ens[:-1]) # deltake[visc,res]=-(ke[-1]-ke[0]) # deltaens[visc,res]=max(medfilt(ens,21))-ens[5] visc_tseries = -dkdt/ensm*4.4*np.pi visc_num = max(visc_tseries[t[1:]>0.02]) #print('N=%4i / visc = %4.1e / num = %4.2e'%(N[res],Kdiff[visc],visc_num[res])) plt.semilogy(t[1:],visc_tseries) plt.xlabel('time') plt.ylabel('viscosity (-(1/2V)dE/dt)') plt.grid('on') plt.show()
def plot_grouping_result(group_id_set, group_ids, city_info): assert len(group_id_set) != 0 import matplotlib.pyplot as plt markers = ['p', '*', '+', 'x', 'd', 'o', 'v', 's', 'h'] colors = [(random.random(), random.random(), random.random()) for x in range(len(group_id_set))] while len(group_id_set) > 0: group_id = group_id_set.pop() clr = colors.pop() makr = markers[random.randint(0, len(markers)-1)] x = [] y = [] for idx, gid in enumerate(group_ids): if gid == group_id: x.append(city_info[idx][0]) y.append(city_info[idx][1]) plt.plot(x, y, color=clr, marker=makr) plt.ylabel('y') plt.xlabel('x') plt.grid(True) plt.show()
def plotLoss(trainDf, testDf, workDir): # fig, ax = plt.subplots(1, 1, figsize=(5,2)) fig, ax = plt.subplots(1, 1) # fig.tight_layout() trainEpoch = trainDf['epoch'].values trainLoss = trainDf['loss'].values N = len(trainEpoch) // math.ceil(trainEpoch[-1]) trainEpoch_, trainLoss_ = rolling(N, trainEpoch, trainLoss) plt.plot(trainEpoch_, trainLoss_, label='Train') # plt.plot(trainEpoch, trainLoss, label='Train') if not testDf.empty: plt.plot(testDf['epoch'].values, testDf['loss'].values, label='Test') plt.xlabel("Epoch") plt.ylabel("MSE") plt.xlim(xmin=0) plt.grid(b=True, which='major', color='k', linestyle='-') plt.grid(b=True, which='minor', color='k', linestyle='--', alpha=0.2) plt.legend() ax.set_yscale('log') for ext in ['pdf', 'png']: f = os.path.join(workDir, "loss."+ext) fig.savefig(f) print("Created {}".format(f))
def plotLoss(trainDf, testDf, workDir): # fig, ax = plt.subplots(1, 1, figsize=(5,2)) fig, ax = plt.subplots(1, 1) # fig.tight_layout() trainEpoch = trainDf['epoch'].values trainLoss = trainDf['loss'].values N = np.argmax(trainEpoch==1.0) trainEpoch = trainEpoch[N:] trainLoss = [sum(trainLoss[i-N:i])/N for i in range(N, len(trainLoss))] plt.plot(trainEpoch, trainLoss, label='Train') if not testDf.empty: plt.plot(testDf['epoch'].values, testDf['loss'].values, label='Test') plt.xlabel("Epoch") plt.ylabel("MSE") plt.xlim(xmin=0) plt.grid(b=True, which='major', color='k', linestyle='-') plt.grid(b=True, which='minor', color='k', linestyle='--', alpha=0.2) plt.legend() ax.set_yscale('log') for ext in ['pdf', 'png']: f = os.path.join(workDir, "loss."+ext) fig.savefig(f) print("Created {}".format(f))
def plotErr(trainDf, testDf, workDir): # fig, ax = plt.subplots(1, 1, figsize=(5,2)) fig, ax = plt.subplots(1, 1) # fig.tight_layout() trainEpoch = trainDf['epoch'].values trainLoss = trainDf['err'].values N = np.argmax(trainEpoch==1.0) trainEpoch = trainEpoch[N:] trainLoss = [sum(trainLoss[i-N:i])/N for i in range(N, len(trainLoss))] plt.plot(trainEpoch, trainLoss, label='Train') if not testDf.empty: plt.plot(testDf['epoch'].values, testDf['err'].values, label='Test') plt.xlabel("Epoch") plt.ylabel("Error") plt.xlim(xmin=0) plt.grid(b=True, which='major', color='k', linestyle='-') plt.grid(b=True, which='minor', color='k', linestyle='--', alpha=0.2) plt.legend() ax.set_yscale('log') for ext in ['pdf', 'png']: f = os.path.join(workDir, "err."+ext) fig.savefig(f) print("Created {}".format(f))
def plot_history(history, result_dir): plt.plot(history.history['acc'], marker='.') plt.plot(history.history['val_acc'], marker='.') plt.title('model accuracy') plt.xlabel('epoch') plt.ylabel('accuracy') plt.grid() plt.legend(['acc', 'val_acc'], loc='lower right') plt.savefig(os.path.join(result_dir, 'model_accuracy.png')) plt.close() plt.plot(history.history['loss'], marker='.') plt.plot(history.history['val_loss'], marker='.') plt.title('model loss') plt.xlabel('epoch') plt.ylabel('loss') plt.grid() plt.legend(['loss', 'val_loss'], loc='upper right') plt.savefig(os.path.join(result_dir, 'model_loss.png')) plt.close()
def fft_test(self): #t = np.arange(0, 1.0, 1.0/8000) #signal = np.sin(2*np.pi*156.25*t) + 2*np.sin(2*np.pi*234.375*t) axis = str(self.axis_combobox.currentText()) signal = self.raw_data[axis] - self.bias_dict[axis] n = signal.size time_step = 0.007 fftResult = (np.abs(np.fft.fft(signal)/n))**2 freq = np.fft.fftfreq(n, d=time_step) plt.plot(1/freq, fftResult, 'g') plt.xlim(0) plt.grid('on') plt.title('Power Spectrum') plt.show()
def main(): check_error() try: with open(sys.argv[1]) as f: tab = parse_file(f) if len(tab) <= 4: raise InvalidFile("Not enough data in file") except (PermissionError, FileNotFoundError) as e: print(e, file=sys.stderr) sys.exit(84) else: derv = bonjour(tab) tab = revers_tab(tab) plt.ylabel("pH") plt.xlabel("Volume") plt.grid(True) plt.plot(tab[0], tab[1]) plt.plot(tab[0], derv) plt.axis([tab[0][0], tab[0][-1], min(tab[1][0], derv[0]), max(tab[1][-1], derv[-1])]) plt.show()
def PCAdo(block, name): cor_ = np.corrcoef(block.T) eig_vals, eig_vecs = np.linalg.eig(cor_) tot = sum(eig_vals) var_exp = [(i / tot) * 100 for i in sorted(eig_vals, reverse=True)] cum_var_exp = np.cumsum(var_exp) loadings = (eig_vecs * np.sqrt(eig_vals)) eig_vals = np.sort(eig_vals)[::-1] print('Eigenvalues') print(eig_vals) print('Variance Explained') print(var_exp) print('Total Variance Explained') print(cum_var_exp) print('Loadings') print(abs(loadings[:, 0])) PAcorrect = PA(block.shape[0], block.shape[1]) print('Parallel Analisys') pa = (eig_vals - (PAcorrect - 1)) print(pa) print('Correlation Matrix') print(pd.DataFrame.corr(block)) plt.plot(range(1,len(pa)+1), pa, '-o') plt.grid(True) plt.xlabel('Fatores') plt.ylabel('Componentes') plt.savefig('imgs/PCA' + name, bbox_inches='tight') plt.clf() plt.cla() # plt.show()
def show_setup(self, halt=True): """Open a plot window that shows the simulation setup including boundaries, outputs and material regions. Args: halt: Halt script execution until plot window is closed. """ pp.figure() self.axes = pp.gca() self.axes.set_xlim(0, max(self.field.x.vector) / self._x_axis_factor) self.axes.set_ylim(-self.scale, self.scale) self.axes.set_xlabel('{0} / {1}m'.format(self.x_label, self._x_axis_prefix)) self.axes.set_ylabel(self.y_label) pp.grid(True) if self.show_materials: for mat_region in self.field.material_regions: self.plot_region(mat_region.region) if self.show_boundaries: for name, component in self.field_components.items(): for boundary in component.boundaries: self.plot_region(boundary.region) if self.show_output: for name, component in self.field_components.items(): for output in component.outputs: self.plot_region(output.region) if halt: pp.show()
def save_image(folder='images'): """ Coroutine of image saving """ from matplotlib import pyplot as plt from matplotlib import colors if folder not in os.listdir('.'): os.mkdir(folder) frame_cnt = it.count() cmap = colors.ListedColormap(['#009688', '#E0F2F1', '#004D40']) bounds = [0, 0.25, 0.75, 1] norm = colors.BoundaryNorm(bounds, cmap.N) while True: screen = (yield) shape = screen.shape plt.imshow( screen, interpolation='none', cmap=cmap, norm=norm, aspect='equal', extent=(0, shape[1], 0, shape[0])) plt.grid(True) plt.axis('off') plt.savefig('%s/frame%06i.png' % (folder, frame_cnt.next()))
def plot_correlations(self, iabscissa=1): """spectrum of correlation matrix and largest correlation""" if not hasattr(self, 'corrspec'): self.load() if len(self.corrspec) < 2: return self x = self.corrspec[:, iabscissa] y = self.corrspec[:, 6:] # principle axes ys = self.corrspec[:, :6] # "special" values from matplotlib.pyplot import semilogy, text, grid, axis, title self._enter_plotting() semilogy(x, y, '-c') # hold(True) semilogy(x[:], np.max(y, 1) / np.min(y, 1), '-r') text(x[-1], np.max(y[-1, :]) / np.min(y[-1, :]), 'axis ratio') if ys is not None: semilogy(x, 1 + ys[:, 2], '-b') text(x[-1], 1 + ys[-1, 2], '1 + min(corr)') semilogy(x, 1 - ys[:, 5], '-b') text(x[-1], 1 - ys[-1, 5], '1 - max(corr)') semilogy(x[:], 1 + ys[:, 3], '-k') text(x[-1], 1 + ys[-1, 3], '1 + max(neg corr)') semilogy(x[:], 1 - ys[:, 4], '-k') text(x[-1], 1 - ys[-1, 4], '1 - min(pos corr)') grid(True) ax = array(axis()) # ax[1] = max(minxend, ax[1]) axis(ax) title('Spectrum (roots) of correlation matrix') # pyplot.xticks(xticklocs) self._xlabel(iabscissa) self._finalize_plotting() return self
def _plot_roc(frrs, colors, labels, title, fontsize=10, position=None, farfrrs=None): if position is None: position = 'lower right' figure = pyplot.figure() # plot FAR and CAR for each algorithm for i in range(len(frrs)): pyplot.semilogx([f for f in frrs[i][0]], [1. - f for f in frrs[i][1]], color=colors[i], label=labels[i]) if isinstance(farfrrs, list): pyplot.plot(farfrrs[i][0], (1.-farfrrs[i][1]), 'o', color=colors[i], markeredgecolor=colors[i]) # plot vertical bar, if desired if farfrrs is not None: if isinstance(farfrrs, float): pyplot.plot([farfrrs,farfrrs],[0.,1.], "--", color='black') else: pyplot.plot([x[0] for x in farfrrs], [(1.-x[1]) for x in farfrrs], '--', color='black') _add_far_labels(frrs[0][0][0]) # set label, legend and title pyplot.xlabel('FMR') pyplot.ylabel('1 - FNMR') pyplot.grid(True, color=(0.6,0.6,0.6)) pyplot.legend(loc=position, prop = {'size':fontsize}) pyplot.title(title) return figure
def _plot_det(dets, colors, labels, title, fontsize=10, position=None): if position is None: position = 'upper right' # open new page for current plot figure = pyplot.figure(figsize=(matplotlib.rcParams['figure.figsize'][0], matplotlib.rcParams['figure.figsize'][0] * 0.975)) pyplot.grid(True) # plot the DET curves for i in range(len(dets)): pyplot.plot(dets[i][0], dets[i][1], color=colors[i], label=labels[i]) # change axes accordingly det_list = [0.0002, 0.001, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 0.7, 0.9, 0.95] ticks = [bob.measure.ppndf(d) for d in det_list] labels = [("%.5f" % d).rstrip('0').rstrip('.') for d in det_list] pyplot.xticks(ticks, [l if i % 2 else "" for i,l in enumerate(labels)]) pyplot.yticks(ticks, labels) pyplot.axis((ticks[0], ticks[-1], ticks[0], ticks[-1])) pyplot.xlabel('FMR') pyplot.ylabel('FNMR') pyplot.legend(loc=position, prop = {'size':fontsize}) pyplot.title(title) return figure
def plot_deviance(sol, save=False, draw=True, save_as_png=True, fig_dpi=144): if save_as_png: save_as = 'png' else: save_as = 'pdf' filename = sol.filename.replace("\\", "/").split("/")[-1].split(".")[0] model = get_model_type(sol) if draw or save: fig, ax = plt.subplots(figsize=(4,3)) deviance = sol.MDL.trace('deviance')[:] sampler_state = sol.MDL.get_state()["sampler"] x = np.arange(sampler_state["_burn"]+1, sampler_state["_iter"]+1, sampler_state["_thin"]) plt.plot(x, deviance, "-", color="C3", label="Model deviance\nDIC = %.2f\nBPIC = %.2f" %(sol.MDL.DIC,sol.MDL.BPIC)) plt.xlabel("Iteration") plt.ylabel("Model deviance") plt.legend(numpoints=1, loc="best", fontsize=9) plt.grid('on') if sampler_state["_burn"] == 0: plt.xscale('log') else: plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) fig.tight_layout() if save: save_where = '/Figures/ModelDeviance/' working_path = getcwd().replace("\\", "/")+"/" save_path = working_path+save_where print("\nSaving model deviance figure in:\n", save_path) if not path.exists(save_path): makedirs(save_path) fig.savefig(save_path+'ModelDeviance-%s-%s.%s'%(model,filename,save_as), dpi=fig_dpi, bbox_inches='tight') try: plt.close(fig) except: pass if draw: return fig else: return None
def plot_logp(sol, save=False, draw=True, save_as_png=True, fig_dpi=144): if save_as_png: save_as = 'png' else: save_as = 'pdf' filename = sol.filename.replace("\\", "/").split("/")[-1].split(".")[0] model = get_model_type(sol) if draw or save: fig, ax = plt.subplots(figsize=(4,3)) logp = logp_trace(sol.MDL) sampler_state = sol.MDL.get_state()["sampler"] x = np.arange(sampler_state["_burn"]+1, sampler_state["_iter"]+1, sampler_state["_thin"]) plt.plot(x, logp, "-", color="C3") plt.xlabel("Iteration") plt.ylabel("Log-likelihood") plt.legend(numpoints=1, loc="best", fontsize=9) plt.grid('on') if sampler_state["_burn"] == 0: plt.xscale('log') else: plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) fig.tight_layout() if save: save_where = '/Figures/LogLikelihood/' working_path = getcwd().replace("\\", "/")+"/" save_path = working_path+save_where print("\nSaving logp trace figure in:\n", save_path) if not path.exists(save_path): makedirs(save_path) fig.savefig(save_path+'LogLikelihood-%s-%s.%s'%(model,filename,save_as), dpi=fig_dpi, bbox_inches='tight') try: plt.close(fig) except: pass if draw: return fig else: return None
def plot_deviance(sol, save=False, draw=True, save_as_png=True, fig_dpi=144): if save_as_png: save_as = 'png' else: save_as = 'pdf' filename = sol.filename.replace("\\", "/").split("/")[-1].split(".")[0] model = get_model_type(sol) if draw or save: fig, ax = plt.subplots(figsize=(4,3)) deviance = sol.MDL.trace('deviance')[:] sampler_state = sol.MDL.get_state()["sampler"] x = np.arange(sampler_state["_burn"]+1, sampler_state["_iter"]+1, sampler_state["_thin"]) plt.plot(x, deviance, "-", color="C3", label="Model deviance\nDIC = %.2f\nBPIC = %.2f" %(sol.MDL.DIC,sol.MDL.BPIC)) plt.xlabel("Iteration") plt.ylabel("Model deviance") plt.legend(numpoints=1, loc="best") plt.grid('on') if sampler_state["_burn"] == 0: plt.xscale('log') else: plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) fig.tight_layout() if save: save_where = '/Figures/ModelDeviance/' working_path = getcwd().replace("\\", "/")+"/" save_path = working_path+save_where print("\nSaving model deviance figure in:\n", save_path) if not path.exists(save_path): makedirs(save_path) fig.savefig(save_path+'ModelDeviance-%s-%s.%s'%(model,filename,save_as), dpi=fig_dpi, bbox_inches='tight') try: plt.close(fig) except: pass if draw: return fig else: return None
def plot_logp(sol, save=False, draw=True, save_as_png=True, fig_dpi=144): if save_as_png: save_as = 'png' else: save_as = 'pdf' filename = sol.filename.replace("\\", "/").split("/")[-1].split(".")[0] model = get_model_type(sol) if draw or save: fig, ax = plt.subplots(figsize=(4,3)) logp = logp_trace(sol.MDL) sampler_state = sol.MDL.get_state()["sampler"] x = np.arange(sampler_state["_burn"]+1, sampler_state["_iter"]+1, sampler_state["_thin"]) plt.plot(x, logp, "-", color="C3") plt.xlabel("Iteration") plt.ylabel("Log-likelihood") plt.legend(numpoints=1, loc="best") plt.grid('on') if sampler_state["_burn"] == 0: plt.xscale('log') else: plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) fig.tight_layout() if save: save_where = '/Figures/LogLikelihood/' working_path = getcwd().replace("\\", "/")+"/" save_path = working_path+save_where print("\nSaving logp trace figure in:\n", save_path) if not path.exists(save_path): makedirs(save_path) fig.savefig(save_path+'LogLikelihood-%s-%s.%s'%(model,filename,save_as), dpi=fig_dpi, bbox_inches='tight') try: plt.close(fig) except: pass if draw: return fig else: return None
def superpose(cdfs, outputpath, data): border_x = 0.5 dx = 0.001 x = np.arange(0, border_x, dx) plt.ioff() fig = plt.figure(figsize=(10,8)) plt.xticks([0.01, 0.02, 0.05, 0.07, 0.09, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5]) plt.yticks([0.1, 0.2, 0.3, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0]) plt.xticks(rotation=70) plt.grid(b=True, which='major', axis='both', linestyle='dotted') floating = 3 prec = "%." + str(floating) + "f" for cdf in cdfs: title = cdf["title"] auc = cdf["auc"] cdf01 = cdf["cdf01"] cdf_val = cdf["cdf"] plt.plot(x, cdf_val, marker=',', label=title + ", CDF(0.1)=" + str(prec % (cdf01*100)) + "%, AUC=" + str(prec % np.float(auc)) + "%") plt.legend(loc=4, prop={'size': 8}, fancybox=True, shadow=True) fig.suptitle('Cumulative distribution function (CDF) of NRMSE over ' + data + ' test set.') plt.xlabel('NRMSE') plt.ylabel('Data proportion') fig.savefig(outputpath, bbox_inches='tight', format='eps', dpi=1000) plt.ion()