def plotting(xgrid, vgrid, x, v, f, scalar_field, f0, timestep, plot_save, plot_show): if (plot_show == 1): plt.clf() plt.ion() # plt.subplot(2,1,1) plt.pcolormesh(xgrid, vgrid, f) plt.axis([x[0], x[-1], v[0], v[-1]]) plt.xlabel('X', fontsize=20) plt.ylabel('V', fontsize=20) plt.title('Phase Space') # Electric Field Comparison # time = 0.02*timestep # Et = 4.0*0.01 * 0.3677 * np.exp(-0.1533*time)*np.sin(0.5*x)*np.cos(1.4156*time - 0.5326245) # plot_title = 't = '+str(timestep*0.02) # plt.plot(x,scalar_field) # plt.plot(x,Et) # plt.title(plot_title) # plt.subplot(2,1,2) # plt.plot(x,potential) # plt.xlabel('X') # plt.ylabel('$\phi$') if (plot_show == 1): plt.draw() plt.pause(.05) if (plot_save == 1): FIG_NAME = 'OUT/f_nonlinear_' + str(timestep) + '.png' plt.savefig(FIG_NAME)
def display_observation(signal_large, f_min, f_max, fs, window_size_t, config, figure_title, figure_path): """ Function used to display an observation, either to make observations to annotate, either to check predictions """ # Get spectrofram window spectro_window_size = config.display['spectro_window_size'] if config.display['window_type'] == 'kaiser': w = sg.kaiser(spectro_window_size, 18) w = w * spectro_window_size / sum([pow(j, 2) for j in w]) else: print('window %s not implemented yet' % config.display['window_type']) return None # Get signal that will be displayed from input signal if config.display['decimate_factor'] is None: spectro_signal = signal_large fs_spectro = fs else: spectro_signal = sg.decimate(signal_large, config.display['decimate_factor'], zero_phase=True) fs_spectro = int(fs / config.display['decimate_factor']) # Compute spectrogram f, time, spec = sg.spectrogram( spectro_signal, fs=fs_spectro, nperseg=eval(config.display['nperseg']), noverlap=eval(config.display['noverlap']), nfft=eval(config.display['nfft']), window=w, scaling=config.display['scaling']) # PSD in unit(x)**2/Hz if eval(config.display['dB']): spec_db = 10 * np.log10(spec) # Make figure and all the proper display on it fig = plt.figure(figsize=(15, 6)) ax = fig.add_subplot(111) plt.pcolormesh(time, f, spec_db, shading='flat', vmin=30, vmax=85) cbar = plt.colorbar() cbar.set_label('Energy (dB)', size=25) cbar.ax.tick_params(labelsize=25) plt.xlabel('Time (s)', size=25) plt.ylabel('Frequency (Hz)', size=25) ax.tick_params(labelsize=25) # Plot the rectangle (observation) height = f_max - f_min plt.title(figure_title, size=25) my_rectangle = patches.Rectangle((window_size_t, f_min), window_size_t, height, alpha=1, facecolor='none', edgecolor='red', linewidth=5) ax.add_patch(my_rectangle) # Save everything plt.savefig(figure_path + '.png', format='png') plt.close('all') # And off you go ! return
def plot_classifier(classifier, X, y): # 定义图形的取值范围,在最大值,最小值的基础上增加余量(buffer) X_min, X_max = min(X[:, 0]) - 1.0, max(X[:, 0]) + 1.0 y_min, y_max = min(X[:, 1]) - 1.0, max(X[:, 0]) + 1.0 # 设置网格(grid)数据画出边界 # 设置网格步长 step_size = 0.01 # 定义网格 X_values, y_values = np.meshgrid(np.arange(X_min, X_max, step_size), np.arange(y_min, y_max, step_size)) # 计算分类器的输出结果 mesh_output = classifier.predict(np.c_[X_values.ravel(), y_values.ravel()]) # 数组维度变形 mesh_output = mesh_output.reshape(X_values.shape) # 作图 plt.figure() plt.pcolormesh(X_values, y_values, mesh_output, cmap=plt.cm.gray) plt.scatter(X[:, 0], X[:, 1], c=y, s=80, edgecolors='black', linewidth=1, cmap=plt.cm.Paired) plt.xlim(X_values.min(), X_values.max()) plt.ylim(y_values.min(), y_values.max()) # 设置X轴,Y轴 plt.xticks((np.arange(int(min(X[:, 0]) - 1), int(max(X[:, 0]) + 1), 1.0))) plt.yticks((np.arange(int(min(X[:, 1]) - 1), int(max(X[:, 1]) + 1), 1.0))) plt.show()
def plot_prof(obj): '''Function that plots a vertical profile of scattering from TOC to BOC. Input: rt_layer instance object. Output: plot of scattering. ''' I = obj.Inodes[:,1,:] \ / -obj.mu_s y = np.linspace(obj.Lc, 0., obj.K + 1) x = obj.views * 180. / np.pi xm = np.array([]) for i in np.arange(0, len(x) - 1): nx = x[i] + (x[i + 1] - x[i]) / 2. xm = np.append(xm, nx) xm = np.insert(xm, 0, 0.) xm = np.append(xm, 180.) xx, yy = np.meshgrid(xm, y) plt.pcolormesh(xx, yy, I) plt.colorbar() plt.title('Canopy Fluxes') plt.xlabel('Exit Zenith Angle') plt.ylabel('Cumulative LAI (0=soil)') plt.arrow(135.,3.5,0.,-3.,head_width=5.,head_length=.2,\ fc='k',ec='k') plt.text(140., 2.5, 'Downwelling Flux', rotation=90) plt.arrow(45.,.5,0.,3.,head_width=5.,head_length=.2,\ fc='k',ec='k') plt.text(35., 2.5, 'Upwelling Flux', rotation=270) plt.show()
def plot_field(self,x,y,u=None,v=None,F=None,contour=False,outdir=None,plot='quiver',figname='_field',format='eps'): outdir = self.set_dir(outdir) p = 64 if F is None: F=self.calc_F(u,v) plt.close('all') plt.figure() #fig, axes = plt.subplots(nrows=1) if contour: plt.hold(True) plt.contourf(x,y,F) if plot=='quiver': plt.quiver(x[::p],y[::p],u[::p],v[::p],scale=0.1) if plot=='pcolor': plt.pcolormesh(x[::4],y[::4],F[::4],cmap=plt.cm.Pastel1) plt.colorbar() if plot=='stream': speed = F[::16] plt.streamplot(x[::16], y[::16], u[::16], v[::16], density=(1,1),color='k') plt.xlabel('$x$ (a.u.)') plt.ylabel('$y$ (a.u.)') plt.savefig(os.path.join(outdir,figname+'.'+format),format=format,dpi=320,bbox_inches='tight') plt.close()
def plot_heatmap_2discretes(x_vec, y_vec, heatmap, base=10, xlabel=None, ylabel=None, outfn=None): n, m = heatmap.shape fig = plt.figure(figsize=(8, 6.5), dpi=96) plt.pcolormesh(heatmap, cmap='jet', norm=LogNorm(), rasterized=True) cb = plt.colorbar() for l in cb.ax.yaxis.get_ticklabels(): l.set_family('Times New roman') l.set_size(20) ax = fig.gca() xticks = ax.get_xticks() if xticks[-1] > m: xticks = xticks[:-1] ### for triangle_count / degree feature nw_xtick = [] for xt in xticks: if ((xt < m) and (xt % 20 == 0)): xval = x_vec[int(xt)] if xval < 1e3: nw_xtick.append(r'%d' % xval) else: pws = int(np.log10(xval)) fv = xval * 1.0 / 10**pws nw_xtick.append(r'%.1fE%d'%(fv, pws)) else: nw_xtick.append('') nw_ytick = [] for yt in ax.get_yticks(): if yt < n: yval = y_vec[int(yt)] if yval < 1e3: nw_ytick.append(r'%d' % yval) else: pws = int(np.log10(yval)) fv = yval * 1.0 / 10**pws nw_ytick.append('%.1fE%d'%(fv, pws)) if nw_xtick[-1] == '': nw_xtick[-1] = '%.2f'%x_vec[-1] # nw_xtick[-1] = '%.2f'%np.power(base, x_vec[-1]) if nw_ytick[-1] == '': nw_ytick[-1] = '%d' % int(y_vec[-1]) # nw_ytick = '%d' % int(np.power(base, y_vec[-1])) ax.set_xticklabels(nw_xtick, fontsize=27, family='Times New roman') ax.set_yticklabels(nw_ytick, fontsize=27, family='Times New roman') if xlabel is not None: plt.xlabel(xlabel, linespacing=12, fontsize=32, family='Times New roman') if ylabel is not None: plt.ylabel(ylabel, linespacing=12, fontsize=32, family='Times New roman') # fig.set_size_inches(8, 7.3) fig.tight_layout() if outfn is not None: fig.savefig(outfn) plt.close() return fig
def compute_nudging_term(self, date, model_state): # Get model SSH state ssh = model_state.getvar(0) # 1st variable (ssh) # Get observations and nudging parameters obs_ssh, nudging_coeff_ssh, sigma_ssh =\ bfn_get_data_at_t(date, self.dict_proj_ssh) obs_rv, nudging_coeff_rv, sigma_rv =\ bfn_get_data_at_t(date, self.dict_proj_rv) # Compute nudging term N = {'ssh':np.zeros_like(ssh), 'rv':np.zeros_like(ssh)} if obs_rv is not None and np.any(np.isfinite(obs_rv)): # Nudging towards relative vorticity rv = switchvar.ssh2rv( ssh, self.lon2d, self.lat2d, name_grd=self.name_grd) nobs = len(obs_rv) for iobs in range(nobs): indNoNan = ~np.isnan(obs_rv[iobs]) if np.any(indNoNan): # Filter model state for spectral nudging rv_ls = rv.copy() if sigma_rv[iobs] is not None and sigma_rv[iobs]>0: rv_ls = gaussian_filter(rv_ls,sigma=sigma_rv[iobs]) N['rv'][indNoNan] += nudging_coeff_rv[iobs,indNoNan] *\ (obs_rv[iobs,indNoNan]-rv_ls[indNoNan]) if obs_ssh is not None and np.any(np.isfinite(obs_ssh)): # Nudging towards ssh nobs = len(obs_ssh) for iobs in range(nobs): indNoNan = ~np.isnan(obs_ssh[iobs]) if np.any(indNoNan): # Filter model state for spectral nudging ssh_ls = ssh.copy() if sigma_ssh[iobs] is not None and sigma_ssh[iobs]>0: ssh_ls = gaussian_filter(ssh_ls,sigma=sigma_ssh[iobs]) N['ssh'][indNoNan] += nudging_coeff_ssh[iobs,indNoNan] *\ (obs_ssh[iobs,indNoNan]-ssh_ls[indNoNan]) # Mask pixels that are not influenced by observations N['ssh'] = N['ssh'] * self.scalenudg[0] N['rv'] = N['rv'] * self.scalenudg[1] N['ssh'][N['ssh']==0] = np.nan N['rv'][N['rv']==0] = np.nan if self.flag_plot>3: plt.figure() plt.suptitle('Nudging coefficient') plt.pcolormesh(self.lon2d,self.lat2d,N['ssh']) plt.colorbar() plt.show() return N
def plot_p_leading_order(frame): mat = scipy.io.loadmat('sound-speed_2D-wave.mat') T=5; nt=T/0.5 pp=mat['U'][nt,:,:] xx=mat['xx'] yy=mat['yy'] fig=pl.figure(figsize=(8, 3.5)) #pl.title("t= "+str(sol.state.t),fontsize=20) pl.xticks(size=20); pl.yticks(size=20) pl.xlabel('x',fontsize=20); pl.ylabel('y',fontsize=20) #pl.pcolormesh(xx,yy,p_subxy,cmap=cm.OrRd) pl.pcolormesh(xx,yy,pp,cmap='RdBu_r') pl.autoscale(tight=True) cb = pl.colorbar(ticks=[0.5,1,1.5,2]); #pl.clim(ticks=[0.5,1,1.5,2]) imaxes = pl.gca(); pl.axes(cb.ax) pl.yticks(fontsize=20); pl.axes(imaxes) #pl.xticks(fontsize=20); pl.axes(imaxes) #pl.axis('equal') pl.axis('tight') fig.tight_layout() pl.savefig('./_plots_to_paper/sound-speed_LO_t'+str(frame)+'_pcolor.png') pl.close()
def plot_intensity_sphere_overlap(theta, phi, rho_0x, rho_0y, rho, w): """ plot intensity profile and sphere outline""" # theta - sphere theta coordinate, array # phi - sphere phi coordinate, array # rho_0x - beam x displacement, scalar # rho_0y - beam y displacement, scalar # rho - sphere diameter, scalar intensity = LG_01_Intensity_sphere_coordinate(theta, phi, rho_0x, rho_0y, rho, w) cartesian_coordinates = spherical_to_cartesian_coordinates(rho, theta, phi) x = cartesian_coordinates['x'] y = cartesian_coordinates['y'] plt.figure("beam_sphere_overlap_pcolormesh") plt.clf() plt.pcolormesh(x, y, intensity) # make sure coordiantes not distorted axes = plt.gca() axes.set_aspect('equal') sphere_outline = plt.Circle((0, 0), radius=rho, facecolor='None', edgecolor='r') axes.add_artist(sphere_outline) #plt.figure("beam_sphere_overlap_surf") #plt.su return
def main(): iris = datasets.load_iris() X = iris.data[:,:2] # 取前2个特征 Y = iris.target h = .02 # step size in the mesh lr = LogisticRegression(C=1e5) lr.fit(X,Y) # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, x_max]x[y_min, y_max]. x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 # 生成网格 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = lr.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.figure(1, figsize=(4, 3)) plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired) # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.xticks(()) plt.yticks(()) plt.show() print(lr.predict_proba([5, 3.4]))
def plot_prof(obj): '''Function that plots a vertical profile of scattering from TOC to BOC. Input: rt_layer instance object. Output: plot of scattering. ''' I = obj.Inodes[:,1,:] \ / -obj.mu_s y = np.linspace(obj.Lc, 0., obj.K+1) x = obj.views*180./np.pi xm = np.array([]) for i in np.arange(0,len(x)-1): nx = x[i] + (x[i+1]-x[i])/2. xm = np.append(xm,nx) xm = np.insert(xm,0,0.) xm = np.append(xm,180.) xx, yy = np.meshgrid(xm, y) plt.pcolormesh(xx,yy,I) plt.colorbar() plt.title('Canopy Fluxes') plt.xlabel('Exit Zenith Angle') plt.ylabel('Cumulative LAI (0=soil)') plt.arrow(135.,3.5,0.,-3.,head_width=5.,head_length=.2,\ fc='k',ec='k') plt.text(140.,2.5,'Downwelling Flux',rotation=90) plt.arrow(45.,.5,0.,3.,head_width=5.,head_length=.2,\ fc='k',ec='k') plt.text(35.,2.5,'Upwelling Flux',rotation=270) plt.show()
def plot(frame,dirname,clim=None,axis_limits=None): if not os.path.exists('./figures'): os.makedirs('./figures') try: sol=Solution(frame,file_format='petsc',read_aux=False,path='./saved_data/'+dirname+'/_p/',file_prefix='claw_p') except IOError: 'Data file not found; please unzip the files in saved_data/.' return x=sol.state.grid.x.centers; y=sol.state.grid.y.centers mx=len(x); my=len(y) mp=sol.state.num_eqn yy,xx = np.meshgrid(y,x) p=sol.state.q[0,:,:] if clim is not None: pl.pcolormesh(xx,yy,p,cmap=cm.RdBu_r) else: pl.pcolormesh(xx,yy,p,cmap=cm.Reds) pl.title("t= "+str(sol.state.t),fontsize=20) pl.xticks(size=20); pl.yticks(size=20) cb = pl.colorbar(); if clim is not None: pl.clim(clim[0],clim[1]); imaxes = pl.gca(); pl.axes(cb.ax) pl.yticks(fontsize=20); pl.axes(imaxes) pl.axis('equal') if axis_limits is None: pl.axis([np.min(x),np.max(x),np.min(y),np.max(y)]) else: pl.axis([axis_limits[0],axis_limits[1],axis_limits[2],axis_limits[3]]) pl.savefig('./figures/'+dirname+'.png') pl.close()
def plot_p_leading_order(frame): mat = scipy.io.loadmat('sound-speed_2D-wave.mat') T = 5 nt = T / 0.5 pp = mat['U'][nt, :, :] xx = mat['xx'] yy = mat['yy'] fig = pl.figure(figsize=(8, 3.5)) #pl.title("t= "+str(sol.state.t),fontsize=20) pl.xticks(size=20) pl.yticks(size=20) pl.xlabel('x', fontsize=20) pl.ylabel('y', fontsize=20) #pl.pcolormesh(xx,yy,p_subxy,cmap=cm.OrRd) pl.pcolormesh(xx, yy, pp, cmap='RdBu_r') pl.autoscale(tight=True) cb = pl.colorbar(ticks=[0.5, 1, 1.5, 2]) #pl.clim(ticks=[0.5,1,1.5,2]) imaxes = pl.gca() pl.axes(cb.ax) pl.yticks(fontsize=20) pl.axes(imaxes) #pl.xticks(fontsize=20); pl.axes(imaxes) #pl.axis('equal') pl.axis('tight') fig.tight_layout() pl.savefig('./_plots_to_paper/sound-speed_LO_t' + str(frame) + '_pcolor.png') pl.close()
def drew_result(clf, x_data, y_data, title): x1_min, x1_max = x_data[:, 0].min()-1, x_data[:, 0].max()+1 x2_min, x2_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1 t1 = np.linspace(x1_min, x1_max, 100) t2 = np.linspace(x2_min, x2_max, 100) x1, x2 = np.meshgrid(t1, t2) x_show = np.stack((x1.flat, x2.flat), axis=1) y_hat = clf.predict(x_show) # 预测 y_hat = y_hat.reshape(x1.shape) # 使之与输入的形状相同 cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0']) cm_dark = mpl.colors.ListedColormap(['g', 'r']) plt.figure(facecolor='w') plt.title(title) # 预测值的显示 plt.pcolormesh(x1, x2, y_hat, cmap=cm_light) # 等高线图 # plt.contourf(xx, yy, Z, alpha=0.4) # 样本的显示 plt.scatter(x_data[:, 0], x_data[:, 1], s=30, c=y_data, edgecolors='k', cmap=cm_dark) plt.savefig(title+".png") plt.show() plt.close()
def animation(self, save_animation=True): """Function to create animation of evolution u matrix using the saved frames. Argumetns: ----------------- save_animation: bool - If true, save animation to gif file """ fig = plab.figure() plt.rcParams['figure.figsize'] = (10, 10) plab.pcolormesh(self.u_mat, cmap=plab.cm.RdBu) def animate(i): """Plotting function for animation""" if i < self.save_u_mat.shape[0]: plab.pcolormesh(np.squeeze(self.save_u_mat[i, :, :]), cmap=plab.cm.RdBu) anim = animation.FuncAnimation(fig, animate, frames=range(self.save_u_mat.shape[0]), blit=False) writer = PillowWriter(fps=20) filename_an = f'u_matrix_F={self.F}_k={self.k}.gif' plab.xlabel('u_1') plab.ylabel('u_2') plab.title( f'u matrix, F={self.F}, k={self.k} after {self.n_times} iterations.' ) if save_animation: anim.save(filename_an, writer=writer)
def get_mask(eta, x, y, mwl, plot_mask=False): yy, xx = np.meshgrid(y, x) mask = xx * 0 mask_inv = xx * 0 + 1 mx = len(x) my = len(y) tol = 1.3E-4 index_max = eta[:, 3 * my / 4].argmax() for k in reversed(xrange(index_max)): aux = eta - mwl if (aux[k, 3 * my / 4] >= tol): mask[k, :] = 1 mask_inv[k, :] = 0 else: break for k in xrange(index_max, mx): aux = eta - mwl if (aux[k, 3 * my / 4] >= tol): mask[k, :] = 1 mask_inv[k, :] = 0 else: break if plot_mask: pl.pcolormesh(xx, yy, mask_inv) pl.colorbar() pl.savefig('mask.png') return mask, mask_inv
def plot_spectogram(f, t, Sxx, file_path): plt.clf() #plt.imshow(np.sqrt(features.T) , origin='lower' ,cmap='bone_r') plt.pcolormesh(t, f, Sxx, cmap='bone_r') plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.savefig(file_path)
def boxed_print(v): if (len(v.shape) == 1): u = v.reshape((v.shape[0], 1)) else: u = v plt.figure(dpi=100, figsize=(u.shape)) vm = np.max(np.abs(np.real(u))) plt.pcolormesh(u.real.T, zorder=2, edgecolor='k', cmap='bwr', vmin=-vm, vmax=vm, linewidth=2.0) plt.gca().set_aspect('equal') plt.axis('off') for lx in range(u.shape[0]): for ly in range(u.shape[1]): if (np.isclose(u[lx, ly], np.rint(u[lx, ly]))): plt.text(0.5 + lx, 0.5 + ly, '$' + str(np.rint(u[lx, ly])) + '$', horizontalalignment='center', verticalalignment='center', fontsize=14) else: plt.text(0.5 + lx, 0.5 + ly, '$' + "{:10.2f}".format(u[lx, ly]) + '$', horizontalalignment='center', verticalalignment='center', fontsize=14) plt.tight_layout()
def plot_p(frame): sol=Solution(frame,file_format='petsc',read_aux=False,path='./_output/_p/',file_prefix='claw_p') x=sol.state.grid.x.centers; y=sol.state.grid.y.centers mx=len(x); my=len(y) mp=sol.state.num_eqn yy,xx = np.meshgrid(y,x) p=sol.state.q[0,:,:] fig = pl.figure(figsize=(8, 3.5)) #pl.title("t= "+str(sol.state.t),fontsize=20) pl.xticks(size=20); pl.yticks(size=20) pl.xlabel('x',fontsize=20); pl.ylabel('y',fontsize=20) #pl.pcolormesh(xx,yy,p_subxy,cmap=cm.OrRd) pl.pcolormesh(xx,yy,p,cmap='RdBu_r') pl.autoscale(tight=True) cb = pl.colorbar(ticks=[0.5,1,1.5,2]); #pl.clim(ticks=[0.5,1,1.5,2]) imaxes = pl.gca(); pl.axes(cb.ax) pl.yticks(fontsize=20); pl.axes(imaxes) #pl.xticks(fontsize=20); pl.axes(imaxes) #pl.axis('equal') pl.axis('tight') fig.tight_layout() pl.savefig('./_plots_to_paper/sound-speed_FV_t'+str(frame)+'_pcolor.png') pl.close()
def decision_boundary(self, proba=False, limits=None, pts_to_plot=None): """Define the decision boundary of the trained classifier. It should be a piecewise quadratic boundary. Args: limits (list) : limits to plot for each feature """ if self.fitted and self.nb_feats_ == 2: if limits is None: # Find plausible intervals based on the fitted model (3 stds around the mean -> 99.7%) sd = np.sqrt(self.sigma_) limits = [ np.min(self.theta_ - 3 * sd, axis=0), np.max(self.theta_ + 3 * sd, axis=0) ] nb_grid_pts = 500 x = np.linspace(limits[0][0], limits[1][0], nb_grid_pts) y = np.linspace(limits[0][1], limits[1][1], nb_grid_pts) xv, yv = np.meshgrid(x, y) # Get decision for each point if proba: y_hat = self.predict_proba( np.concatenate((xv.reshape(-1, 1), yv.reshape(-1, 1)), 1))[:, 1] cMap = 'YlOrRd' colorbar_label = 'P(class=0)' colorbar_ticks = np.arange(0, 1, 10) else: y_hat = self.predict( np.concatenate((xv.reshape(-1, 1), yv.reshape(-1, 1)), 1)) cMap = self._discrete_cmap(self.nb_classes_, 'cubehelix') colorbar_label = 'Class' colorbar_ticks = [] z = y_hat.reshape(nb_grid_pts, nb_grid_pts) # Plot decision function plt.figure() plt.subplot(1, 1, 1) plt.pcolormesh(x, y, z, cmap=cMap, vmin=np.min(z), vmax=np.max(z)) plt.title('Decision surface') plt.axis([x.min(), x.max(), y.min(), y.max()]) cbar = plt.colorbar() cbar.ax.set_ylabel(colorbar_label) # cbar.ax.get_yaxis().set_ticks(colorbar_ticks) plt.xlabel('Feature 1') plt.ylabel('Feature 2') if pts_to_plot is not None: plt.scatter(pts_to_plot[:, 0], pts_to_plot[:, 1]) else: print( 'The model should only use 2 features for the decision boundary to be plotted.' )
def plot(self, T=None, figure=1): """ """ if T==None: T = numpy.array(range(len(self.signal)))*self.dt Xp, Yp = numpy.meshgrid(T, self.frequencies) pylab.figure(figure) pylab.clf() pylab.subplot(211) pylab.plot(T, self.signal, 'k', linewidth=2) pylab.ylabel('signal') pylab.subplot(212) pylab.pcolormesh(Xp, Yp, numpy.abs(self.cwt)**2) pylab.xlabel('time') pylab.ylabel('frequency') #pylab.yscale('log') #pylab.subplot(313) #pylab.pcolormesh(Xp, Yp, numpy.angle(self.cwt)) #pylab.xlabel('time') #pylab.ylabel('frequency') #pylab.yscale('log') return
def myplot(img, fileName=None, clim=None): plt.axis('equal') plt.pcolormesh(img, cmap='gray') plt.colorbar() if fileName != None: plt.gcf().savefig(fileName, dpi=300) if clim != None: plt.clim(clim)
def plot(self, eta): import matplotlib # set matplotlib to work over X-forwarding matplotlib.use('Agg') from matplotlib import pylab as plt plt.figure() plt.pcolormesh(eta) plt.draw() plt.savefig('./debug.png', dpi=320)
def plot_embedding(spec, path): spec = spec.transpose(1, 0) # (seq_len, feature_dim) -> (feature_dim, seq_len) plt.gcf().clear() plt.figure(figsize=(12, 3)) plt.pcolormesh(spec, norm=SymLogNorm(linthresh=1e-3)) plt.colorbar() plt.tight_layout() plt.savefig(path, dpi=300, format="png") plt.close()
def main(): sound = AudioSegment.from_file(INPUT_PATH) samples = np.array(sound.get_array_of_samples()) frequencies, times, spectrogram = scipy.signal.spectrogram(samples, nperseg=2048) plt.pcolormesh(times, frequencies, spectrogram, cmap='binary') plt.savefig(OUTPUT_PATH) plt.show() print(OUTPUT_PATH)
def compare(X, Y): """ Plots a colormesh for each matrix and returns True if they are equal and false otherwise """ plt.pcolormesh(X) plt.show() plt.pcolormesh(Y) plt.show() return np.allclose(X, Y)
def plot_veg(isveg, path): """ saves a png of the vegetation field """ fig = plt.figure(figsize=(4, 5)) plt.pcolormesh(isveg[:-1, :-1].T, cmap='Greens') name = path.split('/')[-1] plt.savefig('{0}/veg_{1}.png'.format(path, name), bbox_inches='tight') plt.close(fig)
def notestPropagatePlane(self): r = np.mgrid[0:10:1.1,1:10:0.8] u = np.ones(r.shape[1:], dtype=complex) grad_uz = np.ones(r.shape[1:], dtype=complex) u, r = propagateWaveFunctionPlane( u=u, grad_uz=grad_uz, variables=r, kappa=2, ) from matplotlib import pylab as plt plt.pcolormesh(u.real)
def plot_q(frame,file_prefix='claw',path='./_output/',plot_pcolor=True,plot_slices=True,slices_xlimits=None): import sys sys.path.append('.') import sw_eqns sol=Solution(frame,file_format='petsc',read_aux=False,path=path,file_prefix=file_prefix) x=sol.state.grid.x.centers; y=sol.state.grid.y.centers mx=len(x); my=len(y) h=sol.state.q[0,:,:] b=sw_eqns.bathymetry(x,y)[0,:,:] eta=h+b yy,xx = np.meshgrid(y,x) if frame < 10: str_frame = "000"+str(frame) elif frame < 100: str_frame = "00"+str(frame) elif frame < 1000: str_frame = "0"+str(frame) else: str_frame = str(frame) if plot_pcolor: pl.pcolormesh(xx,yy,eta) pl.title("t= "+str(sol.state.t),fontsize=20) pl.xlabel('x',fontsize=20); pl.ylabel('y',fontsize=20) pl.xticks(size=20); pl.yticks(size=20) cb = pl.colorbar(); #pl.clim(colorbar_min,colorbar_max); imaxes = pl.gca(); pl.axes(cb.ax) pl.yticks(fontsize=20); pl.axes(imaxes) pl.axis([np.min(x),np.max(x),np.min(y),np.max(y)]) pl.savefig('./_plots/eta_'+str_frame+'.png') #pl.show() pl.close() if plot_slices: pl.figure(figsize=(8,3)) pl.plot(x,eta[:,3*my/4.],'-r',lw=1) pl.plot(x,eta[:,my/4.],'--b',lw=1) #pl.plot(x,b[:,my/4],'-k',lw=1) #pl.plot(x,b[:,3*my/4],'--k',lw=1) pl.title("t= "+str(sol.state.t),fontsize=20) pl.xlabel('x',fontsize=20) pl.ylabel('Surface',fontsize=20) pl.xticks(size=20); pl.yticks(size=20) #pl.ylim([0.9998,1.0002]) pl.xlim([0.0,20]) if slices_xlimits is not None: pl.axis([slices_xlimits[0],slices_xlimits[1],np.min(p),np.max(p)]) pl.savefig('./_plots/eta_'+str_frame+'_slices.png') pl.close()
def plotting(xmin,xmax,ymin,ymax,omega,l,m): x = np.linspace(xmin,xmax,256) y = np.linspace(ymin,ymax,256) z = np.zeros([len(x),len(y)]) for i,xx in enumerate(x): for j, yy in enumerate(y): z[i,j] = psi(xx,yy,omega,l,m) plt.pcolormesh(x, y, z/np.max(z)) plt.title('pcolor') plt.axis([x.min(), x.max(), y.min(), y.max()]) plt.colorbar() plt.show() return
def plot_p(frame,file_prefix='claw_p',path='./_output/_p',plot_slices=True,plot_pcolor=True,slices_limits=None,xshift=0.0,name='',title=True): sol_ref=Solution(frame+450,file_format='petsc',read_aux=False,path='_output/reference/_p/',file_prefix=file_prefix) sol=Solution(frame,file_format='petsc',read_aux=False,path=path,file_prefix=file_prefix) x=sol.state.grid.x.centers; y=sol.state.grid.y.centers x=x+xshift mx=len(x); my=len(y) yy,xx = np.meshgrid(y,x) if frame < 10: str_frame = "00"+str(frame) elif frame < 100: str_frame = "0"+str(frame) else: str_frame = str(frame) p=sol.state.q[0,:,:] p_ref=sol_ref.state.q[0,:,:] if plot_pcolor: pl.pcolormesh(xx,yy,p,cmap=cm.OrRd) pl.title("t= "+str(sol.state.t),fontsize=20) pl.xlabel('x',fontsize=20); pl.ylabel('y',fontsize=20) pl.xticks(size=20); pl.yticks(size=20) cb = pl.colorbar(); #pl.clim(colorbar_min,colorbar_max); imaxes = pl.gca(); pl.axes(cb.ax) pl.yticks(fontsize=20); pl.axes(imaxes) pl.axis([np.min(x),np.max(x),np.min(y),np.max(y)]) #pl.axis([0.25,60.25,0.25,60.25]) pl.savefig('./_plots_to_paper/co-interaction_'+str_frame+name+'.png') #pl.show() pl.close() if plot_slices: pl.figure(figsize=(8,3)) pl.gcf().subplots_adjust(left=0.10) # plot reference pl.plot(x,p_ref[:,my/4.],'--b',linewidth=1) pl.plot(x,p_ref[:,3*my/4.],'--r',linewidth=1) # plot solution of interaction pl.plot(x,p[:,3*my/4.],'-r',linewidth=2) pl.plot(x,p[:,my/4.],'-b',linewidth=2) pl.title("t= "+str(sol.state.t),fontsize=20) pl.xlabel('x',fontsize=20) if title: pl.ylabel('Stress',fontsize=20) pl.xticks(size=20); pl.yticks(size=20) if slices_limits is not None: pl.axis([slices_limits[0]+xshift,slices_limits[1]+xshift,slices_limits[2],slices_limits[3]]) pl.savefig('./_plots_to_paper/co-interaction_'+str_frame+name+'.eps') pl.close()
def _plot_field_pcolormesh(X, Y, R, ax, type, units, colorscale, geodata): R = R.copy() # Get colormap and color levels cmap, norm, clevs, clevsStr = get_colormap(type, units, colorscale) # Plot precipitation field # transparent where no precipitation or the probability is zero if type == "intensity": if units == 'mm/h': R[R < 0.1] = np.nan elif units == 'dBZ': R[R < 10] = np.nan else: R[R < 1e-3] = np.nan vmin, vmax = [None, None] if type == "intensity" else [0.0, 1.0] im = plt.pcolormesh(X, Y, R, cmap=cmap, norm=norm, vmin=vmin, vmax=vmax, zorder=10) return im
def createZoneImg(self, obj): mat = obj xt, yt = self.model.Aquifere.getXYticks() img = pl.pcolormesh(xt, yt, mat) # ,norm='Normalize') obj = GraphicObject("ZoneImg", img, False, None) self.addGraphicObject(obj) # ne pas stocker zoneimage self.redraw()
def plot_value_heatmap(): assert self.robot.kinematics == 'holonomic' for agent in [self.states[global_step][0] ] + self.states[global_step][1]: print( ('{:.4f}, ' * 6 + '{:.4f}').format(agent.px, agent.py, agent.gx, agent.gy, agent.vx, agent.vy, agent.theta)) # when any key is pressed draw the action value plot fig, axis = plt.subplots() speeds = [0] + self.robot.policy.speeds rotations = self.robot.policy.rotations + [np.pi * 2] r, th = np.meshgrid(speeds, rotations) z = np.array(self.action_values[global_step % len(self.states)][1:]) z = (z - np.min(z)) / (np.max(z) - np.min(z)) z = np.reshape(z, (16, 5)) polar = plt.subplot(projection="polar") polar.tick_params(labelsize=16) mesh = plt.pcolormesh(th, r, z, vmin=0, vmax=1) plt.plot(rotations, r, color='k', ls='none') plt.grid() cbaxes = fig.add_axes([0.85, 0.1, 0.03, 0.8]) cbar = plt.colorbar(mesh, cax=cbaxes) cbar.ax.tick_params(labelsize=16) plt.show()
def createZoneImg(self, obj): mat = obj xt, yt = self.model.Aquifere.getXYticks() img = pl.pcolormesh(xt, yt, mat) #,norm='Normalize') obj = GraphicObject('ZoneImg', img, False, None) self.addGraphicObject(obj) # ne pas stocker zoneimage self.redraw()
def plot_generated_batch(X_full, X_sketch, generator_model, batch_size, image_data_format, suffix): # Generate images X_gen = generator_model.predict(X_sketch) X_sketch = inverse_normalization(X_sketch) X_full = inverse_normalization(X_full) X_gen = inverse_normalization(X_gen) #np.save("../../figures/current_batch_%s.png" % suffix) Xs = X_sketch[:8] Xg = X_gen[:8] Xr = X_full[:8] np.save("../../figures/current_batch_{}_{}.npy".format('noisy', suffix), X_sketch) np.save("../../figures/current_batch_{}_{}.npy".format('gen', suffix), X_gen) np.save("../../figures/current_batch_{}_{}.npy".format('clean', suffix), X_full) if image_data_format == "channels_last": X = np.concatenate((Xs, Xg, Xr), axis=0) list_rows = [] for i in range(int(X.shape[0] // 4)): Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=1) list_rows.append(Xr) Xr = np.concatenate(list_rows, axis=0) if image_data_format == "channels_first": X = np.concatenate((Xs, Xg, Xr), axis=0) list_rows = [] for i in range(int(X.shape[0] // 4)): Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=2) list_rows.append(Xr) Xr = np.concatenate(list_rows, axis=1) Xr = Xr.transpose(1,2,0) if Xr.shape[-1] == 1: #plt.imshow(Xr[:, :, 0], cmap="gray") plt.pcolormesh(Xr[:, :, 0], cmap="gnuplot2") else: print "NOT IN PCOLORMESH" plt.imshow(Xr) plt.axis("off") plt.savefig("../../figures/current_batch_%s.png" % suffix) plt.clf() plt.close()
def plot_p(frame,zlim=[0.,1.]): sol_ref=Solution(frame+450,file_format='petsc',read_aux=False,path='_output/reference/_p/',file_prefix='claw_p') sol=Solution(frame,file_format='petsc',read_aux=False,path='./_output/_p/',file_prefix='claw_p') x=sol.state.grid.x.centers; y=sol.state.grid.y.centers mx=len(x); my=len(y) yy,xx = np.meshgrid(y,x) if frame < 10: str_frame = "00"+str(frame) elif frame < 100: str_frame = "0"+str(frame) else: str_frame = str(frame) p=sol.state.q[0,:,:] p_ref=sol_ref.state.q[0,:,:] # plot pcolor pl.figure(figsize=(8,3)) pl.pcolormesh(xx,yy,p,cmap=cm.OrRd) pl.title("t= "+str(sol.state.t),fontsize=20) pl.xticks(size=20); pl.yticks(size=20) cb = pl.colorbar(); pl.clim(zlim[0]-0.05*zlim[1],1.05*zlim[1]); imaxes = pl.gca(); pl.axes(cb.ax) pl.yticks(fontsize=20); pl.axes(imaxes) pl.axis([np.min(x),np.max(x),np.min(y),np.max(y)]) pl.savefig('./_plots_to_animation/pcolor/co-interaction_'+str_frame+'.png') pl.close() # Plot slices pl.figure(figsize=(8,3)) pl.gcf().subplots_adjust(left=0.10) # plot reference pl.plot(x,p_ref[:,3*my/4.],'--r',linewidth=1) pl.plot(x,p_ref[:,my/4.],'--b',linewidth=1) # plot solution of interaction pl.plot(x,p[:,3*my/4.],'-r',linewidth=2) pl.plot(x,p[:,my/4.],'-b',linewidth=2) pl.title("t= "+str(sol.state.t),fontsize=20) #pl.xlabel('x',fontsize=20) #pl.ylabel('Stress',fontsize=20) pl.xticks(size=20); pl.yticks(size=20) pl.ylim(zlim[0]-0.05*zlim[1],1.05*zlim[1]); pl.savefig('./_plots_to_animation/slices/co-interaction_'+str_frame+'_slices.eps') pl.close()
def initPlot(plotName, x1, x2): plt.figure(plotName) # Окрашивание допустимого множества D (желтый цвет) plt.pcolormesh(x1, x2, (g1([x1, x2]) <= 0) & (g2([x1, x2]) <= 0) & (g3([x1, x2]) <= 0), alpha=0.1) # Линии уровня целевой функции (последний аргумент - количество линий) contours = plt.contour(x1, x2, f([x1, x2]), 30) # Значение уровня на линиях (последний аргумент - размер шрифта) plt.clabel(contours, inline=True, fontsize=8) # Ограничения(предпоследний аргумент - активность ограничения, т.е. g1(x) = 0) plt.contour(x1, x2, g1([x1, x2]), (0,), colors='g') plt.contour(x1, x2, g2([x1, x2]), (0,), colors='r') plt.contour(x1, x2, g3([x1, x2]), (0,), colors='y') return plt
def plot_field(self, x, y, u=None, v=None, F=None, contour=False, outdir=None, plot='quiver', figname='_field', format='eps'): outdir = self.set_dir(outdir) p = 64 if F is None: F = self.calc_F(u, v) plt.close('all') plt.figure() #fig, axes = plt.subplots(nrows=1) if contour: plt.hold(True) plt.contourf(x, y, F) if plot == 'quiver': plt.quiver(x[::p], y[::p], u[::p], v[::p], scale=0.1) if plot == 'pcolor': plt.pcolormesh(x[::4], y[::4], F[::4], cmap=plt.cm.Pastel1) plt.colorbar() if plot == 'stream': speed = F[::16] plt.streamplot(x[::16], y[::16], u[::16], v[::16], density=(1, 1), color='k') plt.xlabel('$x$ (a.u.)') plt.ylabel('$y$ (a.u.)') plt.savefig(os.path.join(outdir, figname + '.' + format), format=format, dpi=320, bbox_inches='tight') plt.close()
def lola_image(self, save=False, name='BaseLola.png'): ''' Draw the topography of the region of interest Args: save (Optional[bool]): Weither or not to save the image. Defaults to False. name (Optional[str]): Absolut path to save the resulting image. Default to 'BaseLola.png' in the working directory. Returns: An image correponding to the region tography. Realized from the data taken by the LOLA instrument on board of LRO. Note: Nice to use in a jupyter notebook with ``%matplotib inline`` activated. Feel free to modify this method to plot exactly what you need. ''' fig = plt.figure(figsize=(10, 8)) lon_m, lon_M, lat_m, lat_M = self.lambert_window( self.size_window, self.lat0, self.lon0) #m = Basemap(llcrnrlon=lon_m, llcrnrlat=lat_m, urcrnrlon=lon_M, urcrnrlat=lat_M, # resolution='i', projection='laea', rsphere=1734400, lat_0=self.lat0, lon_0=self.lon0) ax1 = fig.add_subplot(111, projection=self.laea) Xl, Yl, Zl = self.get_arrays('Lola') CS = plt.pcolormesh(Xl, Yl, Zl, transform=self.laea, cmap='gist_earth', alpha=0.5, ax=ax1, zorder=1) # plt.contour(Xl, Yl, Zl, 20, transform=laea, colors='black', alpha=1.0, zorder=2) ax1.scatter(self.lon0, self.lat0, transform=self.laea, s=200, marker='v', zorder=2) #self._add_scale(m, ax1) self._add_colorbar(CS, ax1, 'Topography') if save == True: fig.savefig(name, rasterized=True, dpi=50, bbox_inches='tight', pad_inches=0.1)
def plot_decision_regions_2class(model, dataset): cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#00AAFF']) cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#00AAFF']) X = dataset.x.numpy() y = dataset.y.numpy() h = .02 x_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1 y_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) XX = torch.Tensor(np.c_[xx.ravel(), yy.ravel()]) yhat = np.logical_not((model(XX)[:, 0] > 0.5).numpy()).reshape(xx.shape) plt.pcolormesh(xx, yy, yhat, cmap=cmap_light) plt.plot(X[y[:, 0] == 0, 0], X[y[:, 0] == 0, 1], 'o', label='y=0') plt.plot(X[y[:, 0] == 1, 0], X[y[:, 0] == 1, 1], 'ro', label='y=1') plt.title("decision region") plt.legend()
def plot_p(frame, slices_xlimits=None, init_cond=False): sol = Solution(frame, file_format="petsc", read_aux=False, path="./_output/_p/", file_prefix="claw_p") x = sol.state.grid.x.centers y = sol.state.grid.y.centers mx = len(x) my = len(y) mp = sol.state.num_eqn yy, xx = np.meshgrid(y, x) if frame < 10: str_frame = "00" + str(frame) elif frame < 100: str_frame = "0" + str(frame) else: str_frame = str(frame) p = sol.state.q[0, :, :] pl.pcolormesh(xx, yy, p, cmap="RdBu_r") pl.title("t= " + str(sol.state.t), fontsize=20) pl.xlabel("x", fontsize=20) pl.ylabel("y", fontsize=20) pl.xticks(size=20) pl.yticks(size=20) cb = pl.colorbar() pl.clim([-0.25, 0.25]) # pl.clim(colorbar_min,colorbar_max); imaxes = pl.gca() pl.axes(cb.ax) pl.yticks(fontsize=20) pl.axes(imaxes) pl.axis("equal") pl.axis([np.min(x), np.max(x), np.min(y), np.max(y)]) pl.savefig("./_plots_to_paper/cz-dispersion_macro-iso_low-freq_pcolor_frame" + str_frame + ".png") pl.close() # write slices fx = open("cz-dispersion_macro-iso_low-freq_layered_xslice.txt", "w") fx.writelines(str(xc) + " " + str(p[i, 0]) + "\n" for i, xc in enumerate(x)) fx.close() fy = open("cz-dispersion_macro-iso_low-freq_layered_yslice.txt", "w") fy.writelines(str(yc) + " " + str(p[0, i]) + "\n" for i, yc in enumerate(y)) fy.close()
def plotField(field): from matplotlib import pylab latIndex, lonIndex = 0, 1 iBegLat = field.grid.lower_bounds[ESMF.StaggerLoc.CORNER][latIndex] iEndLat = field.grid.upper_bounds[ESMF.StaggerLoc.CORNER][latIndex] iBegLon = field.grid.lower_bounds[ESMF.StaggerLoc.CORNER][lonIndex] iEndLon = field.grid.upper_bounds[ESMF.StaggerLoc.CORNER][lonIndex] lats = field.grid.get_coords(latIndex, ESMF.StaggerLoc.CORNER)[iBegLat:iEndLat, iBegLon:iEndLon] lons = field.grid.get_coords(lonIndex, ESMF.StaggerLoc.CORNER)[iBegLat:iEndLat, iBegLon:iEndLon] pylab.pcolormesh(lats, lons, field.data[0, ...]) pylab.show()
def image(X, Y, Z, origin='lower', interpolation='nearest', vrange=None, extent=None, inaxis=None, cmap=None, addcolorbar=True, clabel=None): '''A nice wrapper around imshow. vrange = (vmin, vmax) -- Z value range cmap = colormap ''' # calculate the spatial location and vertical / value range XX, YY = _getmesh(X, Y, Z) extent = _getextent(extent, X, Y) vrange = _getvrange(vrange, XX, YY, Z, inaxis=inaxis) # get a nice color map with nans set to be cmap = _getcmap(cmap) # Make the masked array hiding the nans # MZ = np.ma.array(Z, mask=(np.isfinite(Z) is False) ) MZ = np.ma.array(Z, mask=np.isnan(Z)) out = [] # with warnings.catch_warnings(): # warnings.simplefilter("ignore") # im = pylab.imshow(MZ, origin=origin, extent=extent, # vmin=vrange[0], vmax=vrange[1], # cmap=cmap, interpolation='nearest') im = pylab.pcolormesh(XX, YY, MZ, vmin=vrange[0], vmax=vrange[1], cmap=cmap) # box(y=[0,0.2], percent=True, color='r') # pylab.plot(np.medians(XX,axis=0), np.median(MZ,axis=0) # if addmedians: # med = np.median(MZ,axis=0) # box(y=[0,0.1], percent=True) # setup a colorbar and return it out for modifications if addcolorbar: cb = colorbar(im, clabel=clabel) return im, cb return im
def plotting(xmin,xmax,ymin,ymax,omega,l,m): x = np.linspace(xmin,xmax,256) y = np.linspace(ymin,ymax,256) z = np.zeros([len(x),len(y)]) for i,xx in enumerate(x): for j, yy in enumerate(y): z[i,j] = psi(xx,yy,omega,l,m) if [l,m] == [0,0]: r_meas = 14.4e-6/2 else: r_meas = 14.3e-6/2 fig = plt.figure() plt.pcolormesh(x, y, z/np.max(z)) plt.title('$TEM$'+str(l)+str(m)+ ', radius:'+ str(round(omega*1e6,4)) +'um, err:'+ str(round(100*(r_meas-omega)/r_meas,4)) + '%') plt.axis([xmin, xmax, ymin, ymax]) plt.xlabel(r'$x(m)$') plt.ylabel(r'$y(m)$') plt.colorbar() plt.savefig('mode'+str(l)+str(m)+'.png',bbox_inches='tight') plt.close(fig) return
def train_2d(X, Y, labels, fs, plot=True): X = X[:, fs] clf = skl.LogisticRegression(C=10) clf.fit(X, Y) # clf = ske.RandomForestClassifier() if plot: h = 0.1 x_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1 y_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.figure(1, figsize=(4, 3)) plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired) plt.plot(X[Y==1, 0], X[Y==1, 1], 'o', markerfacecolor=plt.cm.Paired(0.5), markersize=10) plt.plot(X[Y==0, 0], X[Y==0, 1], 'o', markerfacecolor=plt.cm.Paired(0.1), markersize=10) # labels = ['a' + str(i) for i in range(X.shape[0])] for label, x, y in zip(labels, X[:, 0], X[:, 1]): plt.annotate(label, xy=(x, y), xytext=(-10, 10), textcoords='offset points', ha='right', va='bottom', fontsize=6, bbox={'boxstyle': 'round,pad=0.5', 'fc': '#DDDDDD', 'alpha': 0.3}, arrowprops={'arrowstyle': '->', 'connectionstyle': 'arc3,rad=0'}) plt.xlabel(PROP_NAMES[fs[0]]) plt.ylabel(PROP_NAMES[fs[1]]) plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.show() return clf.score(X, Y)
def plot_p(frame,slices_xlimits=None,init_cond=False): sol=Solution(frame,file_format='petsc',read_aux=False,path='./_output/_p/',file_prefix='claw_p') x=sol.state.grid.x.centers; y=sol.state.grid.y.centers mx=len(x); my=len(y) mp=sol.state.num_eqn yy,xx = np.meshgrid(y,x) if frame < 10: str_frame = "00"+str(frame) elif frame < 100: str_frame = "0"+str(frame) else: str_frame = str(frame) p=sol.state.q[0,:,:] pl.pcolormesh(xx,yy,p,cmap='RdBu_r') pl.title("t= "+str(sol.state.t),fontsize=20) pl.xlabel('x',fontsize=20); pl.ylabel('y',fontsize=20) pl.xticks(size=20); pl.yticks(size=20) pl.clim([-0.25,0.25]) cb = pl.colorbar(); #pl.clim(colorbar_min,colorbar_max); imaxes = pl.gca(); pl.axes(cb.ax) pl.yticks(fontsize=20); pl.axes(imaxes) pl.axis('equal') pl.axis([np.min(x),np.max(x),np.min(y),np.max(y)]) pl.savefig('./_plots_to_paper/cz-dispersion_grl_pcolor_frame'+str_frame+'.png') pl.close() # write slices fx=open('cz-dispersion_grl_xslice.txt','w') fx.writelines(str(xc)+" "+str(p[i,0])+"\n" for i,xc in enumerate(x)) fx.close() fy=open('cz-dispersion_grl_yslice.txt','w') fy.writelines(str(yc)+" "+str(p[0,i])+"\n" for i,yc in enumerate(y)) fy.close()
def symimage(*args,**kwargs): I = plp.Image() fig = plt.figure() Data = args[0] DataMHD = args[1] var = 517.32*Data.__getattribute__(args[2]) if kwargs.get('ysym',False) == True: ysymvar = 517.32*np.flipud(Data.__getattribute__(args[2])) x1 = Data.x1 x2 = Data.x2 plt.axis([-np.max(x1),np.max(x1),np.min(x2),np.max(x2)]) plt.pcolormesh(-x1[::-1],x2,ysymvar.T,vmin=kwargs.get('vmin',np.min(var)),vmax=kwargs.get('vmax',np.max(var))) plt.pcolormesh(x1,x2,var.T,vmin=kwargs.get('vmin',np.min(var)),vmax=kwargs.get('vmax',np.max(var))) plt.title(kwargs.get('title',"Title"),size=kwargs.get('size')) plt.xlabel(kwargs.get('label1',"Xlabel"),size=kwargs.get('size'),labelpad=6) plt.ylabel(kwargs.get('label2',"Ylabel"),size=kwargs.get('size'),labelpad=6) if kwargs.get('cbar',(False,''))[0] == True: plt.colorbar(orientation=kwargs.get('cbar')[1]) if kwargs.get('flines',(False,[3.0,6.0,10.0,15.0],[0.001,0.001,0.001,0.001]))[0]==True: x0arr = kwargs.get('flines')[1] y0arr = kwargs.get('flines')[2] for i in range(np.size(x0arr)): fl =I.field_line(Data.__getattribute__('b1'),Data.__getattribute__('b2'),Data.__getattribute__('x1'),Data.__getattribute__('x2'),Data.__getattribute__('dx1'),Data.__getattribute__('dx2'),x0arr[i],y0arr[i]) flmhd =I.field_line(DataMHD.__getattribute__('b1'),DataMHD.__getattribute__('b2'),DataMHD.__getattribute__('x1'),DataMHD.__getattribute__('x2'),DataMHD.__getattribute__('dx1'),DataMHD.__getattribute__('dx2'),x0arr[i],y0arr[i]) Qx= fl.get('qx') Qy= fl.get('qy') Qxmhd = flmhd.get('qx') Qymhd = flmhd.get('qy') plt.plot(Qx,Qy,color=kwargs.get('colors','r'),ls=kwargs.get('ls','-'),lw=kwargs.get('lw',2.0)) plt.plot(-Qx,Qy,color=kwargs.get('colors','r'),ls=kwargs.get('ls','-'),lw=kwargs.get('lw',2.0)) plt.plot(Qxmhd,Qymhd,color=kwargs.get('colors','w'),ls=kwargs.get('ls','--'),lw=kwargs.get('lw',2.0)) plt.plot(-Qxmhd,Qymhd,color=kwargs.get('colors','w'),ls=kwargs.get('ls','--'),lw=kwargs.get('lw',2.0))
def plotH(): '''A function that plots the H values for use in the Area Scattering Phase Function, and saves the H values to disk. The H function plotted is not the final one as it has been trandformed into a LUT. See H_LUT above. ''' x = np.linspace(0., np.pi, 500) # view or sun zenith angles y = x.copy() # leaf normal zenith angles xx, yy = np.meshgrid(x,y) h = np.zeros_like(xx) for i in range(len(x)): for j in range(len(y)): h[i,j] = H(xx[i,j], yy[i,j]) #pdb.set_trace() np.savetxt('view_sun.csv', xx, delimiter=',') np.savetxt('leaf.csv', yy, delimiter=',') np.savetxt('H_values.csv', h, delimiter=',') plt.pcolormesh(xx, yy, h) plt.axis([xx.max(),xx.min(),yy.max(),yy.min()]) plt.title('H Function Values') plt.xlabel('Zenith angle view/sun (radians)') plt.ylabel('Zenith angle leaf normal (radians)') plt.colorbar() plt.show()
def image(X,Y,Z, origin='lower', interpolation='nearest', vrange=None, extent=None, inaxis=None, cmap=None, addcolorbar=True, clabel=None): '''A nice wrapper around imshow. vrange = (vmin, vmax) -- Z value range cmap = colormap ''' # calculate the spatial location and vertical / value range XX, YY = _getmesh(X,Y,Z) extent = _getextent(extent, X, Y) vrange = _getvrange(vrange, XX,YY,Z, inaxis=inaxis) # get a nice color map with nans set to be cmap = _getcmap(cmap) # Make the masked array hiding the nans # MZ = np.ma.array(Z, mask=(np.isfinite(Z) is False) ) MZ = np.ma.array(Z, mask=np.isnan(Z)) out = [] # with warnings.catch_warnings(): # warnings.simplefilter("ignore") # im = pylab.imshow(MZ, origin=origin, extent=extent, # vmin=vrange[0], vmax=vrange[1], # cmap=cmap, interpolation='nearest') im = pylab.pcolormesh(XX,YY, MZ, vmin=vrange[0], vmax=vrange[1], cmap=cmap) # box(y=[0,0.2], percent=True, color='r') # pylab.plot(np.medians(XX,axis=0), np.median(MZ,axis=0) # if addmedians: # med = np.median(MZ,axis=0) # box(y=[0,0.1], percent=True) # setup a colorbar and return it out for modifications if addcolorbar: cb = colorbar(im, clabel=clabel) return im, cb return im
#!/usr/bin/env python from scipy.spatial import KDTree, Voronoi, voronoi_plot_2d import matplotlib.pylab as pl import numpy as np data = np.random.rand(25, 2) tree = KDTree(data) vor = Voronoi(data) x = np.linspace(0, 1, 200) y = np.linspace(0, 1, 200) xx, yy = np.meshgrid(x, y) xy = np.c_[xx.ravel(), yy.ravel()] print('Using scipy.spatial.voronoi_plot_2d, wait...') voronoi_plot_2d(vor) pl.savefig('knnVoronoi_1.png') print('Using scipy.spatial.KDTree, wait a few seconds...') pl.figure() pl.plot(data[:, 0], data[:, 1], 'ko') pl.pcolormesh(x, y, tree.query(xy)[1].reshape(200, 200)) pl.savefig('knnVoronoi_2.png') pl.show()
plt.title(r"$|\tilde{I}(\tau,f_D)|$") #plt.ylabel(r"Lag $\tau$ (ms)") plt.xlabel(r"Doppler Frequency $f_D$ ") #plt.subplot(413) #bina=1 #binb=1 #a_num=dynamic.shape[0] #b_num=dynamic.shape[1] plt.figure(2) #a_vv = np.copy(dynamic.reshape(a_num//bina, bina, b_num//binb, binb)) #dynamic=np.mean(np.mean(a_vv,axis=3),axis=1) #fig.add_subplot(gs[0:2, :4]) x = np.linspace(0, 8, dynamic.shape[1], endpoint=True) y = np.linspace(0, 985, dynamic.shape[0], endpoint=True) x_ds, y_ds = np.meshgrid( x,y) im = plt.pcolormesh(x_ds, y_ds, dynamic, cmap=cm.Greys) #plt.ylim(0, 985) plt.colorbar() plt.title("Dynamic Spectrum I(f,t)") plt.ylabel("Time ") plt.xlabel("Frequency ") #fig.add_subplot(gs[2:4, 2:4]) #plt.imshow(np.log10(np.abs(corr)), aspect='auto', cmap=cm.Greys,interpolation='nearest', vmin=-2,origin='lower') #plt.colorbar() #plt.title("dynamic spectrum") #plt.ylabel("time") #plt.xlabel("frequency") #plt.subplot(414) #plt.imshow(a_view, aspect='auto', cmap=cm.Greys, interpolation='nearest', origin='lower') #plt.colorbar() #plt.title("rebined dynamic spectrum")
if isBasemap is True: m = Basemap(llcrnrlon = modelbox[0], \ llcrnrlat = modelbox[2], \ urcrnrlon = modelbox[1], \ urcrnrlat = modelbox[3], \ resolution = 'h', \ projection = proj, \ lon_0 = (modelbox[1]-modelbox[0])/2, \ lat_0 = (modelbox[3]-modelbox[2])/2) m.drawcoastlines() m.fillcontinents(color = '#FFE4B5', lake_color = 'aqua') m.drawmeridians(numpy.arange(int(modelbox[0]),int(modelbox[1])+0.1,(modelbox[1]-modelbox[0])/7.),labels = [0,0,0,2]) m.drawparallels(numpy.arange(int(modelbox[2]),int(modelbox[3])+0.1,(modelbox[3]-modelbox[2])/7.),labels = [2,0,0,0]) for coordfile in listfile: print(coordfile) data = rw_data.Sat_SWOT(file = coordfile) data.load_swath(SSH_model = []) nac = numpy.shape(data.lon)[1] data.lon[numpy.where(data.lon>180)] = data.lon[numpy.where(data.lon>180)]-360 if isBasemap is True: x,y = m(data.lon[:,:],data.lat[:,:]) else: x = data.lon ; y = data.lat norm = mpl.colors.Normalize(vmin = -0.1, vmax = 0.1) SSH = data.SSH_model SSH[SSH==0] = numpy.nan SSH = numpy.ma.array(SSH, mask = numpy.isnan(SSH)) plt.pcolormesh(x[:,:int(nac/2)],y[:,:int(nac/2)],SSH[:,:int(nac/2)]); plt.clim(-0.3,0.3) plt.pcolormesh(x[:,int(nac/2):],y[:,int(nac/2):],SSH[:,int(nac/2):]); plt.clim(-0.3,0.3) plt.colorbar() plt.title('SWOT like data for config ' +p.config) plt.savefig(p.config+'_swath_SSH_model.png')
import numpy as np import matplotlib.pylab as plt import h5py fl=h5py.File('test.h5'); k=fl['/fields/k'].value[0] u=fl['/fields/u'].value u=u['real']+1j*u['imag'] Nt=6800 vk=u[Nt,:,:] [xx,yy]=np.meshgrid(np.arange(-2*np.pi,2*np.pi,np.pi/100),np.arange(-2*np.pi,2*np.pi,np.pi/100)) vx=np.zeros(xx.shape,dtype=complex) vy=np.zeros(xx.shape,dtype=complex) for l in range(k.shape[1]): vx=vx+vk[0,l]*np.exp(1j*(k[0,l]*xx+k[1,l]*yy)) vy=vy+vk[1,l]*np.exp(1j*(k[0,l]*xx+k[1,l]*yy)) E=np.abs(vx)**2+np.abs(vy)**2 plt.figure(dpi=200) plt.pcolormesh(xx,yy,E,shading='gouraud',rasterized=True,vmin=0,vmax=5) plt.xlim(xmin=-6,xmax=6) plt.ylim(ymin=-6,ymax=6) plt.colorbar() plt.show() #plt.savefig('out0.png', bbox_inches='tight')
# print feats return feats entropies,probs=entropyFeats(tData) entropies=np.array(entropies) plt.figure() plt.plot(entropies) plt.title("Entropy for each feature") probs=pdf(tData) probs=np.array(probs).T pthold=0.1 plt.figure() ax1=plt.subplot(2,1,1) plt.pcolormesh(probs) plt.title("Probabilities for each data point") plt.grid(b=True, which='major', color='w', linestyle='-') plt.grid(b=True, which='minor', color='w', linestyle='-') plt.colorbar() plt.subplot(2,1,2,sharex=ax1) plt.pcolormesh(probs<=pthold) plt.grid(b=True, which='major', color='w', linestyle='-') plt.grid(b=True, which='minor', color='w', linestyle='-') plt.colorbar() plt.title("Probabilities for each data point > %.1f"%(pthold)) probsCount=np.sum(probs<=pthold,1) plt.figure() plt.plot(probsCount)
filegrid = p.indatadir + 'OREGON_grd.nc' fileswot = p.outdatadir + 'OREGON_swot292_c01_p024.nc' vmin = -0.06 vmax = 0.06 fig = plt.figure(figsize=(30,10)) tloc=0.11 tfont=24 data = rw_data.Sat_SWOT(file=fileswot) data.load_swath(timing_err=[], x_ac=[], x_al=[]) x_al, x_ac = numpy.meshgrid(data.x_al, data.x_ac) x_al = x_al - numpy.min(numpy.min(x_al)) SSH = data.timing_err stitle = 'Timing error along swath' nac = numpy.shape(data.lon)[1] SSH[abs(SSH) > 1000] = numpy.nan norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) SSH[SSH == 0] = numpy.nan SSH = numpy.ma.array(SSH, mask=numpy.isnan(SSH)) print(numpy.shape(x_al), numpy.shape(x_ac), numpy.shape(SSH)) col = plt.pcolormesh(x_al[(nac/2), :], x_ac[:int(nac/2), 0], numpy.transpose(SSH[:,:int(nac/2)]), norm=norm) col = plt.pcolormesh(x_al[(nac/2), :], x_ac[int(nac/2):, 0], numpy.transpose(SSH[:,int(nac/2):]), norm=norm) plt.xlabel('along track (km)') plt.ylabel('across track (km)') plt.colorbar() plt.title(stitle, y=-tloc, fontsize=tfont) #size[1]) plt.axis('tight') plt.savefig('Fig14.png')
# get grid settings. dx, dy = 1./np.float(nbins), bw/nchan x, y = np.mgrid[slice(0.,1.,dx),slice(freq-bw/2.,freq+bw/2.+dy,dy)] # get function sorted with grid settings. mean, sig = 0.5, 0.5 z = np.exp(-((x-mean)/(sig*y/freq/4.))**2)+np.exp(-((x-0.25)/(sig*y/freq/10.))**2) # add some noise, and remove last 'spare' channel. noise_mean, noise_sig = 0., 0.05 z = z + np.random.normal(noise_mean,noise_sig,size=(nbins,nchan+1)) z = z[:,:-1] # plot stuff in color! plb.subplot(2,1,1) plb.pcolormesh(x,y,z,vmin=z.min(),vmax=z.max()) plb.axis([x.min(),x.max(),y.min(),y.max()]) plb.ylabel('Original') plb.colorbar() #plb.show() # denoise. print 'Denoising...' #z_wt = pp.wavelet2D(z,ncycle=np.int(nbins),threshtype='soft') z_wt = pp.pca(z) # plot reconstructed data in color! diff = z-z_wt plb.subplot(2,1,2)
#cg = np.log10(np.power(np.abs(cj[:cj.shape[0]/2,:]),2)) #vmin = A.mean()-2.*A.std() #vmax = A.mean()+A.std() #print cg.shape,A.shape gs = plt.GridSpec(2, 4, wspace=0.4, hspace=0.4) fig = plt.figure(figsize=(6, 6)) fig.add_subplot(gs[:2, :2]) plt.figure(1) #plt.subplot(121) x = np.linspace(-25.4, +25.4, A.shape[1], endpoint=True) y = np.linspace(0, 128, A.shape[0], endpoint=True) x_ds, y_ds = np.meshgrid( x,y) A=np.where(A > 0, A, 0.0001) A=np.log10(np.power(A,2)) print y_ds.shape,x_ds.shape,A.shape plt.pcolormesh(x_ds,y_ds, A, cmap=cm.Greys,vmin=-1,vmax=3) #ax=plt.imshow(np.log10(np.power(A,2)), aspect='auto', cmap=cm.Greys, interpolation='nearest', vmin=-1, origin='lower') plt.colorbar() plt.ylim(0, 128) plt.xlim(-25.4,25.4) plt.ylabel(r"Lag $\tau$ ($\mu$s)") plt.title(r"$|\tilde{E}(\tau,f_D)|$") plt.xlabel(r"Doppler Frequency $f_D$ (mHz)") #plt.subplot(122) fig.add_subplot(gs[:2, 2:4]) bina=1 binb=1 a_num=cj.shape[0] b_num=cj.shape[1] a_vv = np.copy(cj.reshape(a_num//bina, bina, b_num//binb, binb)) cj=np.mean(np.mean(a_vv,axis=3),axis=1)
def _plot_hdf5_model_vertical(f, component, output_filename, vmin=None, vmax=None): import matplotlib.cm import matplotlib.pylab as plt data = xarray.DataArray( f["data"][component][:], [ ("latitude", 90.0 - f["coordinate_0"][:]), ("longitude", f["coordinate_1"][:]), ("radius", f["coordinate_2"][:] / 1000.0)]) plt.style.use('seaborn-pastel') plt.figure(figsize=(32, 18)) plt.suptitle("Component %s - File %s" % (component, output_filename), fontsize=20) count = 12 lats = plt.linspace(data["latitude"].min(), data["latitude"].max(), count) lngs = plt.linspace(data["longitude"].min(), data["longitude"].max(), count) import lasif.colors my_colormap = lasif.colors.get_colormap( "tomo_full_scale_linear_lightness") # Overwrite colormap things if given. if vmin is not None and vmax is not None: min_val_plot = vmin max_val_plot = vmax else: mean = data.mean() max_diff = max(abs(mean - data.min()), abs(data.max() - mean)) min_val_plot = mean - max_diff max_val_plot = mean + max_diff # Plotting essentially constant models. min_delta = 0.001 * abs(max_val_plot) if (max_val_plot - min_val_plot) < min_delta: max_val_plot = max_val_plot + min_delta min_val_plot = min_val_plot - min_delta for _i in range(count): plt.subplot(4, count // 2, _i + 1) x, y = np.meshgrid(data.longitude, data.radius) plot_data = data.sel(latitude=lats[_i], method="nearest") plot_data = np.ma.masked_invalid(plot_data.data) # Plot. plt.pcolormesh( x, y, plot_data.T, cmap=my_colormap, vmin=min_val_plot, vmax=max_val_plot, shading="flat") # make a colorbar and title plt.colorbar() plt.title("@Latitude: " + str(lats[_i])) for _i in range(count): plt.subplot(4, count // 2, count + _i + 1) x, y = np.meshgrid(data.latitude, data.radius) plot_data = data.sel(longitude=lngs[_i], method="nearest") plot_data = np.ma.masked_invalid(plot_data.data) # Plot. plt.pcolormesh( x, y, plot_data.T, cmap=my_colormap, vmin=min_val_plot, vmax=max_val_plot, shading="flat") # make a colorbar and title plt.colorbar() plt.title("@Longitude: " + str(lngs[_i])) plt.tight_layout(rect=(0, 0, 1, 0.95)) plt.savefig(output_filename, dpi=150) plt.close()
def _plot_hdf5_model_horizontal(f, component, output_filename, vmin=None, vmax=None): import matplotlib.cm import matplotlib.pylab as plt data = xarray.DataArray( f["data"][component][:], [ ("latitude", 90.0 - f["coordinate_0"][:]), ("longitude", f["coordinate_1"][:]), ("radius", f["coordinate_2"][:] / 1000.0)]) plt.style.use('seaborn-pastel') from lasif.domain import RectangularSphericalSection domain = RectangularSphericalSection(**dict(f["_meta"]["domain"].attrs)) plt.figure(figsize=(32, 18)) depth_position_map = { 50: (0, 0), 100: (0, 1), 150: (1, 0), 250: (1, 1), 400: (2, 0), 600: (2, 1) } for depth, location in depth_position_map.items(): ax = plt.subplot2grid((3, 5), location) radius = 6371.0 - depth # set up a map and colourmap m = domain.plot(ax=ax, resolution="c", skip_map_features=True) import lasif.colors my_colormap = lasif.colors.get_colormap( "tomo_full_scale_linear_lightness") from lasif import rotations x, y = np.meshgrid(data.longitude, data.latitude) x_shape = x.shape y_shape = y.shape lat_r, lon_r = rotations.rotate_lat_lon( y.ravel(), x.ravel(), domain.rotation_axis, domain.rotation_angle_in_degree) x, y = m(lon_r, lat_r) x.shape = x_shape y.shape = y_shape plot_data = data.sel(radius=radius, method="nearest") plot_data = np.ma.masked_invalid(plot_data.data) # Overwrite colormap things if given. if vmin is not None and vmax is not None: min_val_plot = vmin max_val_plot = vmax else: mean = plot_data.mean() max_diff = max(abs(mean - plot_data.min()), abs(plot_data.max() - mean)) min_val_plot = mean - max_diff max_val_plot = mean + max_diff # Plotting essentially constant models. min_delta = 0.001 * abs(max_val_plot) if (max_val_plot - min_val_plot) < min_delta: max_val_plot = max_val_plot + min_delta min_val_plot = min_val_plot - min_delta # Plot. im = m.pcolormesh( x, y, plot_data, cmap=my_colormap, vmin=min_val_plot, vmax=max_val_plot, shading="gouraud") # make a colorbar and title m.colorbar(im, "right", size="3%", pad='2%') plt.title(str(depth) + ' km') # Depth based statistics. plt.subplot2grid((3, 5), (0, 4), rowspan=3) plt.title("Depth statistics") mean = data.mean(axis=(0, 1)) std = data.std(axis=(0, 1)) _min = data.min(axis=(0, 1)) _max = data.max(axis=(0, 1)) plt.fill_betweenx(data.radius, mean - std, mean + std, label="std", color="#FF3C83") plt.plot(mean, data.radius, label="mean", color="k", lw=2) plt.plot(_min, data.radius, color="grey", label="min") plt.plot(_max, data.radius, color="grey", label="max") plt.legend(loc="best") plt.xlabel("Value") plt.ylabel("Radius") plt.hlines(data.radius, plt.xlim()[0], plt.xlim()[1], color="0.8", zorder=-10, linewidth=0.5) # Roughness plots. plt.subplot2grid((3, 5), (0, 2)) _d = np.abs(data.diff("latitude", n=1)).sum("latitude").data plt.title("Roughness in latitude direction, Total: %g" % _d.sum()) plt.pcolormesh(data.longitude.data, data.radius.data, _d.T, cmap=matplotlib.cm.viridis) try: plt.colorbar() except: pass plt.xlabel("Longitude") plt.ylabel("Radius") plt.subplot2grid((3, 5), (1, 2)) _d = np.abs(data.diff("longitude", n=1)).sum("longitude").data plt.title("Roughness in longitude direction. Total: %g" % data.sum()) plt.pcolormesh(data.latitude.data, data.radius.data, _d.T, cmap=matplotlib.cm.viridis) try: plt.colorbar() except: pass plt.xlabel("Latitude") plt.ylabel("Radius") plt.subplot2grid((3, 5), (2, 2)) _d = np.abs(data.diff("radius", n=1)).sum("radius").data plt.title("Roughness in radius direction. Total: %g" % _d.sum()) plt.pcolormesh(data.longitude.data, data.latitude.data, _d, cmap=matplotlib.cm.viridis) try: plt.colorbar() except: pass plt.xlabel("Longitude") plt.ylabel("Latitude") # L2 plt.subplot2grid((3, 5), (0, 3)) _d = (data ** 2).sum("latitude").data plt.title("L2 Norm in latitude direction, Total: %g" % _d.sum()) plt.pcolormesh(data.longitude.data, data.radius.data, _d.T, cmap=matplotlib.cm.viridis) try: plt.colorbar() except: pass plt.xlabel("Longitude") plt.ylabel("Radius") plt.subplot2grid((3, 5), (1, 3)) _d = (data ** 2).sum("longitude").data plt.title("L2 Norm in longitude direction, Total: %g" % _d.sum()) plt.pcolormesh(data.latitude.data, data.radius.data, _d.T, cmap=matplotlib.cm.viridis) try: plt.colorbar() except: pass plt.xlabel("Latitude") plt.ylabel("Radius") plt.subplot2grid((3, 5), (2, 3)) _d = (data ** 2).sum("radius").data plt.title("L2 Norm in radius direction, Total: %g" % _d.sum()) plt.pcolormesh(data.longitude.data, data.latitude.data, _d, cmap=matplotlib.cm.viridis) try: plt.colorbar() except: pass plt.xlabel("Longitude") plt.ylabel("Latitude") plt.suptitle("Component %s - File %s" % (component, output_filename), fontsize=20) plt.tight_layout(rect=(0, 0, 1, 0.95)) plt.savefig(output_filename, dpi=150) plt.close()