def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues, filename='viz\\confusion_matrix.png'): plt.figure() plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.savefig(filename)
def plot_classification_report(cr, title='Classification report ', with_avg_total=False, cmap=plt.cm.Blues): lines = cr.split('\n') classes = [] plotMat = [] for line in lines[2:(len(lines) - 3)]: #print(line) t = line.split() if len(t): classes.append(t[0]) v = [float(x) for x in t[1:len(t) - 1]] print(v) plotMat.append(v) if with_avg_total: aveTotal = lines[len(lines) - 1].split() classes.append('avg/total') vAveTotal = [float(x) for x in t[1:len(aveTotal) - 1]] plotMat.append(vAveTotal) plt.imshow(plotMat, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() x_tick_marks = np.arange(3) y_tick_marks = np.arange(len(classes)) plt.xticks(x_tick_marks, ['precision', 'recall', 'f1-score', 'support'], rotation=45) plt.yticks(y_tick_marks, classes) plt.tight_layout() plt.ylabel('Classes') plt.xlabel('Measures')
def plot_confusion_matrix(confusion_matrix, class_labels, normalize=False, title='Confusion Matrix', cmap=plt.cm.Blues): """ Code courtesy of Abinav Sagar: https://towardsdatascience.com/convolutional-neural-network-for-breast-cancer-classification-52f1213dcc9 """ if normalize: confusion_matrix = confusion_matrix.astype( 'float') / confusion_matrix.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(confusion_matrix) plt.imshow(confusion_matrix, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(class_labels)) plt.xticks(tick_marks, class_labels, rotation=55) plt.yticks(tick_marks, class_labels) fmt = '.2f' if normalize else 'd' thresh = confusion_matrix.max() / 2. for i, j in itertools.product(range(confusion_matrix.shape[0]), range(confusion_matrix.shape[1])): plt.text(j, i, format(confusion_matrix[i, j], fmt), horizontalalignment="center", color="white" if confusion_matrix[i, j] > thresh else "black") plt.ylabel('True label') plt.xlabel('Predicted label') plt.tight_layout()
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print("Confusion Matrix, without normalization") print(cm) #imshow displays data as an image on a 2d master plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() #returns evenly spaced values with a given inteerval tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment='center', color='white' if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True Label') plt.xlabel('Predicted Label')
def plot_confusion_matrix(cls_pred, cls_true): # This is called from print_test_accuracy() below. # cls_pred is an array of the predicted class-number for # all images in the test-set. # Get the true classifications for the test-set. # Get the confusion matrix using sklearn. cm = confusion_matrix(y_true=cls_true, y_pred=cls_pred) # Print the confusion matrix as text. print(cm) # Plot the confusion matrix as an image. plt.matshow(cm) # Make various adjustments to the plot. plt.colorbar() tick_marks = np.arange(labels_type) plt.xticks(tick_marks, range(labels_type)) plt.yticks(tick_marks, range(labels_type)) plt.xlabel('Predicted') plt.ylabel('True') # Ensure the plot is shown correctly with multiple plots # in a single Notebook cell. plt.show()
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label')
def forward(self, x): # polar plot dic = creatRealDictionary(self.T, self.rr, self.theta, self.gid) sparsecode = fista(dic, x, self.lam, 100, self.gid) if random.randint(1, 20) == 1: plt.figure() plt.pcolormesh(sparsecode[0, :, :].data.cpu().detach().numpy(), cmap='RdBu') plt.colorbar() plt.savefig('C_evolution_subsIni.png') #, dpi=200 # plt.show() plt.close() rr = self.rr.data.cpu().detach().numpy() theta = self.theta.data.cpu().detach().numpy() ax = plt.subplot(1, 1, 1, projection='polar') ax.scatter(0, 1, c='black') # unactive poles ax.scatter(theta, rr) ax.scatter(-theta, rr) ax.scatter(np.pi - theta, rr) ax.scatter(theta - np.pi, rr) # ax.set_rmax(1.2) ax.set_title("Dictionary", va='bottom') plt.savefig('usedPolesDCT.png') # plt.show() plt.close() return Variable(sparsecode)
def plot_confusion_matrix(cm, classes, title='混淆矩阵', cmap=plt.cm.Greens): # imshow() 表示绘制并显示二维图 有18个参数 # 参数1 X 混淆矩阵中显示的数值 二维数组 # 参数2 cmap 颜色 plt.cm.Blues表示蓝色 plt.cm.Reds表示红色 plt.cm.Greens表示绿色 # 参数5 interpolation 插值法 一般有如下值 # nearest 最近邻插值法 # bilinear 双线性插值法 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.imshow(cm, cmap=cmap, interpolation="nearest") plt.title(title) # 标题 plt.colorbar() # 显示颜色的进度条 tick_marks = np.arange(2) # [0 1] plt.xticks(tick_marks, classes) # 对x轴上分类进行标记 plt.yticks(tick_marks, classes) # 对y轴上分类进行标记 thresh = np.mean(cm) for i in range(2): for j in range(2): plt.text(i, j, cm[j][i], horizontalalignment='center', color='white' if cm[i][j] >= thresh else 'black') plt.xlabel('预测值') plt.ylabel('真实值')
def spect(tr,fmin = 0.1,fmax = None,wlen=10,title=None): import matplotlib as plt if fmax is None: fmax = tr.stats.sampling_rate/2 fig = plt.figure() ax1 = fig.add_axes([0.1, 0.75, 0.7, 0.2]) #[left bottom width height] ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60], sharex=ax1) ax3 = fig.add_axes([0.83, 0.1, 0.03, 0.6]) #make time vector t = np.arange(tr.stats.npts) / tr.stats.sampling_rate #plot waveform (top subfigure) ax1.plot(t, tr.data, 'k') #plot spectrogram (bottom subfigure) tr2 = tr.copy() fig = tr2.spectrogram(per_lap=0.9,wlen=wlen,show=False, axes=ax2) mappable = ax2.images[0] plt.colorbar(mappable=mappable, cax=ax3) ax2.set_ylim(fmin, fmax) ax2.set_xlabel('Time [s]') ax2.set_ylabel('Frequency [Hz]') if title: plt.suptitle(title) else: plt.suptitle('{}.{}.{} {}'.format(tr.stats.network,tr.stats.station, tr.stats.channel,tr.stats.starttime)) plt.show()
def plotConfusionMatrix(lbllist, predlist, classes, type): confusionMatrix = confusion_matrix(lbllist, predlist) # print(confusionMatrix) plt.imshow(confusionMatrix, interpolation="nearest", cmap=plt.cm.Blues) if type == 'train': plt.title("Confusion matrix training") elif type == 'test': plt.title("Confusion matrix testing") plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = "d" thresh = confusionMatrix.max() / 2. for i, j in itertools.product(range(confusionMatrix.shape[0]), range(confusionMatrix.shape[1])): plt.text(j, i, format(confusionMatrix[i, j], fmt), horizontalalignment="center", color="white" if confusionMatrix[i, j] > thresh else "black") plt.tight_layout() plt.ylabel("True label") plt.xlabel("Predicted label") # plt.show() if type == 'train': plt.savefig(LOG_PATH + 'Confusion matrix training.png') elif type == 'test': plt.savefig(LOG_PATH + 'Confusion matrix testing.png') plt.close()
def tsne_plot(embedding, expression_value, cmaps="PuRd"): plt.scatter(embedding[:, 0], embedding[:, 1], lw=0.1, c=expression_value, cmap=plt.cm.get_cmap('PuRd')) plt.colorbar(label='expression value') plt.show()
def plot(self, output): # Create adaptive scale scale_len = 100 scale_fix = 250 nframes = self.v.shape[2] scale = zeros((nframes, 1)) win = ones((scale_len, 1)) for ii in range(0, nframes): scale[ii] = amax(absolute(self.v[:, :, ii])) scale = convolve(squeeze(scale), squeeze(win), mode='same') / output.scale_sat if (self.writestep == 0): scale[:scale_fix] = scale[scale_fix] # Initialize figure comp = {'x': ['Y', 'Z'], 'y': ['X', 'Z'], 'z': ['X', 'Y']} fig = plt.figure(figsize=(output.hres / output.sres, output.hres / (output.sres * output.hratio)), dpi=output.sres) imsize = [self.x[0], self.x[-1], self.y[-1], self.y[0]] vimg = plt.imshow(transpose(self.v[:, :, 0]), extent=imsize, vmin=-scale[0], vmax=scale[0], cmap=cm.RdBu) vtitle = plt.title('') plt.xlabel(comp[self.dir][0]) plt.ylabel(comp[self.dir][1]) plt.colorbar() def animate(ii): vimg.set_array(transpose(self.v[:, :, ii])) vimg.set_clim(-scale[ii], scale[ii]) vtitle.set_text("%s for %s=%s km (t=%1.2e s)" % (self.type, self.dir, self.loc, self.t[ii])) return vimg, vtitle try: ani = animation.FuncAnimation(fig, animate, frames=self.v.shape[2], interval=20, blit=False, repeat=False) if (self.writestep == 0): ani.save("./%s_%s_%s.mp4" % (self.dir, self.loc, self.type), fps=30, codec='libx264', bitrate=1800) else: ani.save("./%s_%s_%s_%i.mp4" % (self.dir, self.loc, self.type, self.writestep), fps=30, codec='libx264', bitrate=1800) except IndexError: print 'To render movies, make sure that ffmpeg is installed!' self.writestep += 1
def cm_plot(original_label, predict_label, kunm, pic=None): prec_score = precision_score(original_label, predict_label, average=None) recall = recall_score(original_label, predict_label, average=None) f1 = f1_score(original_label, predict_label, average=None) cm = confusion_matrix(original_label, predict_label) cm_new = np.empty(shape=[5, 5]) for x in range(5): t = cm.sum(axis=1)[x] for y in range(5): cm_new[x][y] = round(cm[x][y] / t * 100, 2) plt.figure() plt.matshow(cm_new, cmap=plt.cm.Blues) plt.colorbar() x_numbers = [] y_numbers = [] cm_percent = [] for x in range(5): y_numbers.append(cm.sum(axis=1)[x]) x_numbers.append(cm.sum(axis=0)[x]) for y in range(5): percent = format(cm_new[x, y] * 100 / cm_new.sum(axis=1)[x], ".2f") cm_percent.append(str(percent)) plt.annotate(format(cm_new[x, y] * 100 / cm_new.sum(axis=1)[x], ".2f"), xy=(y, x), horizontalalignment='center', verticalalignment='center', fontsize=10) plt.ylabel('True label') plt.xlabel('Predicted label') plt.title('confusion matrix') y_stage = [ "W\n(" + str(y_numbers[0]) + ")", "N1\n(" + str(y_numbers[1]) + ")", "N2\n(" + str(y_numbers[2]) + ")", "N3\n(" + str(y_numbers[3]) + ")", "REM\n(" + str(y_numbers[4]) + ")" ] x_stage = [ "W\n(" + str(x_numbers[0]) + ")", "N1\n(" + str(x_numbers[1]) + ")", "N2\n(" + str(x_numbers[2]) + ")", "N3\n(" + str(x_numbers[3]) + ")", "REM\n(" + str(x_numbers[4]) + ")" ] y = [0, 1, 2, 3, 4] plt.xticks(y, x_stage) plt.yticks(y, y_stage) #sns.heatmap(cm_percent, fmt='g', cmap="Blues", annot=True, cbar=False, xticklabels=x_stage, yticklabels=y_stage) # 画热力图,annot=True 代表 在图上显示 对应的值, fmt 属性 代表输出值的格式,cbar=False, 不显示 热力棒 plt.savefig(savepath + "matrix" + str(kunm) + ".svg") #plt.show() plt.show() plt.close() # plt.savefig("/home/data_new/zhangyongqing/flx/pythoncode/"+str(knum)+"matrix.jpg") return kappa(cm), classification_report(original_label, predict_label)
def plot_various_trial_analyses(self,neuron_ind, var_level): plt.figure(figsize=(16, 5)) #the first thing we want to do is just plot the data average #so first get the data for all trials neuron_i_data_by_trial = self.by_trial_IT_Neural_Data_objmeans_sorted_by_category[var_level][:, :, neuron_ind] #now take the mean over the second dimension -- the trial dimension neuron_i_data_trial_mean = neuron_i_data_by_trial.mean(1) #for convenience, let's compute the min and max values of the neural response minval = neuron_i_data_trial_mean.min() maxval = neuron_i_data_trial_mean.max() #now let's plot the responses across objects plt.plot(neuron_i_data_trial_mean) #and block stuff to make the categories easier to see plt.fill_between(np.arange(64), minval, maxval, where=(np.arange(64) / 8) % 2, color='k', alpha=0.2) plt.xticks(np.arange(0, 64, 8) + 4, self.unique_categories, rotation=30); plt.ylabel('Neural Response of neuron %d' % neuron_ind) plt.ylim(minval, maxval) plt.xlabel('Responses for Variation %s images' % var_level) #now let's look at two trials -- the first and 6th ones, for example t1 = 0; t2 = 5 t1_data = neuron_i_data_by_trial[:, t1] t2_data = neuron_i_data_by_trial[:, t2] plt.figure(figsize=(12, 5)) plt.subplot(1, 2, 1) plt.plot(t1_data) plt.xticks(np.arange(0, 64, 8), self.unique_categories, rotation=30); plt.title('Neuron %d, trial %d, var %s' % (neuron_ind, t1, var_level)) plt.subplot(1, 2, 2) plt.plot(t2_data) plt.xticks(np.arange(0, 64, 8), self.unique_categories, rotation=30); plt.title('Neuron %d, trial %d, var %s' % (neuron_ind, t2, var_level)) #let's do a scatter plot of the responses to one trial vs the other plt.figure() plt.scatter(t1_data, t2_data) plt.xlabel('responses of neuron %d, trial %d, %s'% (neuron_ind, t1, var_level)) plt.ylabel('responses of neuron %d, trial %d, %s'% (neuron_ind, t2, var_level)) #how correlated are they exactly between trials? let's use pearson correlation rval = stats.pearsonr(t1_data, t2_data)[0] plt.title('Correlation for varlevel %s images = %.3f' % (var_level, rval)) #in fact, let's have a look at the correlation for all pairs of trials fig = plt.figure(figsize = (7, 7)) #the numpy corrcoef function basically gets the pairwise pearson correlation efficiently corrs = np.corrcoef(neuron_i_data_by_trial.T) #now let's plot the matrix of correlations using the matshow function plt.colorbar(fig.gca().matshow(corrs)) plt.xlabel('trials of neuron %d' % neuron_ind) plt.ylabel('trials of neuron %d' % neuron_ind) plt.title('Between-trial correlations for varlevel %s' % var_level)
def cm_plot(original_label, predict_label, kunm, savepath): prec_score = precision_score(original_label, predict_label, average=None) recall = recall_score(original_label, predict_label, average=None) f1 = f1_score(original_label, predict_label, average=None) cm = confusion_matrix(original_label, predict_label) cm_new = np.empty(shape=[5, 5]) for x in range(5): t = cm.sum(axis=1)[x] for y in range(5): cm_new[x][y] = round(cm[x][y] / t * 100, 2) plt.figure() plt.matshow(cm_new, cmap=plt.cm.Blues) plt.colorbar() x_numbers = [] y_numbers = [] cm_percent = [] for x in range(5): y_numbers.append(cm.sum(axis=1)[x]) x_numbers.append(cm.sum(axis=0)[x]) for y in range(5): percent = format(cm_new[x, y] * 100 / cm_new.sum(axis=1)[x], ".2f") cm_percent.append(str(percent)) plt.annotate(format(cm_new[x, y] * 100 / cm_new.sum(axis=1)[x], ".2f"), xy=(y, x), horizontalalignment='center', verticalalignment='center', fontsize=10) plt.ylabel('True label') plt.xlabel('Predicted label') plt.title('confusion matrix') y_stage = [ "W\n(" + str(y_numbers[0]) + ")", "N1\n(" + str(y_numbers[1]) + ")", "N2\n(" + str(y_numbers[2]) + ")", "N3\n(" + str(y_numbers[3]) + ")", "REM\n(" + str(y_numbers[4]) + ")" ] x_stage = [ "W\n(" + str(x_numbers[0]) + ")", "N1\n(" + str(x_numbers[1]) + ")", "N2\n(" + str(x_numbers[2]) + ")", "N3\n(" + str(x_numbers[3]) + ")", "REM\n(" + str(x_numbers[4]) + ")" ] y = [0, 1, 2, 3, 4] plt.xticks(y, x_stage) plt.yticks(y, y_stage) plt.savefig(savepath + "matrix" + str(kunm) + ".svg") plt.show() plt.close() return kappa(cm), classification_report(original_label, predict_label)
def plot_confusion_matrix(cm, labels, title='Confusion matrix', cmap=plt.cm.Blues, save=False): plt.figure() plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(labels)) plt.xticks(tick_marks, labels, rotation=45) plt.yticks(tick_marks, labels) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.show() if save: plt.savefig(save)
def estimate_coord_plot(feten): lon_res = 13 lat_res = 9 nz = 26 lat_step = 0.5 lon_step = 0.5 lat_start = 44 lat_end = lat_start + lat_step * (lat_res - 1) # calculas lat final lon_start = -123 lon_end = lon_start + lon_step * ( lon_res - 1) # calculas lon final - con esto puedes construir mesh lat = np.linspace(start=lat_start, stop=lat_end, endpoint=lat_end, num=lat_res) lon = np.linspace(start=lon_start, stop=lon_end, endpoint=lon_end, num=lon_res) # lon, lat = np.meshgrid(lon, lat) Z = feten.reshape(lat_res, lon_res) ptos = np.hstack((lat.reshape((lat.size, 1)), lon.reshape((lon.size, 1)))) fig = plt.figure(figsize=(12, 10)) im = plt.pcolormesh(lat, lon, Z) # Asignas valores a su posición en el mapa return plt.colorbar(mappable=im)
def plot_confusion_matrix(y_true, y_predicted, M0, M1, success_rate, main_title, show): cm = confusion_matrix(y_true, y_predicted) #print(cm) if (show == 'yes'): plt.matshow(cm, cmap = 'Reds') plt.colorbar() plt.ylabel('Actual') plt.xlabel('Predicted') plt.suptitle(main_title) true_positives = 0 plt.show() for i in range (0, 52): for j in range (0, 52): if(i == j): true_positives += cm[i,j] print('\n') print('M0 =',M0,' , M1 =',M1,'Number of true positives = ', true_positives, '\n') plt.close()
def plot_mixture_matrix(axis, mixture_matrix, labels): """ auxiliary function to plot the mixture matrix Keywords: --- axis: the axes object --- mixture_matrix: the data for the mixture matrix --- labels: labels in the mixture matrix corresponding to classes """ # Add a finite number to the otherwise zero values # to get around the logarithmic nan values # mixture_matrix[np.where(mixture_matrix==0)] += 1 mixture_matrix = mixture_matrix / float(np.sum(mixture_matrix)) # disc = np.max(mixture_matrix) fonts = {"fontsize": 10} tick_size = 8 cmap = cm.get_cmap("gist_yarg") # , disc) cmap.set_under((0.0, 0.0, 0.0)) core.show_axis(axis) core.make_spines(axis) imge = axis.imshow(mixture_matrix, cmap=cm_gray_r, aspect=1.0, interpolation="nearest") cax = inset_axes( axis, width="5%", # width = 10% of parent_bbox width height="100%", # height : 50% loc=3, bbox_to_anchor=(1.05, 0.0, 1, 1), bbox_transform=axis.transAxes, borderpad=0, ) # f = ticker.ScalarFormatter(useOffset=False, useMathText=True) cbar = colorbar(imge, cax=cax, ticks=[0, 0.1, 0.2, 0.3], extend="both") cbar.ax.tick_params(labelsize=9) axis.set_ylabel("true label", **fonts) axis.set_xlabel("predicted label", **fonts) for location in ["top", "bottom", "left", "right"]: axis.spines[location].set_visible(True) axis.spines[location].set_linewidth(1.0) # Change the ticks to labels names axis.xaxis.set_major_locator(MaxNLocator(integer=True)) axis.yaxis.set_major_locator(MaxNLocator(integer=True)) axis.tick_params(length=0.0, pad=5) axis.set_xticks(np.arange(len(labels))) axis.set_xticklabels(labels, fontsize=tick_size) axis.set_yticks(np.arange(len(labels))) axis.set_yticklabels(labels, fontsize=tick_size) axis.tick_params(axis="both", which="minor")
def generate_plot(array, vmin, vmax, figNumber=1): plt.figure(figNumber) plt.subplot(2,3,i) print i plt.imshow(array, vmin = vmin, vmax= vmax, interpolation = None) plt.xlabel('Sample') plt.ylabel('Line') plt.title(row[0]) cb = plt.colorbar(orientation='hor', spacing='prop',ticks = [vmin,vmax],format = '%.2f') cb.set_label('Reflectance / cos({0:.2f})'.format(incAnglerad*180.0/math.pi)) plt.grid(True)
def plot_confusion_matrix(y_true, y_predicted, Mpca, Mlda, success_rate, show): cm = confusion_matrix(y_true, y_predicted) #print(cm) if (show == 'yes'): plt.matshow(cm, cmap = 'Reds') title = 'PCA-LDA Confusion Matrix with Mpca='+str(Mpca)+' and Mlda='+str(Mlda)+' [Success Rate='+str(success_rate)+'%]' plt.colorbar() plt.ylabel('Actual') plt.xlabel('Predicted') plt.suptitle(title) true_positives = 0 plt.show() for i in range (0, 52): for j in range (0, 52): if(i == j): true_positives += cm[i,j] print('\n') print('Mpca =',Mpca,' , Mlda =',Mlda,'Number of true positives = ', true_positives, '\n') plt.close()
def plot_grid(df, xvar='x', yvar='y', zvar='acc'): #get the number of xbins/ybins (assumes square grid) bins = df[xvar].nunique() fig = plt.figure(figsize=(10, 8)) plt.hist2d(df[xvar], df[yvar], weights=df[zvar], bins=bins, cmap='inferno') plt.xlabel(xvar) plt.ylabel(yvar) cbar = plt.colorbar() cbar.ax.set_ylabel(zvar) plt.close() return fig
def plot(self, model, output): Z = linspace(0, model.number[2] * model.spacing[2], model.number[2]) + model.spacing[2] imsize = [model.origin[0], model.size[0] + model.origin[0], model.origin[1], model.size[1] + model.origin[1]] fig = plt.figure(figsize=(output.hres / output.sres, output.hres / (output.sres * output.hratio)), dpi=output.sres) vimg = plt.imshow(transpose(self.v[:, :, 0]), extent=imsize, vmin=round(amin(self.v), 1) - 0.05, vmax=round(amax(self.v) + 0.05, 1), cmap=cm.jet) vtitle = plt.title('') plt.xlabel('X') plt.ylabel('Y') plt.colorbar() def animate(ii): vimg.set_array(transpose(self.v[:, :, ii])) vtitle.set_text("%s Plot (Z = %1.2fkm)" % (self.name, Z[ii])) return vimg, vtitle try: ani = animation.FuncAnimation(fig, animate, frames=len(Z), interval=20, blit=False, repeat=False) ani.save("./%s.mp4" % self.type, fps=30, codec='libx264', bitrate=1800) except IndexError: print 'To render movies, make sure that ffmpeg is installed!'
def plot_confusion_matrix(cm, classes, title='Confusion Matrix', cmap=plt.cm.Blues): # np.seterr(divide='ignore',invalid='ignore') cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] plt.figure(figsize=(10, 10)) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") pass plt.ylabel('True Label') plt.xlabel('Predicted Label') pass
def plot(self, model, output): Z = linspace(0, model.number[2] * model.spacing[2], model.number[2]) + model.spacing[2] imsize = [ model.origin[0], model.size[0] + model.origin[0], model.origin[1], model.size[1] + model.origin[1] ] fig = plt.figure(figsize=(output.hres / output.sres, output.hres / (output.sres * output.hratio)), dpi=output.sres) vimg = plt.imshow(transpose(self.v[:, :, 0]), extent=imsize, vmin=round(amin(self.v), 1) - 0.05, vmax=round(amax(self.v) + 0.05, 1), cmap=cm.jet) vtitle = plt.title('') plt.xlabel('X') plt.ylabel('Y') plt.colorbar() def animate(ii): vimg.set_array(transpose(self.v[:, :, ii])) vtitle.set_text("%s Plot (Z = %1.2fkm)" % (self.name, Z[ii])) return vimg, vtitle try: ani = animation.FuncAnimation(fig, animate, frames=len(Z), interval=20, blit=False, repeat=False) ani.save("./%s.mp4" % self.type, fps=30, codec='libx264', bitrate=1800) except IndexError: print 'To render movies, make sure that ffmpeg is installed!'
def cm_plot(original_label, predict_label, kunm, pic=None): cm = confusion_matrix(original_label, predict_label) print('kappa:', kappa(cm)) plt.figure() plt.matshow(cm, cmap=plt.cm.Blues) plt.colorbar() for x in range(len(cm)): for y in range(len(cm)): plt.annotate(cm[x, y], xy=(x, y), horizontalalignment='center', verticalalignment='center') plt.ylabel('True label') plt.xlabel('Predicted label') plt.title('confusion matrix') if pic is not None: plt.savefig(str(pic) + '.svg') # plt.xticks(('Wake','N1','N2','N3','REM')) # plt.yticks(('Wake','N1','N2','N3','REM')) plt.savefig(savepath + "cnnmatrix" + str(kunm) + ".svg") plt.show()
def maplatlon( lon,lat,field,\ proj="cyl",colorb="jet",ndiv=10,zeback=None,trans=0.6,title="",\ vecx=None,vecy=None,stride=2,vmin=None,vmax=None): ### an easy way to map a field over lat/lon grid import numpy as np import matplotlib.pyplot as mpl from matplotlib.cm import get_cmap ## get lon and lat in 2D version. get lat/lon intervals numdim = len(np.array(lon).shape) if numdim == 2: [lon2d, lat2d] = [lon, lat] elif numdim == 1: [lon2d, lat2d] = np.meshgrid(lon, lat) else: errormess("lon and lat arrays must be 1D or 2D") #[wlon,wlat] = latinterv() [wlon, wlat] = simplinterv(lon2d, lat2d) ## define projection and background. define x and y given the projection m = define_proj(proj, wlon, wlat, back=zeback, blat=None, blon=None) x, y = m(lon2d, lat2d) ## define field. bound field. what_I_plot = np.transpose(field) zevmin, zevmax, limtype = setbounds(what_I_plot, vmin=vmin, vmax=vmax) ## define contour field levels. define color palette ticks = ndiv + 1 zelevels = np.linspace(zevmin, zevmax, ticks) palette = get_cmap(name=colorb) ## contour field m.contourf(x, y, what_I_plot, zelevels, cmap=palette, alpha=trans) ## draw colorbar if proj in ['moll', 'cyl']: zeorientation = "horizontal" zepad = 0.07 else: zeorientation = "vertical" zepad = 0.03 daformat = "%.0f" zecb = mpl.colorbar( fraction=0.05,pad=zepad,format=daformat,orientation=zeorientation,\ ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])),extend='neither',spacing='proportional' ) ## give a title if zeorientation == "horizontal": zecb.ax.set_xlabel(title) else: ptitle(title) ## draw vector if vecx is not None and vecy is not None: [vecx_frame, vecy_frame] = m.rotate_vector(np.transpose(vecx), np.transpose(vecy), lon2d, lat2d) ## for metwinds vectorfield(vecx_frame, vecy_frame, x, y, stride=stride, csmooth=2,\ scale=30., factor=500., color=definecolorvec(colorb), key=True) ## scale regle la reference du vecteur. factor regle toutes les longueurs (dont la reference). l'AUGMENTER pour raccourcir les vecteurs. return
def plotCentroidFitDiagnostic(img, hdr, ccdMod, ccdOut, res, prfObj): """Some diagnostic plots showing the performance of fitPrfCentroid() Inputs: ------------- img (np 2d array) Image of star to be fit. Image is in the format img[row, col]. img should not contain Nans hdr (Fits header object) header associated with the TPF file the image was drawn from ccdMod, ccdOut (int) CCD module and output of image. Needed to create the correct PRF model prfObj An object of the class prf.KeplerPrf() Returns: ------------- **None** Output: ---------- A three panel subplot is created """ mp.figure(1) mp.clf() mp.subplot(131) plotTpf.plotCadence(img, hdr) mp.colorbar() mp.title("Input Image") mp.subplot(132) c, r = res.x[0], res.x[1] bbox = getBoundingBoxForImage(img, hdr) model = prfObj.getPrfForBbox(ccdMod, ccdOut, c, r, bbox) model *= res.x[2] plotTpf.plotCadence(model, hdr) mp.colorbar() mp.title("Best fit model") mp.subplot(133) diff = img - model plotTpf.plotCadence(diff, hdr) mp.colorbar() mp.title("Residuals") print "Performance %.3f" % (np.max(np.abs(diff)) / np.max(img))
def plotCentroidFitDiagnostic(img, hdr, ccdMod, ccdOut, res, prfObj): """Some diagnostic plots showing the performance of fitPrfCentroid() Inputs: ------------- img (np 2d array) Image of star to be fit. Image is in the format img[row, col]. img should not contain Nans hdr (Fits header object) header associated with the TPF file the image was drawn from ccdMod, ccdOut (int) CCD module and output of image. Needed to create the correct PRF model prfObj An object of the class prf.KeplerPrf() Returns: ------------- **None** Output: ---------- A three panel subplot is created """ mp.figure(1) mp.clf() mp.subplot(131) plotTpf.plotCadence(img, hdr) mp.colorbar() mp.title("Input Image") mp.subplot(132) c,r = res.x[0], res.x[1] bbox = getBoundingBoxForImage(img, hdr) model = prfObj.getPrfForBbox(ccdMod, ccdOut, c, r, bbox) model *= res.x[2] plotTpf.plotCadence(model, hdr) mp.colorbar() mp.title("Best fit model") mp.subplot(133) diff = img-model plotTpf.plotCadence(diff, hdr) mp.colorbar() mp.title("Residuals") print "Performance %.3f" %(np.max(np.abs(diff))/np.max(img))
def maplatlon( lon,lat,field,\ proj="cyl",colorb="jet",ndiv=10,zeback=None,trans=0.6,title="",\ vecx=None,vecy=None,stride=2,vmin=None,vmax=None): ### an easy way to map a field over lat/lon grid import numpy as np import matplotlib.pyplot as mpl from matplotlib.cm import get_cmap ## get lon and lat in 2D version. get lat/lon intervals numdim = len(np.array(lon).shape) if numdim == 2: [lon2d,lat2d] = [lon,lat] elif numdim == 1: [lon2d,lat2d] = np.meshgrid(lon,lat) else: errormess("lon and lat arrays must be 1D or 2D") #[wlon,wlat] = latinterv() [wlon,wlat] = simplinterv(lon2d,lat2d) ## define projection and background. define x and y given the projection m = define_proj(proj,wlon,wlat,back=zeback,blat=None,blon=None) x, y = m(lon2d, lat2d) ## define field. bound field. what_I_plot = np.transpose(field) zevmin,zevmax,limtype = setbounds(what_I_plot,vmin=vmin,vmax=vmax) ## define contour field levels. define color palette ticks = ndiv + 1 zelevels = np.linspace(zevmin,zevmax,ticks) palette = get_cmap(name=colorb) ## contour field m.contourf( x, y, what_I_plot, zelevels, cmap = palette, alpha = trans ) ## draw colorbar if proj in ['moll','cyl']: zeorientation="horizontal" ; zepad = 0.07 else: zeorientation="vertical" ; zepad = 0.03 daformat = "%.0f" zecb = mpl.colorbar( fraction=0.05,pad=zepad,format=daformat,orientation=zeorientation,\ ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])),extend='neither',spacing='proportional' ) ## give a title if zeorientation == "horizontal": zecb.ax.set_xlabel(title) else: ptitle(title) ## draw vector if vecx is not None and vecy is not None: [vecx_frame,vecy_frame] = m.rotate_vector( np.transpose(vecx), np.transpose(vecy), lon2d, lat2d ) ## for metwinds vectorfield(vecx_frame, vecy_frame, x, y, stride=stride, csmooth=2,\ scale=30., factor=500., color=definecolorvec(colorb), key=True) ## scale regle la reference du vecteur. factor regle toutes les longueurs (dont la reference). l'AUGMENTER pour raccourcir les vecteurs. return
def colorbar_example(): colorbar(filename='colorbar_example.pdf')
def plotFeatureArrays(featureVecs, array_shape, n_figs=10, tiled=True, tiles_shape=(2, 5), tile_psn=(.1, .125, .4, .4), xlims=None, ylims=None, titles=None, xlabel=None, ylabel=None, noise_floor=None, extent=None, origin=None, colorbar=True): n_samples = featureVecs.shape[0] if tiled: sample_idxs = np.array(random.sample(range(n_samples)), np.prod(tiles_shape)).reshape(tiles_shape) plt.figure() for r in range(tiles_shape[0]): for c in range(tiles_shape[1]): idx = sample_idxs[r, c] arr = featureVecs[idx, :].reshape(array_shape) # set signal limits maxSig = arr.max() if noise_floor is not None: minSig = magSig - noise_floor arr[arr < minSig] = minSig minSig = arr.min() left = tile_psn[0] * (c + 1) + tile_psn[2] * c bottom = tile_psn[1] * (r + 1) + tile_psn[3] * r plt.axes((left, bottom, tile_psn[2], tile_psn[3])) plt.imshow(arr, extent=extent, aspect='auto', interpolation='nearest', origin=origin, cmap='binary', vmin=minSig, vmax=maxSig) if colorbar: plt.colorbar() if xlims is not None: plt.xlim(xlims) if ylims is not None: plt.ylim(ylims) if xlabel is not None and r == 0: plt.xlabel(xlabel) else: plt.xticks([]) if ylabel is not None and c == 0: plt.ylabel(ylabel) else: plt.yticks([]) if titles is not None: plt.title(title[idx]) plt.show() else: sample_idxs = np.array(random.sample(range(n_samples)), n_figs) for idx in sample_idxs: arr = featureVecs[idx, :].reshape(array_shape) # set signal limits maxSig = arr.max() if noise_floor is not None: minSig = magSig - noise_floor arr[arr < minSig] = minSig minSig = arr.min() plt.figure() plt.axes(tile_psn) plt.imshow(arr, extent=extent, aspect='auto', interpolation='nearest', origin=origin, cmap='binary', vmin=minSig, vmax=maxSig) if colorbar: plt.colorbar() if xlims is not None: plt.xlim(xlims) if ylims is not None: plt.ylim(ylims) if xlabel is not None and r == 0: plt.xlabel(xlabel) else: plt.xticks([]) if ylabel is not None and c == 0: plt.ylabel(ylabel) else: plt.yticks([]) if titles is not None: plt.title(title[idx]) plt.show()
plt.clf() fig = plt.figure(**figprops) ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) map = Basemap( llcrnrlon=-125.5, llcrnrlat=15.0, urcrnrlon=-30.0, urcrnrlat=50.352, rsphere=(6378137.00, 6356752.3142), resolution="l", area_thresh=1000.0, projection="lcc", lat_1=50.0, lon_0=-107.0, ax=ax1, ) map.drawcoastlines(linewidth=2, color="#444444", zorder=6) map.drawcountries(linewidth=1, color="#444444", zorder=5) map.drawstates(linewidth=0.66, color="#444444", zorder=4) map.drawmapboundary x, y = map(X, Y) cf = map.contourf(x, y, temperature_advection_plot, cmap=djet, levels=cflevs, extend="both", zorder=1) cbar = plt.colorbar(cf, shrink=0.95, orientation="horizontal", extend="both") plt.show() # <codecell>
ax1.set_ylim([-90, 90]) ax1.set_xlabel(r'$\rm{Right\, Ascension\, (J2000)}$', fontsize=18) ax1.set_ylabel(r'$\rm{Declination\, (J2000)}$', fontsize=18) ax1.xaxis.set_ticks(np.arange(0, 361, 60)) ax1.yaxis.set_ticks(np.arange(-80, 81, 20)) sc = ax1.scatter(xs, ys, c=zs, s=20, cmap="PuBu", marker="o", edgecolor="none", vmax=0.5, vmin=0.0) cb = plt.colorbar(sc, pad=0.01, ticks=[0.08, 0.16, 0.24, 0.32, 0.4, 0.48]) cb.ax.set_yticklabels(["0.08", "0.16", "0.24", "0.32", "0.40", ">0.5"]) #grbs_plot = ax1.scatter(grb_ra, grb_dec, edgecolor=grb_col, facecolor=grb_ebv, s = 50, vmax = 1.0, vmin= 0.0, cmap="PuBu") grbs_plot = ax1.scatter(grb_ra, grb_dec, c=grb_ebv, s=60, cmap="PuBu", edgecolor=grb_col, vmax=0.5, vmin=0.0, marker="o") cb.set_label(r'$\rm{E_{B-V}\, (mag)}$', fontsize=18) #grbs_plot = ax1.scatter(grb_ra, grb_dec, marker = "o", color="#31a354")
grb_col.append("#d7301f") elif s[12] == "yellow": grb_col.append("#df65b0") elif s[12] == "blue": grb_col.append("#08306b") grb_data_file.close() ax1.set_xlim([0, 360]) ax1.set_ylim([-90, 90]) ax1.set_xlabel(r'$\rm{Right\, Ascension\, (J2000)}$', fontsize=18) ax1.set_ylabel(r'$\rm{Declination\, (J2000)}$', fontsize=18) ax1.xaxis.set_ticks(np.arange(0, 361, 60)) ax1.yaxis.set_ticks(np.arange(-80, 81, 20)) sc = ax1.scatter(xs, ys, c=zs, s = 20, cmap="PuBu", marker = "o", edgecolor="none", vmax = 0.30e22) cb = plt.colorbar(sc, pad=0.01, ticks=[0.5e21, 1.0e21, 1.5e21, 2.0e21, 2.5e21, 3.0e21]) cb.ax.set_yticklabels(["0.5", "1.0", "1.5", "2.0", "2.5", ">3"]) cb.set_label(r'$\rm{N_H\,10^{21}\,(cm^{-2})}$', fontsize=18) #grbs_plot = ax1.scatter(grb_ra, grb_dec, c=grb_col, facecolors='none', edgecolors='red', s = 40) #grbs_plot = ax1.scatter(grb_ra, grb_dec, c=grb_col, s = 40) grbs_plot = ax1.scatter(grb_ra, grb_dec, c=grb_nh, s = 60, cmap="PuBu", edgecolor=grb_col, vmax = 0.30e22, marker = "o") fig.savefig("nh_map.pdf", format = "pdf") fig.savefig("nh_map.jpeg", format = "jpeg") #plt.show()
elif s[12] == "blue": grb_col.append("#08306b") grb_data_file.close() ax1.set_xlim([0, 360]) ax1.set_ylim([-90, 90]) ax1.set_xlabel(r'$\rm{Right\, Ascension\, (J2000)}$', fontsize=18) ax1.set_ylabel(r'$\rm{Declination\, (J2000)}$', fontsize=18) ax1.xaxis.set_ticks(np.arange(0, 361, 60)) ax1.yaxis.set_ticks(np.arange(-80, 81, 20)) sc = ax1.scatter(xs, ys, c=zs, s = 20, cmap="PuBu", marker = "o", edgecolor="none", vmax = 0.5, vmin= 0.0) cb = plt.colorbar(sc, pad=0.01, ticks=[0.08, 0.16, 0.24, 0.32, 0.4, 0.48]) cb.ax.set_yticklabels(["0.08", "0.16", "0.24", "0.32", "0.40", ">0.5"]) #grbs_plot = ax1.scatter(grb_ra, grb_dec, edgecolor=grb_col, facecolor=grb_ebv, s = 50, vmax = 1.0, vmin= 0.0, cmap="PuBu") grbs_plot = ax1.scatter(grb_ra, grb_dec, c=grb_ebv, s = 60, cmap="PuBu", edgecolor=grb_col, vmax = 0.5, vmin = 0.0, marker = "o") cb.set_label(r'$\rm{E_{B-V}\, (mag)}$', fontsize=18) #grbs_plot = ax1.scatter(grb_ra, grb_dec, marker = "o", color="#31a354") fig.savefig("ebv_map.pdf", format = "pdf") fig.savefig("ebv_map.jpeg", format = "jpeg") #plt.show()
fsr_max_error.append(max_array) f.close() for array in fsr_kinf_error: nparray = numpy.array(array) fig = plt.figure() plt.pcolor( numpy.linspace(0, 5, 5), numpy.linspace(0, 5, 5), nparray, edgecolors="k", linewidths=1, vmin=nparray[:, :].min(), vmax=nparray[:, :].max(), ) plt.colorbar() plt.axis([0, 5, 0, 5]) plt.title("FSR K-infinity Errors") plt.gca().axes.get_xaxis().set_ticks([]) plt.gca().axes.get_yaxis().set_ticks([]) plt.show() fig.savefig(assembly_list[fsr_kinf_error.index(array)] + "-fsr-kinf-errors.jpeg") for array in fsr_mean_error: nparray = numpy.array(array) fig = plt.figure() plt.pcolor( numpy.linspace(0, 5, 5), numpy.linspace(0, 5, 5), nparray, edgecolors="k",
def imshow_zero_center(image, **kwargs): lim = tf.reduce_max(abs(image)) plt.imshow(image, vmin=-lim, vmax=lim, cmap='seismic', **kwargs) plt.colorbar()
elif i == 3: wtt = 3 elif i == 4: wtt = 4 elif i == 5: wtt = 5 elif i == 6: wtt = 6 elif i == 7: wtt = 7 elif i == 8: wtt = 8 else: wtt = 9 title = "Cluster " + str(wtt) ax.set_title(title, fontsize=15) if i == 8: axlist[-1].set_visible(False) plt.colorbar(cs, ax=axlist[:]) i = i + 1 # axlist[6].set_visible(False) plt.suptitle( "MSLP, 850 hPa u- v- Wind, and Precipitation Anomaly", fontsize=25, fontweight="bold", ) title1 = outdir + "/" + str(wtt) + "mslp_uv_prec" plt.savefig(title1, bbox_inches="tight")
def plot_lib(x_nodes,l,b,topo_in_file,bouger_in_file,geoid_in_file,FA_in_file,heatflux_in_file,anomaly,c,l_nodes,b_nodes,mat,max_depth, label_size,marker_size,anomaly_x,anomaly_y,anomaly_amount,anomaly_type,anomaly_compo,anomaly_color): # # Making string list of the observables file input # #data_list=[];data_list.extend([topo_in_file,bouger_in_file,FA_in_file,geoid_in_file,heatflux_in_file]) # ## Figuring out what input files are given #name_len=[ len(data_list[k]) for k in range(len(data_list)) ]; #for i in range(len(name_len)): # if name_len[i] != 0 : # plot it # else # pass try: topo=np.loadtxt(topo_in_file)#f=np.loadtxt(self.digitized,comments=">") max_depth = -max_depth min_depth = max(topo[:,1]/1000) except Exception: max_depth = -400 min_depth = 3 # Initializing the figure # fig = plt.figure() #gs = gridspec.GridSpec(6, 1, width_ratios=[3, 1]) gs = gridspec.GridSpec(6, 1,height_ratios=[1,1,1,1,1,3]) # # ploting the bodies geometry # ax1 = plt.subplot(gs[5]) #fig.add_subplot(616) for i in range(len(l_nodes)): ax1.plot(l_nodes[i],b_nodes[i],color='black',lw=1,marker=None) poly = Polygon(list(zip(l_nodes[i],b_nodes[i])),facecolor=c[i],label=mat[i], lw=1) ax1.add_patch(poly) for i in range(len(anomaly_x)): ax1.plot(anomaly_x[i],anomaly_y[i],color="green",lw=1,marker='o',markersize=4) poly = Polygon(list(zip(anomaly_x[i],anomaly_y[i])),facecolor=anomaly_color[i],label="anomaly", lw=1) l_text=min(anomaly_x[i])+ (max(anomaly_x[i])-min(anomaly_x[i]))/2 b_text=min(anomaly_y[i])+ (max(anomaly_y[i])-min(anomaly_y[i]))/2 ax1.add_patch(poly) ax1.text(l_text, b_text, str(int(i+1))+" "+str(anomaly_type[i])+" Material" +str(anomaly_compo[i])+""+str(anomaly_amount[i]), fontsize=8,fontstyle='italic',color='black',bbox=dict(facecolor='white', alpha=0.9)) #ax1.plot(l[i][:],b[i][:],color='grey',linewidth=0.5) ax1.grid(True) ax1.tick_params(labelsize=10) plt.ylim((max_depth,min_depth)) plt.title('Profile Geometry') plt.xlabel('Distance ($km$)') plt.ylabel('Depth ($km$)') # # plotting the topography # ax2 = plt.subplot(gs[4])#fig.add_subplot(611) # topography data f_out=open("topo_out.dat","r") data_out=f_out.readlines() try: f_in=open(topo_in_file,"r") #f_in=open("test_top.dat","r")#f_in=open("test_top.dat","r") data_in=f_in.readlines() f_in.close() except Exception: data_in=data_out profile_out=[] profile_in=[] if anomaly==1: topo_in=[] topo_error=[] topo_out_coupled=[] topo_out_uncoupled=[] f_out.close() ## storing data into local variables for i in range(len(data_in)): try: data_temp=data_out[i].split() except IndexError: data_temp=[] pass try: profile_out.append(float(str(data_temp[0]))) topo_out_coupled.append(float(str(data_temp[1]))) topo_out_uncoupled.append(float(str(data_temp[2]))) except ValueError: data_temp=[] pass try: data_temp=data_in[i].split() except IndexError: data_temp=[] pass try: profile_in.append(float(str(data_temp[0]))) topo_in.append(float(str(data_temp[1]))) try: topo_error.append(float(str(data_temp[2]))) except: topo_error.append(0) except ValueError: data_temp=[] pass plt.hold(True) ax2.errorbar(profile_in,topo_in,yerr=topo_error,fmt='o-',markersize=marker_size,ecolor='b',label='Observed') ax2.plot(profile_out,topo_out_coupled,'k-',label='Coupled' ) ax2.plot(profile_out,topo_out_uncoupled, 'r-',label='Uncoupled') ''' ax2_=ax2.twinx() diff=[] diff=np.subtract(topo_out_uncoupled,topo_in) ax2_.plot(profile_out,diff,color='g',label='Diff') ax2_.set_ylabel('Diff', color='g') ax2_.tick_params('y', colors='g') ''' #ax2.plot(profile_in,topo_in, 'b-',label='Observed') ax2.grid(True) ax2.set_title('Elevation ') ax2.xaxis.set_ticklabels([]) ax2.tick_params(labelsize=10) #plt.xlabel('Distance (Km)') plt.ylabel('Elevation ($m$)') plt.legend( fancybox=True, framealpha=0.5,fontsize=8,loc='best') #ax2.legend(handles, ['input','Computed-coupled','Computed-uncoupled']) else: topo_in=[] topo_error=[] topo_out=[] f_out.close() ## storing data into local variables for i in range(len(data_in)): try: data_temp=data_out[i].split() except IndexError: pass try: profile_out.append(float(str(data_temp[0]))) topo_out.append(float(str(data_temp[1]))) except ValueError: passa try: data_temp=data_in[i].split() except IndexError: pass try: profile_in.append(float(str(data_temp[0]))) topo_in.append(float(str(data_temp[1]))) try: topo_error.append(float(str(data_temp[2]))) except: topo_error.append(0) except ValueError: pass #topo_misfit= (topo_in - topo_out)/len(topo_in) #print topo_misfit plt.hold(True) #ax2.plot(profile_in,topo_in, 'b-',label='Observed') ax2.errorbar(profile_in,topo_in,yerr=topo_error,fmt='o-',markersize=marker_size,ecolor='b',label='Observed') ax2.plot(profile_out,topo_out,'r-',label='Calculated') ''' ax2_=ax2.twinx() diff=[] diff=np.subtract(topo_out,topo_in) ax2_.plot(profile_out,diff,color='g',label='Diff') ax2_.set_ylabel('Diff', color='g') ax2_.tick_params('y', colors='g') ''' #ax2.fill(profile_in,topo_in+topo_error,zorder=10) ax2.grid(True) ax2.set_title('Elevation') ax2.xaxis.set_ticklabels([]) ax2.tick_params(labelsize=10) #plt.xlabel('Distance (Km)') plt.ylabel('Elevation ($m$)') plt.legend( fancybox=True, framealpha=0.5,fontsize=8,loc='best') # # bouguer data # f_out=open("bouguer_out.dat","r") data_out=f_out.readlines() try: f_in=open(bouger_in_file,"r") #f_in=open("test_bou.dat","r") data_in=f_in.readlines() f_in.close() except Exception: data_in=data_out profile_out=[] profile_in=[] boug_in=[] boug_out=[] boug_error=[] for i in range(len(data_in)): try: data_temp=data_out[i].split() except IndexError: pass try: profile_out.append(float(str(data_temp[0]))) boug_out.append(float(str(data_temp[1]))) except ValueError: pass try: data_temp=data_in[i].split() except IndexError: pass try: profile_in.append(float(str(data_temp[0]))) boug_in.append(float(str(data_temp[1]))) try: boug_error.append(float(str(data_temp[2]))) except: boug_error.append(0.0) except ValueError: pass ax3 = plt.subplot(gs[3])#fig.add_subplot(612) plt.hold(True) #ax3.plot(profile_in,boug_in, 'b-') ax3.errorbar(profile_in,boug_in,yerr=boug_error,fmt='o-',markersize=marker_size,ecolor='b',label='Observed') ax3.plot(profile_out,boug_out,'r-',label='Calculated') ''' ax3_=ax3.twinx() diff=[] diff=np.subtract(boug_out,boug_in[range(len(boug_out))]) ax3_.plot(profile_out,diff,color='g',label='Diff') ax3_.set_ylabel('Diff', color='g') ax3_.tick_params('y', colors='g') ''' ax3.grid(True) ax3.set_title('Bouguer') ax3.xaxis.set_ticklabels([]) ax3.tick_params(labelsize=10) #plt.xlabel('Distance (Km)') plt.legend( fancybox=True, framealpha=0.5,fontsize=8,loc='best') plt.ylabel('Bouguer ($mGal$)') f_out.close() # # geoid data # f_out=open("geoid_out.dat","r") data_out=f_out.readlines() try: f_in=open(geoid_in_file,"r")#f_in=open("test_geo.dat","r") data_in=f_in.readlines() f_in.close() except Exception: data_in=data_out profile_out=[] profile_in=[] geoid_in=[] geoid_out=[] geoid_error=[] for i in range(len(data_in)): try: data_temp=data_out[i].split() except IndexError: pass try: profile_out.append(float(str(data_temp[0]))) geoid_out.append(float(str(data_temp[1]))) except ValueError: pass try: data_temp=data_in[i].split() except IndexError: pass try: profile_in.append(float(str(data_temp[0]))) geoid_in.append(float(str(data_temp[1]))) try: geoid_error.append(float(str(data_temp[2]))) except IndexError: geoid_error.append(0.0) except ValueError: pass #geoid_in=np.loadtxt(geoid_in_file) ax4 = plt.subplot(gs[2])#fig.add_subplot(614) plt.hold(True) ax4.plot(profile_in,geoid_in, 'b-') ax4.errorbar(profile_in,geoid_in,yerr=geoid_error,fmt='o-',markersize=marker_size,ecolor='b',label='Observed') ''' ax4_=ax4.twinx() diff=[] diff=np.subtract(geoid_out,geoid_in[range(len(geoid_out))]) ax4_.plot(profile_out,diff,color='g',label='Diff') ax4_.set_ylabel('Diff', color='g') ax4_.tick_params('y', colors='g') ''' #test=[] #test=smoothListGaussian(geoid_in,degree=1) #ax4.plot(profile_in[0:len(test)],test,fmt='o-',markersize=marker_size,color='black',label='Observed--9') ''' try: ax4.errorbar(geoid_in[:,0],geoid_in[:,1],yerr=geoid_in[:,2],fmt='o-',markersize=marker_size,ecolor='b',label='8') plt.hold(True) except Exception: pass try: ax4.errorbar(geoid_in[:,0],geoid_in[:,3],yerr=geoid_in[:,4],fmt='o-',markersize=marker_size,ecolor='k',label='9') plt.hold(True) except Exception: pass try: ax4.errorbar(geoid_in[:,0],geoid_in[:,5],yerr=geoid_in[:,6],fmt='o-',markersize=marker_size,ecolor='m',label='10') plt.hold(True) except Exception: pass ''' plt.hold(True) ax4.plot(profile_out,geoid_out,'r-', label='Calculated') ax4.grid(True) ax4.set_title('Geoid') ax4.xaxis.set_ticklabels([]) ax4.tick_params(labelsize=10) plt.legend( fancybox=True, framealpha=0.5,fontsize=8,loc='best') #plt.xlabel('Distance (Km)') plt.ylabel('Geoid ($m$)') f_out.close() # # heat flux data # f_out=open("SHF_out.dat","r") data_out=f_out.readlines() f_out.close() try: f_in=open(heatflux_in_file,"r")#f_in=open("fluxout.dat","r") data_in=f_in.readlines() f_in.close() except Exception: data_in=data_out profile_out=[] profile_in=[] flux_in=[] flux_out=[] flux_error=[] for i in range(len(data_out)): try: data_temp=data_out[i].split() except IndexError: pass try: profile_out.append(float(str(data_temp[0]))) flux_out.append(float(str(data_temp[1]))) except ValueError: pass try: data_temp=data_in[i].split() except IndexError: pass for i in range(len(data_in)): try: data_temp=data_in[i].split() except IndexError: pass try: profile_in.append(float(str(data_temp[0]))) flux_in.append(float(str(data_temp[1]))) try: flux_error.append(float(str(data_temp[2]))) except IndexError: flux_error.append(0.0) except ValueError: pass try: data_temp=data_in[i].split() except IndexError: pass ax5 = plt.subplot(gs[0])#fig.add_subplot(615) plt.hold(True) ax5.errorbar(profile_in,flux_in,yerr=flux_error,fmt='o-',markersize=marker_size,ecolor='b',label='Observed') ax5.plot(profile_out,flux_out,'r-',label='Calculated') ax5.grid(True) ax5.set_title('Heat Flux') ax5.xaxis.set_ticklabels([]) ax5.tick_params(labelsize=10) #plt.xlabel('Distance (Km)') plt.legend( fancybox=True, framealpha=0.5,fontsize=8,loc='best') plt.ylabel('Heat-flux ($mW/m^2$)') #plt.tight_layout() #plt.tight_layout() # # FA data # f_out=open("FA_out.dat","r") data_out=f_out.readlines() f_out.close() try: f_in=open(FA_in_file,"r")#f_in=open("fluxout.dat","r") data_in=f_in.readlines() f_in.close() except Exception: data_in=data_out profile_out=[] profile_in=[] FA_in=[] FA_out=[] FA_error=[] for i in range(len(data_in)): try: data_temp=data_out[i].split() except IndexError: pass try: profile_out.append(float(str(data_temp[0]))) FA_out.append(float(str(data_temp[1]))) except ValueError: pass try: data_temp=data_in[i].split() except IndexError: pass try: profile_in.append(float(str(data_temp[0]))) FA_in.append(float(str(data_temp[1]))) try: FA_error.append(float(str(data_temp[2]))) except IndexError: FA_error.append(0.0) except ValueError: pass ax6 = plt.subplot(gs[1])#fig.add_subplot(613) plt.hold(True) #ax6.plot(profile_in,FA_in, 'b-') ax6.errorbar(profile_in,FA_in,yerr=FA_error,fmt='o-',markersize=marker_size,ecolor='b',label='Observed') ax6.plot(profile_out,FA_out,'r-',label='Calculated') ''' ax6_=ax6.twinx() diff=[] diff=np.subtract(FA_out,FA_in[range(len(FA_out))]) ax6_.plot(profile_out,diff,color='g',label='Diff') ax6_.set_ylabel('Diff', color='g') ax6_.tick_params('y', colors='g') ''' ax6.grid(True) ax6.set_title('Free-Air') ax6.xaxis.set_ticklabels([]) ax6.tick_params(labelsize=10) plt.legend( fancybox=True, framealpha=0.5,fontsize=8,loc='best') #plt.xlabel('Distance (Km)') plt.ylabel('FA (mGal)') #plt.tight_layout() multi = MultiCursor(fig.canvas,(ax1,ax2,ax3,ax4,ax5,ax6), color='r', lw=1) ##############33 temperature profile plotting gs_ = gridspec.GridSpec(4, 1) #fig_out = plt.figure() fig_out = plt.figure() #ax_temp = fig_out.add_subplot(411) ax_temp =plt.subplot(gs_[0]) #fig_out.add_subplot(411) f=open("tempout.dat","r") data_out=f.readlines() temp_x=[] temp_y=[] temp_z=[] for i in range(2,len(data_out)): data_temp=data_out[i].split() temp_x.append(float(str(data_temp[0]))) temp_y.append(float(str(data_temp[1]))) temp_z.append(float(str(data_temp[2]))) xlist=[] ylist = np.array(temp_y[0:96]) z =temp_z #np.array(temp_z) Z=[] temp=0 for i in range(0,x_nodes): tmp = [] xlist.append(temp_x[temp]) for j in range(0,96): tmp.append(z[temp]) temp=temp+1 Z.append(tmp) X,Y = np.meshgrid(ylist, xlist) levels = np.linspace(0, 50, 1600) for i in range(len(l)): ax_temp.plot(l[i][:],b[i][:],color='grey',linewidth=2) levels =[300,500,600,1000,1200,1300,1450,1550,1650] CS3 = plt.contourf(Y, X, Z, levels,extend='both',cmap=plt.cm.get_cmap('coolwarm',20)) CS3.cmap.set_under('white') CS3.cmap.set_over('black') #levels = np.arange(min(temp_z), max(temp_z)+100, 100) CS4 = plt.contour(Y, X, Z, levels,linewidths=0.2,linestyles='dashed',colors='black') plt.clabel(CS4,inline=5,inline_spacing=10,fontsize=10,fontstyles='arial',fontweight='bold',fmt='%1.0f',colors='black') plt.colorbar(CS3,label='$^oC$') plt.title('Temperature',fontsize=10, fontweight='bold') """ cp = plt.contourf(Y,X,Z) plt.colorbar(cp) #cpc=plt.contour(Y,X,Z,levels) # predefinrd number of contour CS = plt.contour(Y, X, Z, 30 ,linewidths=0.5,colors='grey') # automatice number of contours plt.clabel(CS,inline=1,inline_spacing=0,fontsize=12,fmt='%1.0f',colors='black') #plt.clabel(CS, inline=1, fontsize=10,color="black") # contour line labels """ #plt.title('Temperature profile') #plt.xlabel('Distance ($km$)') plt.tick_params(labelsize=10) plt.ylabel('Depth ($km$)') ##############33 density profile plotting f=open("dens_node2.dat","r") data_out=f.readlines() temp_x=[] temp_y=[] temp_z=[] for i in range(len(data_out)): data_temp=data_out[i].split() temp_x.append(float(str(data_temp[0]))) temp_y.append(float(str(data_temp[1]))) temp_z.append(float(str(data_temp[2]))) xlist=[] ylist = np.array(temp_y[0:95]) z =temp_z #np.array(temp_z) Z=[] temp=0 for i in range(0,x_nodes): tmp = [] xlist.append(temp_x[temp]) for j in range(0,95): tmp.append(z[temp]) temp=temp+1 Z.append(tmp) X,Y = np.meshgrid(ylist, xlist) levels = np.linspace(0, 50, 1600) #ax_dens = fig_out.add_subplot(412) ax_dens =plt.subplot(gs_[1]) for i in range(len(l)): ax_dens.plot(l[i][:],b[i][:],color='grey',linewidth=2) levels = np.arange(2800, 3800, 50) #levels = np.arange(3000, 3800, 20) CS3 = plt.contourf(Y, X, Z, levels,extend='both',cmap=plt.cm.get_cmap('rainbow',20),origin=origin) CS3.cmap.set_under('white') CS3.cmap.set_over('black') levels = np.arange(3000, 3800, 50) CS4 = plt.contour(Y, X, Z,levels,linewidths=0.2,linestyles='dashed',colors='grey') plt.clabel(CS4,inline=True,inline_spacing=2,fontsize=10,fontstyles='arial',fontweight='normal',fmt='%1.0f',colors='black') plt.colorbar(CS3,label='$kg/m^3$') plt.title('Density',fontsize=10, fontweight='bold') plt.tick_params(labelsize=10) """ cp = plt.contourf(Y,X,Z) plt.colorbar(cp)3 #cpc=plt.contour(Y,X,Z,levels) # predefinrd number of contour CS = plt.contour(Y, X, Z, 30 ,linewidths=0.5,colors='grey') # automatice number of contours plt.clabel(CS,inline=1,inline_spacing=0,fontsize=12,fmt='%1.0f',colors='black') #plt.clabel(CS, inline=1, fontsize=10,color="black") # contour line labels """ #plt.title('Density profile') #plt.xlabel('Distance ($km$)') plt.ylabel('Depth ($km$)') ##############33 Vp profile plotting #f=open("velatten.dat","r") f=open("velocities.dat","r") data_out=f.readlines() temp_x=[] temp_y=[] temp_z_vp=[] temp_z_vs=[] for i in range(len(data_out)): data_temp=data_out[i].split() temp_x.append(float(str(data_temp[0]))) temp_y.append(float(str(data_temp[1]))) temp_z_vp.append(float(str(data_temp[2]))) temp_z_vs.append(float(str(data_temp[3]))) xlist=[] ylist = np.array(temp_y[0:95]) z_vp =temp_z_vp #np.array(temp_z) z_vs =temp_z_vs Z_vp=[] Z_vs=[] temp=0 for i in range(0,x_nodes): tmp1 = [] tmp2 = [] xlist.append(temp_x[temp+1]) for j in range(0,95): tmp1.append(z_vp[temp]) tmp2.append(z_vs[temp]) temp=temp+1 Z_vp.append(tmp1) Z_vs.append(tmp2) X,Y = np.meshgrid(ylist, xlist) levels = np.linspace(0, 50, 1600) #ax_vp = fig_out.add_subplot(413) ax_vp =plt.subplot(gs_[2]) for i in range(len(l)): ax_vp.plot(l[i][:],b[i][:],color='grey',linewidth=2) levels = np.arange(7.2, 8.8, 0.01) CS3 = plt.contourf(Y, X, Z_vp, levels,extend='both',cmap=plt.cm.get_cmap('RdYlBu',20),origin=origin) #CS3 = plt.contourf(Y, X, Z_vp, levels,extend='both',cmap=cmap,origin=origin) CS3.cmap.set_under('white') CS3.cmap.set_over('black') levels = np.arange(7.7, 8.8, 0.05) CS4 = plt.contour(Y, X, Z_vp, levels,linewidths=0.2,linestyles='dashed',colors='black') plt.clabel(CS4,inline=5,inline_spacing=10,fontsize=10,fmt='%1.1f',colors='black') plt.colorbar(CS3,label='$km/s$') plt.tick_params(labelsize=10) plt.title('P wave velocity',fontsize=10, fontweight='bold') #plt.xlabel('Distance ($km$)') plt.ylabel('Depth ($km$)') #ax_vs = fig_out.add_subplot(414) ax_vs =plt.subplot(gs_[3]) for i in range(len(l)): ax_vs.plot(l[i][:],b[i][:],color='grey',linewidth=2) levels = np.arange(4.2, 4.8, 0.01) #CS3 = plt.contourf(Y, X, Z_vs, levels,extend='both') CS3 = plt.contourf(Y, X, Z_vs, levels,extend='both',cmap=plt.cm.get_cmap('RdYlBu',20),origin=origin) CS3.cmap.set_under('white') CS3.cmap.set_over('black') #levels = np.arange(4.1, 4.8, 0.05) levels = np.arange(4.3, 5.1, 0.05) CS4 = plt.contour(Y, X, Z_vs, levels,linewidths=0.2,linestyles='dashed',colors='black') plt.clabel(CS4,inline=5,inline_spacing=10,fontsize=10,fmt='%1.1f',colors='black') plt.colorbar(CS3,label='$km/s$') plt.title('S wave velocity',fontsize=10, fontweight='bold') plt.xlabel('Distance ($km$)') plt.ylabel('Depth ($km$)') plt.tick_params(labelsize=10) #plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) #plt.tight_layout() savefig('Temp_Dens_velocities.png', dpi=300) ###########################3 ### calculating the misfit #boug_misfit= (bouger_in - bouguer_out)/len(bouger_in) #print boug_misfit #geoid_misfit=(geoid_in - geoid_out )/len(geoid_in) #print geoid_misfit ################## plt.show()