def xlayer_yarea_zscore(filename, nareas, nlayers, n_sig_in_area, n_tot_in_area, data, title): # generate Y axis labels ylabels = [] for aid in range(nareas): prefix = '0' if aid < 10 else '' label = '(%d/%d) %s%d' % (int( n_sig_in_area[aid]), int(n_tot_in_area[aid]), prefix, aid) ylabels.append(label) plt.figure(figsize=(30, 30), dpi=600) plt.imshow(data, interpolation='none', cmap=cm.Blues) plt.clim(0, 0.22) plt.xticks(range(nlayers), size=14) plt.yticks(range(nareas), ylabels, size=14) plt.xlabel('DCNN layer', size=18) plt.ylabel('Brodmann area', size=18) plt.title(title, size=18) plt.colorbar() for aid in range(nareas): for lid in range(nlayers): plt.text(lid, aid, ('%.3f' % data[aid, lid])[1:], va='center', ha='center', size=12) plt.savefig(filename, bbox_inches='tight') plt.clf()
def plotTimedependentDensity2dWithRawData( xv, yv, Z, ts, us, addContour=True, color_bar_label=r'$\hat{F}(\xi_1, \xi_2)$', levels=None, clabels=None, manual_locations=None): # np.savetxt('density2d.csv', z.reshape(n * n, 3), delimiter=' ') im = plt.imshow(Z, interpolation='bicubic', origin="lower", aspect='auto', extent=[ts.min(), ts.max(), us.min(), us.max()]) cbar = plt.colorbar(im) cbar.ax.set_ylabel(color_bar_label) plt.clim(0, 1) if addContour: addContours(xv, yv, Z, levels, clabels, manual_locations)
def plotscalefactors(self): ''' Plots the distribution of scalefactors between consecutive images. This is to check manually that the hdr image assembly is done correctly. ''' import matplotlib.pylab as plt print('Scalefactors for HDR-assembling are', self.scalefactors) print('Standard deviations for Scalefactors are', self.scalefactorsstd) # Plots the scalefactordistribution and scalefactors for each pixelvalue self.scaleforpix = list(range(len(self.raw))) for n in range(len(self.raw) - 1): A = self.getimgquotient(n) B = self._getrealimg(n + 1) fig = plt.figure() plt.xlabel('x [pixel]') plt.ylabel('y [pixel]') fig.set_size_inches(10, 10) plt.imshow(A) plt.clim([0.95 * A[np.isfinite(A)].min(), 1.05 * A[np.isfinite(A)].max()]) plt.colorbar() fig = plt.figure() linplotdata = np.array([B[np.isfinite(B)].flatten(), A[np.isfinite(B)].flatten()]) plt.plot(linplotdata[0, :], linplotdata[1, :], 'ro')
def plotConn(): # Create plot figh = figure(figsize=(8,6)) figh.subplots_adjust(left=0.02) # Less space on left figh.subplots_adjust(right=0.98) # Less space on right figh.subplots_adjust(top=0.96) # Less space on bottom figh.subplots_adjust(bottom=0.02) # Less space on bottom figh.subplots_adjust(wspace=0) # More space between figh.subplots_adjust(hspace=0) # More space between h = axes() totalconns = zeros(shape(f.connprobs)) for c1 in range(size(f.connprobs,0)): for c2 in range(size(f.connprobs,1)): for w in range(f.nreceptors): totalconns[c1,c2] += f.connprobs[c1,c2]*f.connweights[c1,c2,w]*(-1 if w>=2 else 1) imshow(totalconns,interpolation='nearest',cmap=bicolormap(gap=0)) # Plot grid lines hold(True) for pop in range(f.npops): plot(array([0,f.npops])-0.5,array([pop,pop])-0.5,'-',c=(0.7,0.7,0.7)) plot(array([pop,pop])-0.5,array([0,f.npops])-0.5,'-',c=(0.7,0.7,0.7)) # Make pretty h.set_xticks(range(f.npops)) h.set_yticks(range(f.npops)) h.set_xticklabels(f.popnames) h.set_yticklabels(f.popnames) h.xaxis.set_ticks_position('top') xlim(-0.5,f.npops-0.5) ylim(f.npops-0.5,-0.5) clim(-abs(totalconns).max(),abs(totalconns).max()) colorbar()
def plotWeightChanges(): if f.usestdp: # create plot figh = figure(figsize=(1.2*8,1.2*6)) figh.subplots_adjust(left=0.02) # Less space on left figh.subplots_adjust(right=0.98) # Less space on right figh.subplots_adjust(top=0.96) # Less space on bottom figh.subplots_adjust(bottom=0.02) # Less space on bottom figh.subplots_adjust(wspace=0) # More space between figh.subplots_adjust(hspace=0) # More space between h = axes() # create data matrix wcs = [x[-1][-1] for x in f.allweightchanges] # absolute final weight wcs = [x[-1][-1]-x[0][-1] for x in f.allweightchanges] # absolute weight change pre,post,recep = zip(*[(x[0],x[1],x[2]) for x in f.allstdpconndata]) ncells = int(max(max(pre),max(post))+1) wcmat = zeros([ncells, ncells]) for iwc,ipre,ipost,irecep in zip(wcs,pre,post,recep): wcmat[int(ipre),int(ipost)] = iwc *(-1 if irecep>=2 else 1) # plot imshow(wcmat,interpolation='nearest',cmap=bicolormap(gap=0,mingreen=0.2,redbluemix=0.1,epsilon=0.01)) xlabel('post-synaptic cell id') ylabel('pre-synaptic cell id') h.set_xticks(f.popGidStart) h.set_yticks(f.popGidStart) h.set_xticklabels(f.popnames) h.set_yticklabels(f.popnames) h.xaxif.set_ticks_position('top') xlim(-0.5,ncells-0.5) ylim(ncells-0.5,-0.5) clim(-abs(wcmat).max(),abs(wcmat).max()) colorbar()
def show_slice(data, slice_no=0, clim=None): """ Visualize the reconstructed slice. Parameters ----------- data : ndarray 3-D matrix of stacked reconstructed slices. slice_no : scalar, optional The index of the slice to be imaged. """ plt.figure(figsize=(7, 7)) if len(data.shape) is 2: plt.imshow(data, interpolation='none', cmap='gray') plt.colorbar() elif len(data.shape) is 3: plt.imshow(data[slice_no, :, :], interpolation='none', cmap='gray') plt.colorbar() if clim is not None: plt.clim(clim) plt.show()
def func_plot_map(self, event): prop = self.get_map_properties() lat = prop.pop('south'), prop.pop('north') lon = prop.pop('west'), prop.pop('east') dlim = prop.pop('dmin'), prop.pop('dmax') map_obj = bath_map(lat, lon, **prop) x = self.data.wg_longitude y = self.data.wg_latitude t = self.data.wg_datenum idx_dtime = (t >= dlim[0]) * (t <= dlim[1]) idx_cords = (x > lon[0]) * (x < lon[1]) * \ (y > lat[0]) * (y < lat[1]) idx_licor = self.get_midx() idx = idx_dtime * idx_cords * idx_licor x = x[idx] y = y[idx] c = self.data[prop['var']][idx] x, y = map_obj(x, y) map_obj.scatter(x, y, prop['markersize'], c, marker=prop['marker'], cmap=prop['cmap'], linewidths=0) plt.clim(prop['cmin'], prop['cmax']) plt.title(prop['title']) plt.colorbar() plt.show()
def plotTimedependentDensity2d(Us, us, ts, addContour=True, color_bar_label=r'$\hat{F}(\xi_1, \xi_2)$', levels=None, clabels=None, manual_locations=None): Z = np.ones((us.shape[0], ts.shape[0])) xv, yv = np.meshgrid(ts, us, sparse=False, indexing='xy') for i in range(len(ts)): for j in range(len(us)): Z[j, i] = Us[i](np.array([yv[j, i]])) # np.savetxt('density2d.csv', z.reshape(n * n, 3), delimiter=' ') im = plt.imshow(Z, interpolation='bicubic', origin="lower", aspect='auto', extent=[ts.min(), ts.max(), us.min(), us.max()]) cbar = plt.colorbar(im) cbar.ax.set_ylabel(color_bar_label) plt.clim(0, 1) if addContour: addContours(xv, yv, Z, levels, clabels, manual_locations)
def plotscalefactors(self): ''' Plots the distribution of scalefactors between consecutive images. This is to check manually that the hdr image assembly is done correctly. ''' import matplotlib.pylab as plt print('Scalefactors for HDR-assembling are', self.scalefactors) print('Standard deviations for Scalefactors are', self.scalefactorsstd) # Plots the scalefactordistribution and scalefactors for each pixelvalue self.scaleforpix = range(len(self.raw)) for n in range(len(self.raw) - 1): A = self.getimgquotient(n) B = self._getrealimg(n + 1) fig = plt.figure() plt.xlabel('x [pixel]') plt.ylabel('y [pixel]') fig.set_size_inches(10, 10) plt.imshow(A) plt.clim([0.95 * A[np.isfinite(A)].min(), 1.05 * A[np.isfinite(A)].max()]) plt.colorbar() fig = plt.figure() linplotdata = np.array([B[np.isfinite(B)].flatten(), A[np.isfinite(B)].flatten()]) plt.plot(linplotdata[0, :], linplotdata[1, :], 'ro')
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_image(data): fig = plt.figure() cax = plt.imshow(data, cmap='Blues') plt.colormaps() plt.clim(0, 400) cbar = fig.colorbar(cax, orientation='vertical') #cbar.ax.set_yticklabels(['< -1', '0', 1, 2,'> 10'])# vertically oriented colorbar plt.show()
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_distogram(distogram, savepath, title="", clim=None): """Save a plot of a distogram to the given path.""" plt.imshow(distogram) plt.title(title, fontsize=14) plt.xlabel("Residue i") plt.ylabel("Residue j") if clim is not None: plt.clim(clim[0], clim[1]) plt.colorbar() plt.tight_layout() plt.savefig(savepath) plt.close("all")
def plotPoint_Scatter(a1dData, a1dGeoX, a1dGeoY, a1dGeoBox, dDataMin=0, dDataMax=10, sColorMap='RdBu_r', sCBarLabel='NA', sMapRes='l'): # Define geobox dGeoYMin = a1dGeoBox[0] dGeoXMin = a1dGeoBox[1] dGeoYMax = a1dGeoBox[2] dGeoXMax = a1dGeoBox[3] oFig = plt.figure(figsize=(18, 18)) oBaseMap = Basemap(projection='cea', resolution=sMapRes, llcrnrlat=dGeoYMin, llcrnrlon=dGeoXMin, urcrnrlat=dGeoYMax, urcrnrlon=dGeoXMax) oBaseMap.drawlsmask(land_color="#ddaa66", ocean_color="#7777ff", resolution='i') oBaseMap.drawcoastlines(color='lightgray', linewidth=1.25) oBaseMap.fillcontinents() oBaseMap.drawmapboundary(fill_color='aqua') oBaseMap.scatter(a1dGeoX, a1dGeoY, s=a1dData * 10, c=a1dData, cmap=sColorMap, zorder=10, latlon=True) oBaseMap.drawparallels(arange(dGeoYMin, dGeoYMax, 0.4), labels=[True, False, False, False]) oBaseMap.drawmeridians(arange(dGeoXMin, dGeoXMax, 0.4), labels=[False, False, False, True]) oBaseMap.colorbar(location='bottom', format='%d', label=sCBarLabel) plt.clim(dDataMin, dDataMax) plt.show()
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 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 main(argv=None): if argv is None: argv=sys.argv parser = OptionParser(add_help_option=False) parser.add_option("-l", dest="inList") parser.add_option("-b", dest="inBase") parser.add_option("-o", dest="outImg") parser.add_option("-h", dest="doHelp", action="store_true", default=False) options, _ = parser.parse_args() if options.doHelp: usage() sys.exit(-1) inBase = options.inBase inList = options.inList outImg = options.outImg with open(inList) as fid: lines = fid.readlines() data = [] for l in lines: imgName = os.path.join(inBase, l.rstrip()) basName, ext = os.path.splitext(l.rstrip()) img = np.fromfile(imgName, dtype=np.float32) data.append(img) maxVals = [np.amax(x.ravel()) for x in data] minVals = [np.amin(x.ravel()) for x in data] amax = np.amax(maxVals) amin = np.amin(minVals) for cnt, x in enumerate(data): subplotId = "1" + str(len(data)) + str(cnt+1) lab.subplot(subplotId) lab.imshow(x.reshape((256,256)).T, cmap=lab.cm.jet) lab.clim(amin, amax) lab.axis('Off') lab.savefig(outImg, bbox_inches='tight')
def showImage(data, xticks=None, yticks=None, range=None, title=None): """ Used to show 2D data using imshow from matplotlib. Issues regarding transposition of data, and setting up the correct origin are resolved """ plt.figure() data_shape = np.shape(data) plt.imshow(data.T, origin='lower') # NOTE: LINSPACE in numpy includes the last point, whereas the vanilla # 'range' does not. This is the cause of all the pain below! if xticks is not None: if len(xticks) > MAX_TICKS_TO_SHOW: plt.xticks( np.linspace(0, data_shape[0] - 1, num=MAX_TICKS_TO_SHOW), np.round( np.linspace(xticks[0], xticks[-1], num=MAX_TICKS_TO_SHOW), 2)) else: plt.xticks(np.linspace(0, data_shape[0] - 1, num=len(xticks)), np.round(xticks, 2)) if yticks is not None: if len(yticks) > MAX_TICKS_TO_SHOW: plt.yticks( np.linspace(0, data_shape[1] - 1, num=MAX_TICKS_TO_SHOW), np.round( np.linspace(yticks[0], yticks[-1], num=MAX_TICKS_TO_SHOW), 2)) else: plt.yticks(np.linspace(0, data_shape[1] - 1, num=len(yticks)), np.round(yticks, 2)) if range is not None: plt.clim(vmin=range[0], vmax=range[1]) if title is not None: plt.title(title) plt.xlabel('X (bin)') plt.ylabel('Y (bin)') plt.colorbar() plt.gcf().show()
def main(argv=None): if argv is None: argv = sys.argv parser = OptionParser(add_help_option=False) parser.add_option("-l", dest="inList") parser.add_option("-b", dest="inBase") parser.add_option("-o", dest="outImg") parser.add_option("-h", dest="doHelp", action="store_true", default=False) options, _ = parser.parse_args() if options.doHelp: usage() sys.exit(-1) inBase = options.inBase inList = options.inList outImg = options.outImg with open(inList) as fid: lines = fid.readlines() data = [] for l in lines: imgName = os.path.join(inBase, l.rstrip()) basName, ext = os.path.splitext(l.rstrip()) img = np.fromfile(imgName, dtype=np.float32) data.append(img) maxVals = [np.amax(x.ravel()) for x in data] minVals = [np.amin(x.ravel()) for x in data] amax = np.amax(maxVals) amin = np.amin(minVals) for cnt, x in enumerate(data): subplotId = "1" + str(len(data)) + str(cnt + 1) lab.subplot(subplotId) lab.imshow(x.reshape((256, 256)).T, cmap=lab.cm.jet) lab.clim(amin, amax) lab.axis('Off') lab.savefig(outImg, bbox_inches='tight')
def xlayer_yarea_zscore_visual(filename, nareas, nlayers, n_sig_in_area, n_tot_in_area, data, title): # trim data to visual areas visual_areas = visual_areas = [17, 18, 19, 37, 20] nareas = len(visual_areas) n_sig_in_area = n_sig_in_area[visual_areas] n_tot_in_area = n_tot_in_area[visual_areas] data = data[visual_areas, :] # generate Y axis labels ylabels = [] for aid in range(nareas): prefix = '0' if visual_areas[aid] < 10 else '' label = '(%d/%d) %s%d' % (int( n_sig_in_area[aid]), int( n_tot_in_area[aid]), prefix, visual_areas[aid]) ylabels.append(label) # plot plt.figure(figsize=(15, 8), dpi=600) plt.imshow(data, interpolation='none', cmap=cm.Blues) plt.clim(0, 0.22) plt.xticks(range(nlayers), size=24) plt.yticks(range(nareas), ylabels, size=24) plt.xlabel('DCNN layer', size=24) plt.ylabel('Brodmann area', size=24) plt.title(title, size=24) #plt.colorbar(); for aid in range(nareas): for lid in range(nlayers): plt.text(lid, aid, ('%.3f' % data[aid, lid])[1:], va='center', ha='center', size=24) plt.savefig(filename, bbox_inches='tight') plt.clf() plt.close()
def plotMap_Pcolor(a2dData, a2dGeoX, a2dGeoY, a1dGeoBox, dDataMin=0, dDataMax=10, sColorMap='RdBu_r', sCBarLabel='NA', sMapRes='l'): # Define geobox dGeoYMin = a1dGeoBox[0] dGeoXMin = a1dGeoBox[1] dGeoYMax = a1dGeoBox[2] dGeoXMax = a1dGeoBox[3] oFig = plt.figure(figsize=(18, 18)) oBaseMap = Basemap(projection='cea', resolution=sMapRes, llcrnrlat=dGeoYMin, llcrnrlon=dGeoXMin, urcrnrlat=dGeoYMax, urcrnrlon=dGeoXMax) oBaseMap.drawcoastlines(color='lightgray', linewidth=1.25) # oBaseMap.fillcontinents() oBaseMap.drawmapboundary(fill_color='aqua') oBaseMap.pcolormesh(a2dGeoX, a2dGeoY, a2dData, latlon=True, cmap=sColorMap) oBaseMap.drawparallels(arange(dGeoYMin, dGeoYMax, 0.4), labels=[True, False, False, False]) oBaseMap.drawmeridians(arange(dGeoXMin, dGeoXMax, 0.4), labels=[False, False, False, True]) oBaseMap.colorbar(location='right', format='%d', label=sCBarLabel) plt.clim(dDataMin, dDataMax) plt.show()
def panel_activity(activity, title, lines, mask=None): plt.imshow(activity, interpolation='none', origin='lower', cmap=cm.bwr, aspect='auto'); cb = plt.colorbar(); plt.clim(-4.0, 4.0) if mask is not None: plt.contour(mask, mask, colors='black', vmin=0.0, vmax=1.0, extend='max', linewidths=1.0) cb.ax.tick_params(labelsize=16); plt.axvline(x=16, ymin=0.0, ymax = 1.0, linewidth=1.0, color='r', ls='--') if lines: plt.axvline(x=19, ymin=0.0, ymax = 1.0, linewidth=0.5, color='gray', ls='-') plt.axvline(x=24, ymin=0.0, ymax = 1.0, linewidth=0.5, color='gray', ls='-') plt.axvline(x=32, ymin=0.0, ymax = 1.0, linewidth=0.5, color='gray', ls='-') plt.axhline(y=4, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-') plt.axhline(y=10, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-') plt.axhline(y=27, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-') plt.axhline(y=56, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-') plt.xticks(np.arange(0, 48, 2), np.asarray((np.arange(0, 769, 32) - 256) / 512.0 * 1000, dtype='int'), size=18, rotation=90); plt.yticks(np.arange(0, 146, 7), np.arange(4, 150, 7), size=18); plt.ylabel('Frequency (Hz)', size=24); plt.xlabel('Time (ms)', size=24); if title is not None: plt.title(title, size=26);
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 createAndSaveHeatMap(dataArray, figFileRoot, xLabel="", yLabel="", xMin=0, xMax=-1, yMin=0, yMax=-1, colorMap=0, maxInt=0, vMin=0, vMax=0, fontSize=20, majorFontSize=18, pngDPI=150, svgDPI=75, svgFlag=0): """Make a 2D intensity map of the data and save it to file.""" colorList = [None, plt.cm.Reds, plt.cm.Greens, plt.cm.Greys] if vMin == -10: vMin = 0 if vMax == 0: for a in dataArray.flat: if not isnan(a) and a > vMax: vMax = a plt.pcolor(dataArray, cmap=colorList[colorMap], vmin=vMin, vmax=vMax) plt.xlabel(xLabel, fontsize=fontSize) plt.ylabel(yLabel, fontsize=fontSize) plt.colorbar(orientation="vertical") ax = plt.gca() for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(majorFontSize) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(majorFontSize) if xMax == -1: plt.xlim() else: plt.xlim(xMin, xMax) if yMax == -1: plt.ylim() else: plt.ylim(yMin, yMax) if maxInt != 0: plt.clim(0, maxInt) plt.savefig(figFileRoot + '.png', dpi=pngDPI) if svgFlag == 1: plt.savefig(figFileRoot + '.svg', dpi=svgDPI) plt.clf()
def plot_frames_2D(frames,dataset,out,mm=None,title='',filter=lambda d: d,cmap=plt.get_cmap('jet'),extent=None,overwrite=False): for n in range(len(frames)): try: plot_out=out%n except TypeError: plot_out=out if not os.path.exists(plot_out) or overwrite: LOG.debug("Plotting frame %s",plot_out) step,time=frames[n] data=dataset[n] LOG.debug("data shape : %s",data.shape) fig=plt.figure(frameon=False) fig.clf() plt.imshow(filter(data.T),origin='bottom',cmap=cmap,extent=extent) plt.colorbar(shrink=.3,aspect=40) if mm!=None: plt.clim(filter(mm[0]),filter(mm[1])) ma=time/s_in_y/1e6 plt.title('%s (%0.3f Ma @ timestep %d)'%(title,ma,step)) plt.savefig(plot_out,bbox_inches='tight') plt.close() else: LOG.debug("Skipping existing frame %s",plot_out)
def xlayer_yarea_zscore_visual_linfit(filename, nareas, nlayers, n_sig_in_area, n_tot_in_area, data, title): # trim data to visual areas visual_areas = visual_areas = [17, 18, 19, 37, 20] nareas = len(visual_areas) n_sig_in_area = n_sig_in_area[visual_areas] n_tot_in_area = n_tot_in_area[visual_areas] data = data[visual_areas, :] # generate Y axis labels ylabels = [] for aid in range(nareas): prefix = '0' if visual_areas[aid] < 10 else '' label = '(%d/%d) %s%d' % (int( n_sig_in_area[aid]), int( n_tot_in_area[aid]), prefix, visual_areas[aid]) ylabels.append(label) # compute similarity measure x = np.ravel(np.matrix([range(nlayers)] * nareas)) y = np.ravel([[i] * nlayers for i in np.arange(nareas - 1, -1, -1)]) # fit the lines ideal_m, ideal_b = np.polyfit([0, 1, 1, 2, 3, 4, 5, 5, 6, 7], [4, 4, 3, 3, 3, 2, 2, 1, 1, 0], 1) m, b = np.polyfit(x, y, 1, w=np.ravel(data)) # cosine distance v = np.array([100, m * 100 + b]) - np.array([0, m * 0 + b]) ideal_v = np.array([100, ideal_m * 100 + ideal_b]) - np.array( [0, ideal_m * 0 + ideal_b]) # plot plt.figure(figsize=(15, 8), dpi=600) plt.subplot(1, 2, 1) plt.imshow(data, interpolation='none', cmap=cm.Blues) plt.clim(0, 0.22) plt.xticks(range(nlayers), size=24) plt.yticks(range(nareas), ylabels, size=24) plt.xlabel('DCNN layer', size=24) plt.ylabel('Brodmann area', size=24) plt.title(title, size=24) #plt.colorbar(); for aid in range(nareas): for lid in range(nlayers): plt.text(lid, aid, ('%.3f' % data[aid, lid])[1:], va='center', ha='center', size=24) plt.subplot(1, 2, 2) plt.scatter(x, y, s=np.array(np.ravel(data)) * 1000) plt.plot(np.array(x), ideal_m * np.array(x) + ideal_b, 'g') plt.plot(np.array(x), m * np.array(x) + b, 'b') plt.title('Cosine distance: %.5f' % cosine(v, ideal_v)) plt.xticks(range(nlayers)) plt.yticks(range(nareas), list(reversed(ylabels))) plt.savefig(filename, bbox_inches='tight') plt.clf()
def PlotPt2PtDiff(SSH_DAprods0,nameDAprods0,SSH_Ensforecast0,SSH_NATL60_degrad0,lon2d0,lat2d0,ntime0): timet0=0 timet1=int(ntime0/2) timet2=ntime0-2 max_range=0.02 plt.figure(figsize=(20, 10)) plt.subplot(131) plt.pcolormesh(lon2d0,lat2d0,np.mean(SSH_Ensforecast0[timet0,:,:,:],0)-SSH_NATL60_degrad0[timet0,:,:],cmap=plt.cm.get_cmap('bwr')) plt.colorbar(extend='both', fraction=0.042, pad=0.04) plt.title('DA_SSH-NATL60_SSH(%sd)'%(timet0+1)); plt.clim(-max_range,max_range) plt.subplot(132) plt.pcolormesh(lon2d0,lat2d0,np.mean(SSH_Ensforecast0[timet1,:,:,:],0)-SSH_NATL60_degrad0[timet1,:,:],cmap=plt.cm.get_cmap('bwr')) plt.colorbar(extend='both', fraction=0.042, pad=0.04) plt.title('DA_SSH-NATL60_SSH(%sd)'%(timet1+1)); plt.clim(-max_range,max_range) plt.subplot(133) plt.pcolormesh(lon2d0,lat2d0,np.mean(SSH_Ensforecast0[timet2,:,:,:],0)-SSH_NATL60_degrad0[timet2,:,:],cmap=plt.cm.get_cmap('bwr')) plt.colorbar(extend='both', fraction=0.042, pad=0.04) plt.title('DA_SSH-NATL60_SSH(%sd)'%(timet2+1)); plt.clim(-max_range,max_range) for i_DAprod in range(np.shape(nameDAprods0)[0]): SSH_DAprod=SSH_DAprods0[i_DAprod] plt.figure(figsize=(20, 10)) plt.subplot(131) plt.pcolormesh(lon2d0,lat2d0,SSH_DAprod[timet0,:,:]-SSH_NATL60_degrad0[timet0,:,:],cmap=plt.cm.get_cmap('bwr')) plt.colorbar(extend='both', fraction=0.042, pad=0.04) plt.title('DA_SSH-NATL60_SSH(%sd)'%(timet0+1)); plt.clim(-max_range,max_range) plt.subplot(132) plt.pcolormesh(lon2d0,lat2d0,SSH_DAprod[timet1,:,:]-SSH_NATL60_degrad0[timet1,:,:],cmap=plt.cm.get_cmap('bwr')) plt.colorbar(extend='both', fraction=0.042, pad=0.04) plt.title('DA_SSH-NATL60_SSH(%sd)'%(timet1+1)); plt.clim(-max_range,max_range) plt.subplot(133) plt.pcolormesh(lon2d0,lat2d0,SSH_DAprod[timet2,:,:]-SSH_NATL60_degrad0[timet2,:,:],cmap=plt.cm.get_cmap('bwr')) plt.colorbar(extend='both', fraction=0.042, pad=0.04) plt.title('DA_SSH-NATL60_SSH(%sd)'%(timet2+1)); plt.clim(-max_range,max_range) return
def plot_memb_current_for_cell(time_pt, params, plot_morpho=False, plot_field=True, plot_synapses=False, plot_current=False, ax=None): # this is used for frames of the movie v_ext, xx, yy, seg_coords, x_range, y_range, dt = params #v_ext, xx, yy, seg_coords, x_range, y_range, inh_syn_coords, exc_syn_coords, dt = params max_field = np.max(v_ext) if max_field >= 1000: # convert to microvolts v_ext = v_ext / 10e2 # change to microvolts scale_type = 'micro' max_field /= 10e2 else: scale_type = 'nano' #v_ext = v_ext / 10e2 # change nano to micro volts import matplotlib.colors as colors if ax == None: ax = plt.subplot(1, 1, 1) # draw field mycmap, colormap_range_ceil, aspect, one_forth_colormap, colormap_range = helper_provide_imshow_details( v_ext, x_range, y_range) if plot_field: pcm = plt.imshow( v_ext[time_pt, :, :], interpolation="nearest", #norm=colors.SymLogNorm(linthresh=0.01 * np.max(v_ext), # linscale=1.0, # vmin=colormap_range_ceil[0], vmax=colormap_range_ceil[1]), origin='lower', aspect=0.8, extent=(x_range[0], x_range[1], y_range[0], y_range[1]), cmap=mycmap) plt.clim(colormap_range[0], colormap_range[1]) if plot_morpho: # draw morpho import pdb pdb.set_trace() col = graph.plot_neuron(seg_coords, colors='k', autolim=True) soma_idcs, = np.where(seg_coords['name'] == 'soma') draw_soma(ax, x0=seg_coords[soma_idcs[0]]['x0'], x1=seg_coords[soma_idcs[-1]]['x1'], y0=seg_coords[soma_idcs[0]]['y0'], y1=seg_coords[soma_idcs[-1]]['y1'], color='k') plt.xlim(x_range) plt.ylim(y_range) x_tic_label, xtics, y_tic_label, ytics = helper_define_tick_space( x_range, y_range) ax.set_yticks(ytics) ax.set_yticklabels(y_tic_label) ax.set_xticks(xtics) ax.set_xticklabels(x_tic_label) if plot_field: cbar = plt.colorbar(pcm, extend='both', drawedges=False) # ax=ax[0], cbar.set_ticks([ colormap_range[0], -one_forth_colormap, 0, one_forth_colormap, colormap_range[1] ]) cbar.set_ticklabels([ str(colormap_range[0]), str(-one_forth_colormap), '0', str(one_forth_colormap), colormap_range[1] ]) if scale_type == 'micro': cbar.set_label(r"voltage ($\mu$V)", fontsize=18) elif scale_type == 'nano': cbar.set_label(r"voltage (nV)", fontsize=18) #cbar.set_label(r"voltage ($\mu$V)", fontsize=18) #cbar.set_label(r"voltage (nV)", fontsize=18) cbar.ax.tick_params(labelsize=16) if plot_current: # draw streamplots U = -np.diff(v_ext[time_pt, :, :], axis=0)[:, :-1] V = -np.diff(v_ext[time_pt, :, :], axis=1)[:-1, :] plt.streamplot(xx[0, :-1], yy[:-1, 0], V, U, density=1.0, color='g') plt.title('time: ' + str(("%0.2f" % (time_pt * dt))) + 'ms') ax.set_xlabel(r"space ($\mu$m)") ax.set_ylabel(r"space ($\mu$m)") clean_plot(ax) plt.tight_layout() return mycmap, colormap_range
def buildSM(self, coords, n_modes=None, kbt=1., saveMap=False, saveMatrix=False, filename='sm'): """Calculate stiffness matrix calculated using :class:`.ANM` instance. Method described in [EB08]_. .. [EB08] Eyal E., Bahar I. Toward a Molecular Understanding of the Anisotropic Response of Proteins to External Forces: Insights from Elastic Network Models. *Biophys J* **2008** 94:3424-34355. :arg coords: a coordinate set or an object with ``getCoords`` method :type coords: :class:`numpy.ndarray`. :arg n_modes: number of non-zero eigenvalues/vectors to calculate. If ``None`` is given, all modes will be calculated (3x number of atoms). :type n_modes: int or ``None``, default is 20. By default results are not saved to a *filename* file. To save data with stiffness matrix map and mean value of effective force constant for each residue use: ``saveMap=True`` and ``saveMatrix=True``. Author: Mustafa Tekpinar & Karolina Mikulska-Ruminska & Cihan Kaya """ try: coords = (coords._getCoords() if hasattr(coords, '_getCoords') else coords.getCoords()) except AttributeError: try: checkCoords(coords) except TypeError: raise TypeError('coords must be a Numpy array or an object ' 'with `getCoords` method') n_atoms = natoms = self._n_atoms n_modes = 3 * n_atoms self.calcModes(n_modes=None, zeros=True) LOGGER.timeit('_sm') eigvecs = (np.transpose(self._array)).flatten() eigvals = np.transpose(self._eigvals) natoms = n_atoms sm = np.zeros((n_atoms, n_atoms), np.double) from .smtools import calcSM LOGGER.info('Calculating stiffness matrix.') calcSM(coords, sm, eigvecs, eigvals, natoms, n_modes, float(kbt)) LOGGER.report('Stiffness matrix calculated in %.2lfs.', label='_sm') self._stiffness = sm meanSiff = np.mean(sm, axis=0) LOGGER.info('The range of effective force constant is: {0} to {1}.' .format(np.min(sm[np.nonzero(sm)]), np.amax(sm))) if (saveMatrix == True): np.savetxt(filename+'.txt', sm, fmt='%.6f') out_mean = open(filename+'_mean.txt','w') # mean value of Kij for each residue for nr_i, i in enumerate(meanSiff): out_mean.write("{} {}\n".format(nr_i, i)) out_mean.close() if (saveMap == True): import math import matplotlib import matplotlib.pylab as plt matplotlib.rcParams['font.size'] = '16' fig = plt.figure(num=None, figsize=(10,8), dpi=100, facecolor='w') plt.imshow(sm, origin='lower') plt.axis([0, n_atoms, n_atoms, 0]) plt.xlabel('residue', fontsize = '18') plt.ylabel('residue', fontsize = '18') cbar = plt.colorbar() #cbar.set_label('N/m', rotation=90, fontsize = '18') plt.clim(math.floor(np.min(sm[np.nonzero(sm)])), round(np.amax(sm),1)) plt.savefig(filename+'.png', dpi=100)
plt.xlim([0,len(solution.T)]) plt.subplot(1,7,2) solution = np.loadtxt("random_sampled_population_{0}.dat".format(i)) solution_means = np.mean(solution,axis=0) plt.bar([_ for _ in range(0,len(solution.T))],solution_means,color="k") plt.ylim([0,1]) plt.xlim([0,len(solution.T)]) plt.subplot(1,7,3) solution = np.loadtxt("training_data_{0}.dat".format(i)) plt.pcolor(solution,cmap="Greys") plt.xlim(0,128) plt.subplot(1,7,4) solution = np.loadtxt("fitness_training_data_{0}.dat".format(i)) solution = solution.reshape(solution.shape[0],1) plt.pcolor(solution,cmap="Reds") plt.clim(0,1024) # plt.xlim(0,105) plt.subplot(1,7,5) solution = np.loadtxt("population_{0}.dat".format(i)) plt.pcolor(solution,cmap="Greys") plt.xlim(0,128) plt.subplot(1,7,6) solution = np.loadtxt("fitness_pop_{0}.dat".format(i)) solution = solution.reshape(solution.shape[0],1) plt.pcolor(solution,cmap="Reds") plt.clim(0,1024) # plt.savefig("top_20_noise_0.5.png") plt.subplot(1,7,7) solution = np.loadtxt("fitness_pop_{0}.dat".format(i)) fitnesses = np.loadtxt("fitness_pop_{0}.dat".format(0)) fitnesses = fitnesses.reshape((fitnesses.shape[0],1))
def principal_tensor(self, scale=100, space=5, twod=False, absolutemax=False, colorbarcenter=True): ''' Plot the principal tensor direction :param scale: scale of the arrow (default 100) :type scale: float :param space: take only 1 value every 'space' value to not charge the picture to much (default 5) :type space: int :param twod: use a 2d symetric tensor (=> t33=t23=t13=0) (default False) :type twod: bool :param colorbarcenter: do you want center the colorbar around 0 :type colorbarcenter: bool :return: image of the principal tensor direction :rtype: matplotlib.pyplot ''' a, v = self.diag(twod=twod) # create X, Y, U, V X = [] Y = [] U = [] V = [] C = [] ss = np.shape(self.t11.field) for i in list(range(int(ss[0] / space))): for j in list(range(int(ss[1] / space))): ii = space * i jj = space * j # eigenvalue absolute max if absolutemax: kk = np.where(abs(a[:, ii, jj]) == max(abs(a[:, ii, jj]))) else: kk = np.where(a[:, ii, jj] == max(a[:, ii, jj])) k = kk[0][0] # first arrow X.append(ii * self.t11.res) Y.append(jj * self.t11.res) U.append(a[k, ii, jj] * v[0, k, ii, jj]) V.append(a[k, ii, jj] * v[1, k, ii, jj]) C.append(a[k, ii, jj]) #symetric arrow X.append(ii * self.t11.res) Y.append(jj * self.t11.res) U.append(-a[k, ii, jj] * v[0, k, ii, jj]) V.append(-a[k, ii, jj] * v[1, k, ii, jj]) C.append(a[k, ii, jj]) X = np.array(X) Y = np.array(Y) U = np.array(U) V = np.array(V) C = np.array(C) img = plt.quiver(Y, ss[0] * self.t11.res - X, scale * V, scale * U, C, angles='xy', scale_units='xy', scale=1, cmap=cm.bwr) plt.colorbar(img, orientation='horizontal', aspect=15, format=ticker.FuncFormatter(utils.fmt)) plt.axis('equal') if colorbarcenter: zcolor = np.max(np.abs(C)) plt.clim(-zcolor, zcolor) return img
# from matplotlib.pyplot import figure, show, savefig # from matplotlib import cm, colors # from numpy import ma # fig = figure() # ax = fig.add_subplot(111) # # ax.set_axis_bgcolor("#bdb76b") # ax.set_axis_bgcolor('white') # cs=ax.pcolormesh(asca, shading='gouraud') # cs=ax.imshow(asca,origin='lower left',cmap=cm.jet) # fig.colorbar(cs) # show() ########################################### plt.imshow(asca,origin='lower left') plt.title(str(iyear)+' '+'Snow Cover Days') plt.colorbar(orientation='horizontal') plt.clim(vmin=0,vmax=365) figure_path='H:/SCA_DATA/resample_SCA/snow cover days/' plt.savefig(figure_path+str(iyear)+' '+'Snow Cover Days.jpg') #save the figure plt.show() plt.clf() ############################################# asca = mask*0. dsca = [] if temp_year != iyear or temp_month != imonth: if i_date>=datetime.date(2000,3,1) and i_date<datetime.date(2004,4,1): modisdata.close() modisdata = Dataset(modis_path+'UHBSCA'+str(iyear)+'%02d'%(imonth)+'.nc', format='NETCDF4') modisdataset = modisdata.variables['SCA'] if i_date>=datetime.date(2004,4,1) and i_date<datetime.date(2015,1,1): modisdata.close() modisdata = Dataset(modis_path+'UHBSCA'+str(iyear)+'%02d'%(imonth)+'_H.nc', format='NETCDF4')
def k_FoldGMM(featureData, k): """ Trains a GMM classifier and calculates the accuracy of a random k-fold cross-validation on the freesound data iteself @param featureData: Dictionary containing 'features' and 'labels' as numpy array and 'classesDict' for mapping of class names to numbers @param k: Cross-validation parameter, defines in how many blocks the data should be divided """ X = featureData['features'] scaler = preprocessing.StandardScaler().fit(X) X = scaler.transform(X) Y = featureData['labels'] kf = KFold(len(Y), n_folds=k, indices=True, shuffle=True) for train, test in kf: X_train, X_test, y_train, y_test = X[train], X[test], Y[train], Y[test] n_classes = len(np.unique(y_train)) print str(n_classes) + " different classes" clfs = [] for i in range(n_classes): iTmp = (y_train == i) # """ Estimate number of components using BIC criteria: """ # n_components_list = range(1,17) # bicList = [] # for c in n_components_list: # tmpClf = GMM(n_components=c, covariance_type='full', n_iter=100) # tmpClf.fit(X_train[iTmp]) # bicList.append(bic(X_train[iTmp], tmpClf.means_, tmpClf.covars_, tmpClf.weights_, c)) # # #print(str(c) + " components: " + " BIC = " + str(bicList[-1])) # # # select that number of components that resulted in the best (lowest) BIC: # val, n_components = min((val, idx) for (idx, val) in enumerate(bicList)) # n_components += 1 # print("Optimal number of components :" + str(n_components)) n_components = 16 tmpClf = GMM(n_components = n_components, covariance_type='full', n_iter=100) tmpClf.fit(X_train[iTmp]) clfs.append(tmpClf) likelihood = np.zeros((n_classes, X_test.shape[0])) """ Find class with highest likelihood: """ for i in range(n_classes): likelihood[i] = clfs[i].score(X_test) y_pred = np.argmax(likelihood, 0) """ Compare predictions to ground truth: """ agreementCounter = 0 for j in range(y_test.shape[0]): if y_test[j] == y_pred[j]: agreementCounter += 1 print str(100 * agreementCounter/y_test.shape[0]) + " % of all samples predicted correctly (without majority vote...)" """ Sort classesDict to show labels in the CM: """ sortedTmp = sorted(featureData["classesDict"].iteritems(), key=operator.itemgetter(1)) sortedLabels = [] for j in range(len(sortedTmp)): sortedLabels.append(sortedTmp[j][0]) cm = confusion_matrix(y_test, y_pred) print(cm) normalized = [] for row in cm: rowSum = sum(row) normalized.append([round(x/float(rowSum),2) for x in row]) width = len(cm) height = len(cm[0]) pl.matshow(normalized) pl.ylabel('True label') pl.xlabel('Predicted label') pl.xticks(range(len(sortedLabels)), sortedLabels) pl.yticks(range(len(sortedLabels)), sortedLabels) for x in xrange(width): for y in xrange(height): pl.annotate(str(normalized[x][y]), xy=(y, x), horizontalalignment='center', verticalalignment='center') # Force the min and max value, so that the colors will have the full range from 0 to 1: pl.clim(0,1) pl.colorbar() pl.show()
import numpy as np import matplotlib.pylab as plt a = np.genfromtxt("matrix.txt") plt.imshow(a, cmap="tab20") plt.colorbar() plt.clim(0, 100) plt.show()
def make_plot_gpd(WMO, database='', date='', what='a'): # https://stackoverflow.com/questions/59417997/how-to-plot-a-list-of-shapely-points plt.xlim([-180., 180.]) plt.ylim([-90., 90.]) """ Loading from geopandas built-in methods """ world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) world = world.plot() """ Loading from geopandas built-in methods """ world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) world = world.plot() WMO.plot(ax=world, facecolor="none", edgecolor="lightgray", lw=0.8) points_lat, points_lon, anomaly, average = [], [], [], [] for f in os.listdir(database): print(f) loaded = xr.open_dataset(database + '/' + f).to_dataframe() df_red = loaded.loc[(loaded['date_time'] == date) & (loaded['z_coordinate'] == 85000)] points_lat.append(df_red['latitude'].values) points_lon.append(df_red['longitude'].values) anomaly.append(df_red['anomaly_bias'].values) average.append(df_red['average_bias'].values) #print(points_lon, points_lat, anomaly, average) if what == 'a': plotto = plt.scatter(points_lon, points_lat, c=anomaly, s=50, marker='s', cmap='rainbow', alpha=0.7) cbar = plt.colorbar( fraction=0.03, pad=0.03 ) # pad moves bar to left-right, fractions is the length of the bar cbar.set_label('Temperature Anomaly over 20 years [K]') plt.clim(-5, 5) else: plotto = plt.scatter(points_lon, points_lat, c=average, s=50, marker='s', cmap='rainbow', alpha=0.7) cbar = plt.colorbar( fraction=0.03, pad=0.03 ) # pad moves bar to left-right, fractions is the length of the bar cbar.set_label('Average Temperature [K]') plt.clim(250, 330) date_string = 'June 2019' plt.title('Climate Studies using Radiosonde Data ' + date_string, fontsize=9) plt.xlim([-180., 180.]) plt.ylim([-90., 90.]) plt.savefig(out_dir + '/ClimateChange_' + date_string + '_' + what + '_average.png', dpi=250, bbox_inches='tight') #plt.show() plt.close() print('Done +++', d)
#see train and test error Error_train_fs[k] = np.square(y_train - m.predict( X_train[:, selected_features])).sum() / y_train.shape[0] Error_test_fs[k] = np.square(y_test - m.predict( X_test[:, selected_features])).sum() / y_test.shape[0] figure(k) subplot(1, 2, 1) plot(range(1, len(loss_record)), loss_record[1:]) xlabel('Iteration') ylabel('Squared error (crossvalidation)') subplot(1, 3, 3) bmplot(attributeNames, range(1, features_record.shape[1]), -features_record[:, 1:]) clim(-1.5, 0) xlabel('Iteration') print('Cross validation fold {0}/{1}'.format(k + 1, K)) print('Train indices: {0}'.format(train_index)) print('Test indices: {0}'.format(test_index)) print('Features no: {0}\n'.format(selected_features.size)) k += 1 # Display results print('\n') print('Linear regression without feature selection:\n') print('- Training error: {0}'.format(Error_train.mean())) print('- Test error: {0}'.format(Error_test.mean())) print('- R^2 train: {0}'.format(
plt.xlim([0,len(solution.T)]) plt.subplot(1,7,2) solution = np.loadtxt("random_sampled_population_{0}.dat".format(i)) solution_means = np.mean(solution,axis=0) plt.bar([_ for _ in range(0,len(solution.T))],solution_means,color="k") plt.ylim([0,1]) plt.xlim([0,len(solution.T)]) plt.subplot(1,7,3) solution = np.loadtxt("training_data_{0}.dat".format(i)) plt.pcolor(solution,cmap="Greys") plt.xlim(0,genome_l) plt.subplot(1,7,4) solution = np.loadtxt("fitness_training_data_{0}.dat".format(i)) solution = solution.reshape(solution.shape[0],1) plt.pcolor(solution,cmap="Reds") plt.clim(low,high) # plt.xlim(0,105) plt.subplot(1,7,5) solution = np.loadtxt("population_{0}.dat".format(i)) plt.pcolor(solution,cmap="Greys") plt.xlim(0,genome_l) plt.subplot(1,7,6) solution = np.loadtxt("fitness_pop_{0}.dat".format(i)) solution = solution.reshape(solution.shape[0],1) plt.pcolor(solution,cmap="Reds") plt.clim(low,high) # plt.savefig("top_20_noise_0.5.png") # plt.subplot(1,7,7) # solution = np.loadtxt("fitness_pop_{0}.dat".format(i)) # fitnesses = np.loadtxt("fitness_pop_{0}.dat".format(0)) # fitnesses = fitnesses.reshape((fitnesses.shape[0],1))
def plotConn (include = ['all'], feature = 'strength', orderBy = 'gid', figSize = (10,10), groupBy = 'pop', groupByInterval = None, saveData = None, saveFig = None, showFig = True): ''' Plot network connectivity - include (['all',|'allCells','allNetStims',|,120,|,'E1'|,('L2', 56)|,('L5',[4,5,6])]): Cells to show (default: ['all']) - feature ('weight'|'delay'|'numConns'|'probability'|'strength'|'convergence'|'divergence'): Feature to show in connectivity matrix; the only features applicable to groupBy='cell' are 'weight', 'delay' and 'numConns'; 'strength' = weight * probability (default: 'strength') - groupBy ('pop'|'cell'|'y'|: Show matrix for individual cells, populations, or by other numeric tag such as 'y' (default: 'pop') - groupByInterval (int or float): Interval of groupBy feature to group cells by in conn matrix, e.g. 100 to group by cortical depth in steps of 100 um (default: None) - orderBy ('gid'|'y'|'ynorm'|...): Unique numeric cell property to order x and y axes by, e.g. 'gid', 'ynorm', 'y' (requires groupBy='cells') (default: 'gid') - figSize ((width, height)): Size of figure (default: (10,10)) - saveData (None|True|'fileName'): File name where to save the final data used to generate the figure; if set to True uses filename from simConfig (default: None) - saveFig (None|True|'fileName'): File name where to save the figure; if set to True uses filename from simConfig (default: None) - showFig (True|False): Whether to show the figure or not (default: True) - Returns figure handles ''' print('Plotting connectivity matrix...') cells, cellGids, netStimPops = getCellsInclude(include) # Create plot fig = figure(figsize=figSize) fig.subplots_adjust(right=0.98) # Less space on right fig.subplots_adjust(top=0.96) # Less space on top fig.subplots_adjust(bottom=0.02) # Less space on bottom h = axes() # Calculate matrix if grouped by cell if groupBy == 'cell': if feature in ['weight', 'delay', 'numConns']: connMatrix = zeros((len(cellGids), len(cellGids))) countMatrix = zeros((len(cellGids), len(cellGids))) else: print 'Conn matrix with groupBy="cell" only supports features= "weight", "delay" or "numConns"' return fig cellInds = {cell['gid']: ind for ind,cell in enumerate(cells)} # Order by if len(cells) > 0: if orderBy not in cells[0]['tags']: # if orderBy property doesn't exist or is not numeric, use gid orderBy = 'gid' elif not isinstance(cells[0]['tags'][orderBy], Number): orderBy = 'gid' if orderBy == 'gid': yorder = [cell[orderBy] for cell in cells] else: yorder = [cell['tags'][orderBy] for cell in cells] sortedGids = {gid:i for i,(y,gid) in enumerate(sorted(zip(yorder,cellGids)))} cellInds = sortedGids # Calculate conn matrix for cell in cells: # for each postsyn cell for conn in cell['conns']: if conn['preGid'] != 'NetStim' and conn['preGid'] in cellInds: if feature in ['weight', 'delay']: if conn['preGid'] in cellInds: connMatrix[cellInds[conn['preGid']], cellInds[cell['gid']]] += conn[feature] countMatrix[cellInds[conn['preGid']], cellInds[cell['gid']]] += 1 if feature in ['weight', 'delay']: connMatrix = connMatrix / countMatrix elif feature in ['numConns']: connMatrix = countMatrix # Calculate matrix if grouped by pop elif groupBy == 'pop': # get list of pops popsTemp = list(set([cell['tags']['popLabel'] for cell in cells])) pops = [pop for pop in sim.net.allPops if pop in popsTemp]+netStimPops popInds = {pop: ind for ind,pop in enumerate(pops)} # initialize matrices if feature in ['weight', 'strength']: weightMatrix = zeros((len(pops), len(pops))) elif feature == 'delay': delayMatrix = zeros((len(pops), len(pops))) countMatrix = zeros((len(pops), len(pops))) # calculate max num conns per pre and post pair of pops numCellsPop = {} for pop in pops: if pop in netStimPops: numCellsPop[pop] = -1 else: numCellsPop[pop] = len([cell for cell in cells if cell['tags']['popLabel']==pop]) maxConnMatrix = zeros((len(pops), len(pops))) if feature == 'convergence': maxPostConnMatrix = zeros((len(pops), len(pops))) if feature == 'divergence': maxPreConnMatrix = zeros((len(pops), len(pops))) for prePop in pops: for postPop in pops: if numCellsPop[prePop] == -1: numCellsPop[prePop] = numCellsPop[postPop] maxConnMatrix[popInds[prePop], popInds[postPop]] = numCellsPop[prePop]*numCellsPop[postPop] if feature == 'convergence': maxPostConnMatrix[popInds[prePop], popInds[postPop]] = numCellsPop[postPop] if feature == 'divergence': maxPreConnMatrix[popInds[prePop], popInds[postPop]] = numCellsPop[prePop] # Calculate conn matrix for cell in cells: # for each postsyn cell for conn in cell['conns']: if conn['preGid'] == 'NetStim': prePopLabel = conn['preLabel'] else: preCell = next((cell for cell in cells if cell['gid']==conn['preGid']), None) prePopLabel = preCell['tags']['popLabel'] if preCell else None if prePopLabel in popInds: if feature in ['weight', 'strength']: weightMatrix[popInds[prePopLabel], popInds[cell['tags']['popLabel']]] += conn['weight'] elif feature == 'delay': delayMatrix[popInds[prePopLabel], popInds[cell['tags']['popLabel']]] += conn['delay'] countMatrix[popInds[prePopLabel], popInds[cell['tags']['popLabel']]] += 1 # Calculate matrix if grouped by numeric tag (eg. 'y') elif groupBy in sim.net.allCells[0]['tags'] and isinstance(sim.net.allCells[0]['tags'][groupBy], Number): if not isinstance(groupByInterval, Number): print 'groupByInterval not specified' return # group cells by 'groupBy' feature (eg. 'y') in intervals of 'groupByInterval') cellValues = [cell['tags'][groupBy] for cell in cells] minValue = _roundFigures(groupByInterval * floor(min(cellValues) / groupByInterval), 3) maxValue = _roundFigures(groupByInterval * ceil(max(cellValues) / groupByInterval), 3) groups = arange(minValue, maxValue, groupByInterval) groups = [_roundFigures(x,3) for x in groups] print groups if len(groups) < 2: print 'groupBy %s with groupByInterval %s results in <2 groups'%(str(groupBy), str(groupByInterval)) return groupInds = {group: ind for ind,group in enumerate(groups)} # initialize matrices if feature in ['weight', 'strength']: weightMatrix = zeros((len(groups), len(groups))) elif feature == 'delay': delayMatrix = zeros((len(groups), len(groups))) countMatrix = zeros((len(groups), len(groups))) # calculate max num conns per pre and post pair of pops numCellsGroup = {} for group in groups: numCellsGroup[group] = len([cell for cell in cells if group <= cell['tags'][groupBy] < (group+groupByInterval)]) maxConnMatrix = zeros((len(groups), len(groups))) if feature == 'convergence': maxPostConnMatrix = zeros((len(groups), len(groups))) if feature == 'divergence': maxPreConnMatrix = zeros((len(groups), len(groups))) for preGroup in groups: for postGroup in groups: if numCellsGroup[preGroup] == -1: numCellsGroup[preGroup] = numCellsGroup[postGroup] maxConnMatrix[groupInds[preGroup], groupInds[postGroup]] = numCellsGroup[preGroup]*numCellsGroup[postGroup] if feature == 'convergence': maxPostConnMatrix[groupInds[prePop], groupInds[postGroup]] = numCellsPop[postGroup] if feature == 'divergence': maxPreConnMatrix[groupInds[preGroup], groupInds[postGroup]] = numCellsPop[preGroup] # Calculate conn matrix for cell in cells: # for each postsyn cell for conn in cell['conns']: if conn['preGid'] == 'NetStim': prePopLabel = -1 # maybe add in future else: preCell = next((cell for cell in cells if cell['gid']==conn['preGid']), None) if preCell: preGroup = _roundFigures(groupByInterval * floor(preCell['tags'][groupBy] / groupByInterval), 3) else: None postGroup = _roundFigures(groupByInterval * floor(cell['tags'][groupBy] / groupByInterval), 3) #print groupInds if preGroup in groupInds: if feature in ['weight', 'strength']: weightMatrix[groupInds[preGroup], groupInds[postGroup]] += conn['weight'] elif feature == 'delay': delayMatrix[groupInds[preGroup], groupInds[postGroup]] += conn['delay'] countMatrix[groupInds[preGroup], groupInds[postGroup]] += 1 # no valid groupBy else: print 'groupBy (%s) is not valid'%(str(groupBy)) return if groupBy != 'cell': if feature == 'weight': connMatrix = weightMatrix / countMatrix # avg weight per conn (fix to remove divide by zero warning) elif feature == 'delay': connMatrix = delayMatrix / countMatrix elif feature == 'numConns': connMatrix = countMatrix elif feature in ['probability', 'strength']: connMatrix = countMatrix / maxConnMatrix # probability if feature == 'strength': connMatrix = connMatrix * weightMatrix # strength elif feature == 'convergence': connMatrix = countMatrix / maxPostConnMatrix elif feature == 'divergence': connMatrix = countMatrix / maxPreConnMatrix imshow(connMatrix, interpolation='nearest', cmap='jet', vmin=nanmin(connMatrix), vmax=nanmax(connMatrix)) #_bicolormap(gap=0) # Plot grid lines hold(True) if groupBy == 'cell': # Make pretty step = int(len(cells)/10.0) base = 100 if step>100 else 10 step = int(base * floor(float(step)/base)) h.set_xticks(arange(0,len(cells),step)) h.set_yticks(arange(0,len(cells),step)) h.set_xticklabels(arange(0,len(cells),step)) h.set_yticklabels(arange(0,len(cells),step)) h.xaxis.set_ticks_position('top') xlim(-0.5,len(cells)-0.5) ylim(len(cells)-0.5,-0.5) clim(nanmin(connMatrix),nanmax(connMatrix)) elif groupBy == 'pop': for ipop, pop in enumerate(pops): plot(array([0,len(pops)])-0.5,array([ipop,ipop])-0.5,'-',c=(0.7,0.7,0.7)) plot(array([ipop,ipop])-0.5,array([0,len(pops)])-0.5,'-',c=(0.7,0.7,0.7)) # Make pretty h.set_xticks(range(len(pops))) h.set_yticks(range(len(pops))) h.set_xticklabels(pops) h.set_yticklabels(pops) h.xaxis.set_ticks_position('top') xlim(-0.5,len(pops)-0.5) ylim(len(pops)-0.5,-0.5) clim(nanmin(connMatrix),nanmax(connMatrix)) else: for igroup, group in enumerate(groups): plot(array([0,len(groups)])-0.5,array([igroup,igroup])-0.5,'-',c=(0.7,0.7,0.7)) plot(array([igroup,igroup])-0.5,array([0,len(groups)])-0.5,'-',c=(0.7,0.7,0.7)) # Make pretty h.set_xticks([i-0.5 for i in range(len(groups))]) h.set_yticks([i-0.5 for i in range(len(groups))]) h.set_xticklabels([int(x) if x>1 else x for x in groups]) h.set_yticklabels([int(x) if x>1 else x for x in groups]) h.xaxis.set_ticks_position('top') xlim(-0.5,len(groups)-0.5) ylim(len(groups)-0.5,-0.5) clim(nanmin(connMatrix),nanmax(connMatrix)) colorbar(label=feature, shrink=0.8) #.set_label(label='Fitness',size=20,weight='bold') xlabel('post') h.xaxis.set_label_coords(0.5, 1.06) ylabel('pre') title ('Connection '+feature+' matrix', y=1.08) #save figure data if saveData: figData = {'connMatrix': connMatrix, 'feature': feature, 'groupBy': groupBy, 'include': include, 'saveData': saveData, 'saveFig': saveFig, 'showFig': showFig} _saveFigData(figData, saveData, 'conn') # save figure if saveFig: if isinstance(saveFig, str): filename = saveFig else: filename = sim.cfg.filename+'_'+'conn.png' savefig(filename) # show fig if showFig: _showFigure() return fig
fig.add_subplot(gs[0, 0], xticks=Xt, xticklabels=Xtl, yticks=Yt, yticklabels=Ytl, title="2*c") mx = GcDisp.max() plt.imshow(GcDisp / mx, cmap=cmap, interpolation='none') plt.title( '{}\n(r:rectangular,p:polar)\nrPcG=P.c*G (/{:.2g})\n' .format(fnB, mx)) #plt.title('weighted by 2*c'); plt.colorbar(fraction=0.05, pad=0.04) plt.clim(0, 1) # fig.add_subplot(gs[1, 0], xticks=Xt, xticklabels=Xtl, yticks=Yt, yticklabels=Ytl, title="2*c") mx = G1Disp.max() plt.imshow(G1Disp / mx, cmap=cmap, interpolation='none') plt.title('rP1=P.1 (/{:.0f})'.format(mx)) #plt.title('weighted by 2*c'); plt.colorbar(fraction=0.05, pad=0.04) plt.clim(0, 1)
cMap = ListedColormap( ['lightslategrey', 'lightgray', 'silver', 'darkgray', 'dimgray']) plt.imshow(nr_stable_all, cmap=cMap, aspect='auto') plt.xticks(()) plt.yticks(()) for spine in plt.gca().spines.values(): spine.set_visible(False) cbar = plt.colorbar(ticks=np.array([0, 1, 2, 3, 4]), orientation='horizontal', aspect=5) cbar.ax.tick_params(size=0, labelsize=20, pad=-40) cbar.set_label(label='number of stable fixed points', fontsize=15, labelpad=10, weight='bold') plt.clim(-0.5, 4.5) if M == 14: cMap = ListedColormap(['lightgray', 'silver', 'darkgray', 'dimgray']) plt.imshow(nr_stable_all, cmap=cMap, aspect='auto') plt.xticks(()) plt.yticks(()) for spine in plt.gca().spines.values(): spine.set_visible(False) cbar = plt.colorbar(ticks=np.array([1, 2, 3, 4]), orientation='horizontal', aspect=5) cbar.ax.tick_params(size=0, labelsize=20, pad=-40) cbar.set_label(label='number of stable fixed points', fontsize=15, labelpad=10,
def confusionMatrixMulti(y_GT, y_pred, classesDict, ssh=False): """ @param y_GT: Ground truth array that can contain multiple labels for each data point @param y_pred: @param classesDict:i @param ssh: If True the plot will only be saved in the plotsTmp folder. If False, the plot will be displayed """ """ Sort classesDict to show labels in the CM: """ sortedTmp = sorted(classesDict.iteritems(), key=operator.itemgetter(1)) sortedLabels = [] for j in range(len(sortedTmp)): sortedLabels.append(sortedTmp[j][0]) n_classes = len(classesDict) cm = np.zeros((n_classes,n_classes)) for i in range(y_pred.shape[0]): # Only count points where prediction value is valid: if int(y_pred[i]) != -1: if y_pred[i] in y_GT[i,:]: """ If correct prediction made, add one on the corresponding diagonal element in the confusion matrix: """ cm[int(y_pred[i]),int(y_pred[i])] += 1 else: """ If not predicted correctly, divide by the number of ground truth labels for that point and split between corresponding non-diagonal elements: """ gtLabels = y_GT[i,:] labels = gtLabels[gtLabels != -1] #ground truth labels assigned to that point (only valid ones) n_labels = len(labels) #number of valid labels assigned weight = 1/float(n_labels) #value that will be added to each assigned (incorrect) label for label in labels: cm[int(label), int(y_pred[i])] += weight normalized = [] for row in cm: rowSum = sum(row) normalized.append([round(x/float(rowSum),2) for x in row]) """ Calculate precision: """ colSum = np.sum(cm, axis=0) precisions = [] for i in range(n_classes): tmpPrecision = cm[i,i] / float(colSum[i]) # print("Precision " + str(sortedLabels[i]) + ": " + str(tmpPrecision)) precisions.append(tmpPrecision) """ Calculate recall: """ recalls = [] for i in range(n_classes): recalls.append(normalized[i][i]) # print("Recall " + str(sortedLabels[i]) + ": " + str(normalized[i][i])) """ Calculate F1-score: """ F1s = [] for i in range(n_classes): tmpF1 = 2 * (precisions[i] * recalls[i]) / float(precisions[i] + recalls[i]) print("F1 " + str(sortedLabels[i]) + ": " + str(tmpF1)) F1s.append(tmpF1) width = len(cm) height = len(cm[0]) pl.figure(figsize=(15,15)) pl.matshow(normalized) pl.ylabel('True label') pl.xlabel('Predicted label') pl.xticks(range(len(sortedLabels)), sortedLabels) pl.yticks(range(len(sortedLabels)), sortedLabels) for x in xrange(width): for y in xrange(height): pl.annotate(str(normalized[x][y]), xy=(y, x), horizontalalignment='center', verticalalignment='center') # Force the min and max value, so that the colors will have the full range from 0 to 1: pl.clim(0,1) pl.colorbar() if ssh == False: pl.show() else: # When saving to disk, don't overwrite previous files, but instead # create new file with increased index: # "plotsTmp/CM_0.jpg" filename_beginning = "plotsTmp/CM_" cnt = 0 filename_extension = ".jpg" filename = filename_beginning + str(cnt) + filename_extension while os.path.isfile(filename): cnt += 1 filename = filename_beginning + str(cnt) + filename_extension fig = matplotlib.pyplot.gcf() fig.set_size_inches(15,15) pl.savefig(filename)
scatters = plt.scatter(x - xc, y - yc, c=binding_energy, s=300, cmap='coolwarm') cb = plt.colorbar(scatters, pad=0.01) cb.set_label(label="binding energy (eV)", size=45) cb.ax.tick_params(labelsize=35, direction='in') cb.set_ticks(np.linspace(-0.2, 1.6, 5, endpoint=True)) cbarlevels = ('-0.25', '0.25', '0.75', '1.25', '1.60') cb.set_ticklabels(cbarlevels) plt.clim(np.min((binding_energy)) - 0.1, np.max(binding_energy)) # lim of colorbar ax.tick_params(axis='x', pad=15) # distance between axis and text ax.tick_params(axis='y', pad=15) #-------------------------------------------------------------------- ax.spines['left'].set_linewidth(3.0) ax.spines['right'].set_linewidth(3.0) ax.spines['top'].set_linewidth(3.0) ax.spines['bottom'].set_linewidth(3.0) #=================================================================================== plt.minorticks_on() plt.tick_params(which='major', direction='in', width=3.0, length=12) # plt.tick_params(which='minor', direction='in', width=3.0, length=5) plt.xticks(fontsize=40) plt.yticks(fontsize=40)
def style_subplot(): plt.colorbar(fraction=0.046, pad=0.04) plt.clim([0, 0.75]) plt.gca().xaxis.grid(False) plt.gca().yaxis.grid(False)
matrix = numpy.array(m) plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1) ax.set_aspect('equal') plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.cool, extent=(0.5, 10.5, 10.5, 0.5)) plt.colorbar() plt.xticks(numpy.arange(1, 11)) plt.yticks(numpy.arange(1, 11)) plt.clim(100, 0) ax.xaxis.set_label_position('top') plt.title('Likelihood of Attacker Taking Territory in a Risk Dice Battle') plt.ylabel('Attacker Dice Count') plt.xlabel('Defender Dice Count') for i in range(10): for j in range(10): plt.text(j + 1, i + 1, str(matrix[i][j]) + "%", va='center', ha='center') plt.savefig('mygraph.png') plt.show()
def make_plot_gpd(WMO, sc, database, press, size, date): #def make_plot_gpd(WMO, sc = '', database = '', date = '', what = 'a', press = 85000, size = 10 ): # https://stackoverflow.com/questions/59417997/how-to-plot-a-list-of-shapely-points date_s = date date = np.datetime64(date) """ Loading from geopandas built-in methods """ world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) #world = gpd.read_file('Europe_coastline.shp') #world = world.query( 'continent == "Europe"' ) w = world.plot() WMO.plot(ax=w, facecolor="none", edgecolor="lightgray", lw=0.8) """ Saving coordinates to plot, and values """ points_lat, points_lon, anomaly, average = [], [], [], [] lat_stations, lon_stations = [], [] none_lat, none_lon = [], [] """ Loop over files in database """ db = os.listdir(database) for f in tqdm(db): if 'dat' in f: no_lat, no_lon = f.split('_')[3], f.split('_')[4] none_lat.append(float(no_lat)) none_lon.append(float(no_lon)) continue else: #loaded = xr.open_dataset(database + '/' + f).to_dataframe() #df_red = loaded.loc [ (loaded['date_time'] == date) & (loaded['z_coordinate'] == press ) loaded = xr.open_dataset(database + '/' + f) stations = loaded['longitude'].attrs stat = stations['stations'] if stat == 'None': pass else: for id in stat.split('_'): ID = str(np.bytes_(id)) station = sc.loc[sc['primary_id'] == ID] try: la = station['latitude'].values[0] lo = station['longitude'].values[0] if lo > 180: lo = -360 + lo lat_stations.append(la) lon_stations.append(lo) except: pass loaded = loaded.to_dataframe() df_red = loaded.loc[(loaded['date_time'] == date) & (loaded['z_coordinate'] == press)] points_lat.append(df_red['latitude'].values[0]) points_lon.append(df_red['longitude'].values[0]) an, an_bias = df_red['anomaly'].values[0], df_red[ 'anomaly_bias'].values[0] av, av_bias = df_red['average'].values[0], df_red[ 'average_bias'].values[0] if not np.isnan(av_bias): average.append(av_bias) else: average.append(av) if not np.isnan(an_bias): anomaly.append(an_bias) else: anomaly.append(an) #print(points_lon, points_lat, anomaly, average) if size == 10: marker_size = 75 elif size == 5: marker_size = 17 what = 'anomaly' if what == 'anomaly': w = world.plot() WMO.plot(ax=w, facecolor="none", edgecolor="lightgray", lw=0.8) plt.xlim([-180., 180.]) plt.ylim([-90., 90.]) plt.scatter(lon_stations, lat_stations, c='lime', s=0.8, marker='o') #plt.scatter( none_lon, none_lat , c= 'lightgray' , s = marker_size, marker = 'x' ) plt.scatter(points_lon, points_lat, c=anomaly, s=marker_size, marker='s', cmap='bwr', alpha=0.8, edgecolor='black', linewidths=0.3) cbar = plt.colorbar( fraction=0.03, pad=0.03 ) # pad moves bar to left-right, fractions is the length of the bar cbar.set_label('Temperature Anomaly over 20 years [K]') plt.clim(-5, 5) plt.title('Climate Studies using Radiosonde Data - ' + date_s + ', p=' + str(press)[:-2] + ' [hPa] ', fontsize=8) plt.savefig(out_dir + '/ClimateChange_' + date_s + '_' + what + '_' + '_plevel_' + str(press) + '_gridsize_' + str(size) + '.png', dpi=150, bbox_inches='tight') plt.close() print('Done +++', date, ' ', what) what = 'average' if what == 'average': w = world.plot() WMO.plot(ax=w, facecolor="none", edgecolor="lightgray", lw=0.8) plt.xlim([-180., 180.]) plt.ylim([-90., 90.]) plt.scatter(lon_stations, lat_stations, c='lime', s=1, marker='o') plt.scatter(points_lon, points_lat, c=average, s=marker_size, marker='s', cmap=CM, alpha=0.8, edgecolor='black', linewidths=0.3) cbar = plt.colorbar( fraction=0.03, pad=0.03 ) # pad moves bar to left-right, fractions is the length of the bar cbar.set_label('Average Temperature [K]') plt.clim(200, 330) plt.title('Climate Studies using Radiosonde Data - ' + date_s + ', p=' + str(press)[:-2] + ' [hPa] ', fontsize=9) plt.savefig(out_dir + '/ClimateChange_' + date_s + '_' + what + '_' + '_plevel_' + str(press) + '_gridsize_' + str(size) + '.png', dpi=150, bbox_inches='tight') plt.close() print('Done +++', date, ' ', what)
(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')
fig.add_subplot(gs[0, 0], xticks=Xt, xticklabels=Xtl, yticks=Yt, yticklabels=Ytl, title="2*c") mx = GcDisp.max() plt.imshow(GcDisp / mx, cmap=cmap, interpolation='none') plt.title( '{}\n(r:rectangular,p:polar)\nrPcG=P.c*G (/{:.2g})\n' .format(fnB, mx)) #plt.title('weighted by 2*c'); plt.colorbar(fraction=0.05, pad=0.04) plt.clim(-1, 1) # fig.add_subplot(gs[1, 0], xticks=Xt, xticklabels=Xtl, yticks=Yt, yticklabels=Ytl, title="2*c") mx = G1Disp.max() plt.imshow(G1Disp / mx, cmap=cmap, interpolation='none') plt.title('rP1=P.1 (/{:.0f})'.format(mx)) #plt.title('weighted by 2*c'); plt.colorbar(fraction=0.05, pad=0.04) plt.clim(-1, 1)
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')