def plot_slice_lon(lat_sl, data_cube, lats, lons, levs, u,w, mask, par='CZ', w_mag=2.0, **kwargs): ksp=kwargs.get('ksp', 0.05) bquiver=kwargs.get('bquiver', [0.1, 0.2]) my_lat=argsort(abs(lats-lat_sl))[0] print lats[my_lat] data=M.masked_where(M.array(mask[my_lat,:,:])<0.5, M.array(data_cube[par][my_lat,:,:])) wm=M.masked_where(M.array(mask[my_lat,:,:]) < 0.5, M.array(w[my_lat,:,:])) um=M.masked_where(M.array(mask[my_lat,:,:]) < 0.5, M.array(u[my_lat,:,:])) if par in ['diff']: data=M.masked_where(M.array(mask) < 0.5, M.array(data)) comp_levs=linspace(-1.,1., 30) levs_dict={'VR':linspace(-25,25,51), 'CZ': linspace(-8,64,10), 'TEST':linspace(((abs(data)+data)/2.0).min(), data.max(), 200), 'i_comp':comp_levs,'j_comp':comp_levs,'k_comp':comp_levs,'diff':linspace(-15,15,31), 'VE':linspace(-25,25,51)} titles_dict={'VR': 'Radial velocity m/s', 'CZ':'Corrected Reflectivity dBz', 'TEST':'TEST', 'i_comp':'i component','j_comp':'j component','k_comp':'k component', 'diff':'diff', 'VE':'Edited velocity'} xx,yy=meshgrid(lons,levs) #gca().xaxis.major.formatter.set_powerlimits((-10.,10.)) #contourf(xx, yy, transpose(data), levs_dict[par]) pcolor(xx, yy, transpose(data), vmin=levs_dict[par].min(), vmax=levs_dict[par].max()) #gca().xaxis.major.formatter.set_scientific(False) #print myaxis.formatter.limits colorbar() print "scale ", kwargs.get('qscale', 200) qq=quiver(xx, yy, transpose(um), transpose(wm*w_mag), scale=kwargs.get('qscale', 200)) quiverkey(qq, bquiver[0], bquiver[1]+2.*ksp, 10, '10 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) print bquiver[0], bquiver[1]+2.*ksp quiverkey(qq, bquiver[0], bquiver[1]+ksp, 5, '5 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) quiverkey(qq, bquiver[0], bquiver[1], 2, '2 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) xlabel('Longitude (degrees)') ylabel('Height (Metres)') if 'box' in kwargs.keys(): box=kwargs['box'] ax=gca() cr=ax.axis() ax.axis([box[0], box[1], cr[2], cr[3]]) return lats[my_lat]
def plot_slice_lat(lon_sl, data_cube, lats, lons, levs, v,w, mask, par='CZ', w_mag=2.0, **kwargs): ksp=kwargs.get('ksp', 0.05) bquiver=kwargs.get('bquiver', [0.95, 0.75]) my_lon=argsort(abs(lons-lon_sl))[0] print lons[my_lon] data=M.masked_where(M.array(mask[:,my_lon,:])<0.5, M.array(data_cube[par][:,my_lon,:])) wm=M.masked_where(M.array(mask[:,my_lon,:]) < 0.5, M.array(w[:,my_lon,:])) vm=M.masked_where(M.array(mask[:,my_lon,:]) < 0.5, M.array(v[:,my_lon,:])) if par in ['diff']: data=M.masked_where(M.array(mask) < 0.5, M.array(data)) comp_levs=linspace(-1.,1., 30) levs_dict={'VR':linspace(-25,25,51), 'CZ': linspace(-8,64,10), 'TEST':linspace(((abs(data)+data)/2.0).min(), data.max(), 200), 'i_comp':comp_levs,'j_comp':comp_levs,'k_comp':comp_levs,'diff':linspace(-15,15,31), 'VE':linspace(-25,25,51)} titles_dict={'VR': 'Radial velocity m/s', 'CZ':'Corrected Reflectivity dBz', 'TEST':'TEST', 'i_comp':'i component','j_comp':'j component','k_comp':'k component', 'diff':'diff', 'VE':'Edited velocity'} print data.shape print wm.shape print vm.shape print lats.shape print levs.shape xx,yy=meshgrid(lats,levs) #contourf(xx, yy, transpose(data), levs_dict[par]) pcolor(xx, yy, transpose(data), vmin=levs_dict[par].min(), vmax=levs_dict[par].max()) colorbar() qq=quiver(xx, yy, transpose(vm), transpose(wm*w_mag), scale=kwargs.get('qscale', 200)) quiverkey(qq, bquiver[0], bquiver[1]+2.*ksp, 10, '10 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) print bquiver[0], bquiver[1]+2.*ksp quiverkey(qq, bquiver[0], bquiver[1]+ksp, 5, '5 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) quiverkey(qq, bquiver[0], bquiver[1], 2, '2 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) xlabel('Latitude (degrees)') ylabel('Height (Metres)') if 'box' in kwargs.keys(): box=kwargs['box'] ax=gca() cr=ax.axis() ax.axis([box[2], box[3], cr[2], cr[3]]) return lons[my_lon]
def reconstruction_plot_w(mapobj, lats, lons, data_cube, lvl_num, parm, u, v,w, angs, mask, **kwargs): um=M.masked_where(M.array(mask) < 0.5, M.array(u)) vm=M.masked_where(M.array(mask) < 0.5, M.array(v)) mag=M.array(sqrt(u**2+v**2)) magm=M.masked_where(M.array(mask)<0.5, mag) fig_name=kwargs.get('fig_name', 'recon_'+parm+'_.png') longr, latgr=meshgrid(lons,lats) xx, yy = mapobj(longr, latgr) mapobj.drawmapboundary() mapobj.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstntcd_r','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) mapobj.drawmeridians(array([130,130.5, 131, 131.5, 132]), labels=[1,0,0,1]) mapobj.drawparallels(array([-13,-12.5,-12,-11.5,-11]), labels=[1,0,0,1]) data=data_cube[parm][:,:,lvl_num] if parm in ['diff']: data=M.masked_where(M.array(mask) < 0.5, M.array(data)) comp_levs=linspace(-1.,1., 30) levs_dict={'VR':linspace(-15,15,31), 'CZ': linspace(-8,64,10), 'TEST':linspace(((abs(data)+data)/2.0).min(), data.max(), 200), 'i_comp':comp_levs,'j_comp':comp_levs,'k_comp':comp_levs,'diff':linspace(-15,15,31)} titles_dict={'VR': 'Radial velocity m/s', 'CZ':'Corrected Reflectivity dBz', 'TEST':'TEST', 'i_comp':'i component','j_comp':'j component','k_comp':'k component', 'diff':'diff'} mapobj.contourf(xx,yy,data, levels=levs_dict[parm]) colorbar() #mapobj.quiver(xx,yy,u/sqrt(u**2+v**2),v/sqrt(u**2+v**2), scale=50) qq=mapobj.quiver(xx,yy,um,vm, scale=kwargs.get('qscale', 200)) quiverkey(qq, 0.1, 0.8, 10, '10 m/s', coordinates='figure') quiverkey(qq, 0.1, 0.75, 5, '5 m/s', coordinates='figure') quiverkey(qq, 0.1, 0.7, 2, '2 m/s', coordinates='figure') cobject=mapobj.contour(xx,yy,w, colors=['k'], levels=linspace(0,20,11)) fon = { 'fontname':'Tahoma', 'fontsize':10 } clabel(cobject, fmt="%d", **fon) mapobj.contour(xx,yy,angs, levels=[30.0, 150.0],colors=['r'])
def plot_soilw_from_gfs(file_name, cntr_lvl=None): file, vars = peek(file_name, show_vars=False) lon = vars['lon_3'].get_value() lat = vars['lat_3'].get_value() soilw_var = vars['SOILW_3_DBLY_10'] soilw = soilw_var.get_value() soilw_m = ma.masked_where(soilw == soilw_var._FillValue, soilw) for lvl_idx in range(len(soilw)): p.figure() if cntr_lvl is not None: p.contourf(lon, lat, soilw_m[lvl_idx], cntr_lvl) else: p.contourf(lon, lat, soilw_m[lvl_idx]) p.colorbar() # flip the y-axis p.ylim((lat[-1], lat[0])) p.ylabel('degrees North') p.xlabel('degrees East') lvl_bounds = vars['lv_DBLY5_l' + str(lvl_idx)] valid_when = soilw_var.initial_time valid_when = valid_when[3:5] + ' ' \ + cardinal_2_month(int(valid_when[:2])) + ' ' + valid_when[6:10] \ + ' ' + valid_when[12:17] + ' UTC' title_string = 'Volumetric soil moisture (fraction) valid at ' \ + '\n' + valid_when + ' ' \ + str(lvl_bounds[0]) + '-' + str(lvl_bounds[1]) + ' cm from GFS' p.title(title_string) return
def set_default_basemap(lon, lat, frame_width=5.): test = lon < 0. if True in test: # matplotlib expects 0-360 while WRF for example uses -180-180 delta = n.ones(lon.shape) delta *= 360 delta = ma.masked_where(lon > 0., delta) lon += delta.filled(fill_value=0) llcrnrlon=lon.min() - frame_width urcrnrlon=lon.max() + frame_width llcrnrlat=lat.min() - frame_width urcrnrlat=lat.max() + frame_width lon_0 = llcrnrlon + (urcrnrlon - llcrnrlon) / 2. lat_0 = llcrnrlat + (urcrnrlat - llcrnrlat) / 2. map = Basemap( llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat, urcrnrlon=urcrnrlon, urcrnrlat=urcrnrlat, resolution='l', projection='cyl', lon_0=lon_0, lat_0=lat_0 ) return map
def plot_data(xa,ya,za,fig,nfig,colorflag=False): cmap = pylab.cm.jet cmap.set_bad('w', 1.0) myfilter=N.array([[0.1,0.2,0.1],[0.2,0.8,0.2],[0.1,0.2,0.1]],'d') /2.0 if smooth: zout=convolve2d(za,myfilter,mode='same') else: zout=za zima = ma.masked_where(N.isnan(zout),zout) ax=fig.add_subplot(1,1,nfig) pc=ax.pcolormesh(xa,ya,zima,shading='interp',cmap=cmap) # working good! # pc=ax.imshow(zima,interpolation='bilinear',cmap=cmap) pc.set_clim(0.0,ctop) if colorflag: g=pylab.colorbar(pc,ticks=N.arange(0,ctop,cstep)) print g #g.ticks=None #gax.yaxis.set_major_locator(MultipleLocator(40)) #g.ticks(N.array([0,20,40,60,80])) return ax,g
def plot_data(xa, ya, za, fig, nfig, colorflag=False, convolveflag=False): cmap = pylab.cm.jet cmap.set_bad("w", 1.0) myfilter = N.array([[0.1, 0.2, 0.1], [0.2, 0.8, 0.2], [0.1, 0.2, 0.1]], "d") / 2.0 if convolveflag: zout = convolve2d(za, myfilter, mode="same") # to convolve, or not to convolve... else: zout = za zima = ma.masked_where(N.isnan(zout), zout) ax = fig.add_subplot(1, 1, nfig) pc = ax.pcolormesh(xa, ya, zima, shading="interp", cmap=cmap) # working good! # pc=ax.imshow(zima,interpolation='bilinear',cmap=cmap) pmin = zima.min() pmax = zima.max() # pmin=0 # pmax=700 # pc.set_clim(0.0,660.0) pc.set_clim(pmin, pmax) if colorflag: # g=pylab.colorbar(pc,ticks=N.arange(0,675,100)) g = pylab.colorbar(pc, ticks=N.arange(pmin, pmax, 100)) print g # g.ticks=None # gax.yaxis.set_major_locator(MultipleLocator(40)) # g.ticks(N.array([0,20,40,60,80])) return ax, g
def filterMetric(reader, timeFrame=None): """ @param reader is a MetricReader @param timeFrame is a tuple of start and end timestamps it can also be None (no time filter) or have one of the components (or both) as None (no filter on that respective side of time. @return two masked array""" import matplotlib.numerix.ma as MArray if timeFrame == None: timeFrame = [None, None] if timeFrame[0] == None: timeFrame[0] = 0 if timeFrame[1] == None: timeFrame[1] = sys.maxint timeVector = [] valueVector = [] for m in reader: if m.timestamp != None: if m.timestamp >= timeFrame[0] and m.timestamp <= timeFrame[1]: timeVector.append(m.timestamp) valueVector.append(m.value) timeVector = MArray.array(timeVector) valueVector = MArray.array(valueVector) valueVector_masked = MArray.masked_where(valueVector == None, valueVector) return [timeVector, valueVector_masked]
def plot_data(xa, ya, za, fig, nfig, colorflag=False): cmap = pylab.cm.jet cmap.set_bad('w', 1.0) myfilter = N.array([[0.1, 0.2, 0.1], [0.2, 0.8, 0.2], [0.1, 0.2, 0.1]], 'd') / 2.0 if smooth: zout = convolve2d(za, myfilter, mode='same') else: zout = za zima = ma.masked_where(N.isnan(zout), zout) ax = fig.add_subplot(1, 1, nfig) pc = ax.pcolormesh(xa, ya, zima, shading='interp', cmap=cmap) # working good! # pc=ax.imshow(zima,interpolation='bilinear',cmap=cmap) pc.set_clim(0.0, ctop) if colorflag: g = pylab.colorbar(pc, ticks=N.arange(0, ctop, cstep)) print g #g.ticks=None #gax.yaxis.set_major_locator(MultipleLocator(40)) #g.ticks(N.array([0,20,40,60,80])) return ax, g
def plot_data(xa,ya,za,fig,nfig,colorflag=False,convolveflag=False, clim=None): cmap = pylab.cm.jet cmap.set_bad('w', 1.0) myfilter=N.array([[0.1,0.2,0.1],[0.2,0.8,0.2],[0.1,0.2,0.1]],'d') /2.0 if convolveflag: zout=convolve2d(za,myfilter,mode='same') #to convolve, or not to convolve... else: zout=za zima = ma.masked_where(N.isnan(zout),zout) ax=fig.add_subplot(2,2,nfig) pc=ax.pcolormesh(xa,ya,zima,shading='interp',cmap=cmap) # working good! # pc=ax.imshow(zima,interpolation='bilinear',cmap=cmap) if clim is None: clim = zima.min(),zima.max() pc.set_clim(*clim) if colorflag: #g=pylab.colorbar(pc,ticks=N.arange(0,675,100)) g=pylab.colorbar(pc,ticks=N.arange(clim[0],clim[1],100)) print g #g.ticks=None #gax.yaxis.set_major_locator(MultipleLocator(40)) #g.ticks(N.array([0,20,40,60,80])) return ax,g
def reconstruction_plot_pcolor(lats, lons, data_cube, lvl_num, parm, u, v,w, angs, mask, **kwargs): ber_loc=[-12.4, 130.85] #location of Berrimah radar gp_loc=[-12.2492, 131.0444]#location of CPOL at Gunn Point box=kwargs.get('box',[130.0, 132.0, -13.0, -11.5])#box for the plot bquiver=kwargs.get('bquiver', [0.1, 0.75]) ksp=kwargs.get('ksp', 0.05) #Set up the map and projection mapobj= Basemap(projection='merc',lat_0=(box[2]+box[3])/2.0, lon_0=(box[0]+box[1])/2.0,llcrnrlat=box[2], llcrnrlon=box[0], urcrnrlat=box[3] , urcrnrlon=box[1], resolution='l',area_thresh=1., lat_ts=(box[2]+box[3])/2.0) #map.drawmapboundary() um=M.masked_where(M.array(mask) < 0.5, M.array(u)) vm=M.masked_where(M.array(mask) < 0.5, M.array(v)) mag=M.array(sqrt(u**2+v**2)) magm=M.masked_where(M.array(mask)<0.5, mag) fig_name=kwargs.get('fig_name', 'recon_'+parm+'_.png') longr, latgr=meshgrid(lons,lats) xx, yy = mapobj(longr, latgr) mapobj.drawmapboundary() mapobj.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstntcd_r','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) mapobj.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstqldmd_r', 'qcoast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) #mapobj.drawmeridians(array([130,130.5, 131, 131.5, 132]), labels=[1,0,0,1]) #mapobj.drawparallels(array([-13,-12.5,-12,-11.5,-11]), labels=[1,0,0,1]) data=M.masked_where(M.array(mask) < 0.5, M.array(data_cube[parm][:,:,lvl_num])) if parm in ['diff']: data=M.masked_where(M.array(mask) < 0.5, M.array(data)) comp_levs=linspace(-1.,1., 30) levs_dict={'VR':linspace(-25,25,51), 'CZ': linspace(-8,64,10), 'i_comp':comp_levs,'j_comp':comp_levs,'k_comp':comp_levs,'diff':linspace(-15,15,31), 'VE':linspace(-25,25,51)} titles_dict={'VR': 'Radial velocity m/s', 'CZ':'Corrected Reflectivity dBz', 'TEST':'TEST', 'i_comp':'i component','j_comp':'j component','k_comp':'k component', 'diff':'diff', 'VE':'Edited velocity'} mapobj.pcolor(xx,yy,data, vmin=levs_dict[parm].min(), vmax=levs_dict[parm].max()) colorbar() #mapobj.quiver(xx,yy,u/sqrt(u**2+v**2),v/sqrt(u**2+v**2), scale=50) qq=mapobj.quiver(xx,yy,um,vm, scale=kwargs.get('qscale', 200)) quiverkey(qq, bquiver[0], bquiver[1]+2.*ksp, 10, '10 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) print bquiver[0], bquiver[1]+2.*ksp quiverkey(qq, bquiver[0], bquiver[1]+ksp, 5, '5 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) quiverkey(qq, bquiver[0], bquiver[1], 2, '2 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) cobject=mapobj.contour(xx,yy,w, colors=['k'], levels=linspace(-10,10,6)) fon = { 'fontname':'Tahoma', 'fontsize':5 } clabel(cobject, fmt="%1.1f", **fon) mapobj.contour(xx,yy,angs, levels=[30.0, 150.0],colors=['r']) mapobj.readshapefile(getenv('HOME')+'/bom_mds/shapes/nt_coast','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) mapobj.drawmeridians(linspace(0,4,41)+130., labels=[1,0,0,1], fontsize=rcParams['xtick.labelsize']) mapobj.drawparallels(linspace(0,4,41)-15.0, labels=[1,0,0,1], fontsize=rcParams['ytick.labelsize']) return mapobj
def plot_slice_lon_hydro_sym_refl(lat_sl, data_cube,hydro_cube, hydro_bins, u,w, mask, par='CZ', w_mag=2.0, **kwargs): lats=hydro_cube['lats'] lons=hydro_cube['lons'] levs=hydro_cube['zar'] ksp=kwargs.get('ksp', 0.05) bquiver=kwargs.get('bquiver', [0.1, 0.2]) my_lat=argsort(abs(lats-lat_sl))[0] print lats[my_lat] data=M.masked_where(M.array(hydro_cube['CZ'][my_lat,:,:])<0.0, M.array(hydro_cube['CZ'][my_lat,:,:])) wm=M.masked_where(M.array(mask[my_lat,:,:]) < 0.5, M.array(w[my_lat,:,:])) um=M.masked_where(M.array(mask[my_lat,:,:]) < 0.5, M.array(u[my_lat,:,:])) if par in ['diff']: data=M.masked_where(M.array(mask) < 0.5, M.array(data)) comp_levs=linspace(-1.,1., 30) levs_dict={'VR':linspace(-15,15,31), 'CZ': linspace(-8,64,10), 'TEST':linspace(((abs(data)+data)/2.0).min(), data.max(), 200), 'i_comp':comp_levs,'j_comp':comp_levs,'k_comp':comp_levs,'diff':linspace(-15,15,31)} titles_dict={'VR': 'Radial velocity m/s', 'CZ':'Corrected Reflectivity dBz', 'TEST':'TEST', 'i_comp':'i component','j_comp':'j component','k_comp':'k component', 'diff':'diff'} xx,yy=meshgrid(lons,levs) plotting_syms={"unclassified":'k.', "Drizzle":'co', "Rain":'bo', "Dry LD snow":'cx', "Dry HD snow":'bx', "Melting Snow":'r+', "Dry Graupel":'bs', "Wet Graupel": 'rs', "Small Hail": 'cd', "Large Hail":'bD', "Rain + Hail":'g>'} for item in set(hydro_bins['bins'])-set(['unclassified']): plot(hydro_bins[item+"_lons"], hydro_bins[item+"_z"], plotting_syms[item]) legend(set(hydro_bins['bins'])-set(['unclassified'])) #gca().xaxis.major.formatter.set_powerlimits((-10.,10.)) #gca().xaxis.major.formatter.set_scientific(False) #print myaxis.formatter.limits #pcolor(xx_hydro, yy_hydro, transpose(hydro_data), vmin=-0.5, vmax=10.5, cmap=cmap_discretize(cm.jet, 11)) #colorbar() contour(xx, yy, transpose(data), levs_dict[par]) print "QSCALE ", kwargs.get('qscale', 200) qq=quiver(xx, yy, transpose(um), transpose(wm*w_mag), scale=kwargs.get('qscale', 200)) quiverkey(qq, bquiver[0], bquiver[1]+2.*ksp, 10, '10 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) print bquiver[0], bquiver[1]+2.*ksp quiverkey(qq, bquiver[0], bquiver[1]+ksp, 5, '5 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) quiverkey(qq, bquiver[0], bquiver[1], 2, '2 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) xlabel('Longitude (degrees)') ylabel('Height (Metres)') #item="Rain" if 'box' in kwargs.keys(): box=kwargs['box'] ax=gca() cr=ax.axis() ax.axis([box[0], box[1], cr[2], cr[3]]) return lats[my_lat]
def plot_slice_lon_hydro(lat_sl, data_cube, lats, lons, levs, hydro_cube, u,w, mask, par='CZ', w_mag=2.0, **kwargs): ksp=kwargs.get('ksp', 0.05) bquiver=kwargs.get('bquiver', [0.1, 0.2]) my_lat=argsort(abs(lats-lat_sl))[0] my_lat_hydro=argsort(abs(hydro_cube['lats']-lat_sl))[0] print lats[my_lat] data=M.masked_where(M.array(mask[my_lat,:,:])<0.5, M.array(data_cube[par][my_lat,:,:])) hydro_data=M.masked_where(classify[my_lat_hydro,:,:]==-9.0, classify[my_lat_hydro,:,:]) wm=M.masked_where(M.array(mask[my_lat,:,:]) < 0.5, M.array(w[my_lat,:,:])) um=M.masked_where(M.array(mask[my_lat,:,:]) < 0.5, M.array(u[my_lat,:,:])) if par in ['diff']: data=M.masked_where(M.array(mask) < 0.5, M.array(data)) comp_levs=linspace(-1.,1., 30) levs_dict={'VR':linspace(-15,15,31), 'CZ': linspace(-8,64,10), 'TEST':linspace(((abs(data)+data)/2.0).min(), data.max(), 200), 'i_comp':comp_levs,'j_comp':comp_levs,'k_comp':comp_levs,'diff':linspace(-15,15,31)} titles_dict={'VR': 'Radial velocity m/s', 'CZ':'Corrected Reflectivity dBz', 'TEST':'TEST', 'i_comp':'i component','j_comp':'j component','k_comp':'k component', 'diff':'diff'} xx,yy=meshgrid(lons,levs) xx_hydro, yy_hydro=meshgrid(hydro_cube['lons'], hydro_cube['zar']) #gca().xaxis.major.formatter.set_powerlimits((-10.,10.)) #gca().xaxis.major.formatter.set_scientific(False) #print myaxis.formatter.limits print "my_lat_hydro:", my_lat_hydro print hydro_cube['lats'][my_lat_hydro] pcolor(xx_hydro, yy_hydro, transpose(hydro_data), vmin=-0.5, vmax=10.5, cmap=cmap_discretize(cm.jet, 11)) myc=colorbar() myc.ax.text(0.0, 3.0, "HD snow") #yticks((0,1,2,3),("Uncl", "Dz", "Ra", "HD Sn")) contour(xx, yy, transpose(data), levs_dict[par]) qq=quiver(xx, yy, transpose(um), transpose(wm*w_mag), scale=kwargs.get('qscale', 200)) quiverkey(qq, bquiver[0], bquiver[1]+2.*ksp, 10, '10 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) print bquiver[0], bquiver[1]+2.*ksp quiverkey(qq, bquiver[0], bquiver[1]+ksp, 5, '5 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) quiverkey(qq, bquiver[0], bquiver[1], 2, '2 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']}) xlabel('Longitude (degrees)') ylabel('Height (Metres)') if 'box' in kwargs.keys(): box=kwargs['box'] ax=gca() cr=ax.axis() ax.axis([box[0], box[1], cr[2], cr[3]]) return lats[my_lat]
def plot_soilw(file_name, cntr_lvl=None): file, vars = peek(file_name, show_vars=False) lon = vars['lon'].get_value() lat = vars['lat'].get_value() soilw_var = vars['soil_mois'] soilw = soilw_var.get_value()[0] mask = n.zeros(soilw.shape, dtype=int) for lvl_idx in range(len(soilw)): mask[lvl_idx] = vars['sea_lnd_ice_mask'].get_value() soilw_m = ma.masked_where(mask == 0 , soilw) lvl_bounds = vars['soil_lvl'].get_value() valid_date = str(vars['valid_date'].get_value()[0]) valid_time = zfill(str(vars['valid_time'].get_value()[0]), 4) valid_when = valid_date[6:] + ' ' \ + cardinal_2_month(int(valid_date[4:6])) + ' ' \ + valid_date[0:4] \ + ' ' + valid_time[:2] + ':' \ + valid_time[2:] + ' UTC' m = set_default_basemap(lon,lat) # must plot using 2d lon and lat LON, LAT = p.meshgrid(lon,lat) #for lvl_idx in range(1): for lvl_idx in range(len(soilw)): p.figure() if cntr_lvl is not None: # let's not forget the scaling by the layer depth m.contourf(LON,LAT,soilw_m[lvl_idx]/lvl_bounds[lvl_idx], cntr_lvl) else: # let's not forget the scaling by the layer depth m.contourf(LON,LAT,soilw_m[lvl_idx]/lvl_bounds[lvl_idx]) m.drawcoastlines() m.drawmeridians(n.array(n.arange(lon.min(), lon.max() + a_small_number, 15.)), labels=[1,0,0,1]) m.drawparallels(n.array(n.arange(lat.min(), lat.max() + a_small_number, 15.)), labels=[1,0,0,1]) p.colorbar(orientation='horizontal', shrink=0.7, fraction=0.02, pad=0.07, aspect=50) if lvl_idx == 0: title_string = 'Volumetric soil moisture (fraction) valid at ' \ + '\n' + valid_when + ' ' \ + '0' \ + '-' + str(int(round(lvl_bounds[lvl_idx]*100))) + ' cm' \ + ' from LAPS' else: title_string = 'Volumetric soil moisture (fraction) valid at ' \ + '\n' + valid_when + ' ' \ + str(int(round(lvl_bounds[lvl_idx-1]*100))) \ + '-' + str(int(round(lvl_bounds[lvl_idx]*100))) + ' cm' \ + ' from LAPS' p.title(title_string) return
def plot_cappi(data,parm,lnum, **kwargs): x=data['xar'] y=data['yar'] radar_loc=data['radar_loc'] radar_name=kwargs.get('radar_name', data['radar_name']) fig_name=kwargs.get('fig_name', 'cappi_'+parm+'_.png') f=figure() Re=6371.0*1000.0 rad_at_radar=Re*sin(pi/2.0 -abs(radar_loc[0]*pi/180.0))#ax_radius(float(lat_cpol), units='degrees') lons=radar_loc[1]+360.0*(x-data['displacement'][0])/(rad_at_radar*2.0*pi) lats=radar_loc[0] + 360.0*(y-data['displacement'][1])/(Re*2.0*pi) def_loc_dict={'lat_0':lats.mean(), 'lon_0':lons.mean(),'llcrnrlat':lats.min(), 'llcrnrlon':lons.min(), 'urcrnrlat':lats.max() , 'urcrnrlon':lons.max(), 'lat_ts':lats.mean()} loc_dict=kwargs.get('loc_dict', def_loc_dict) #print 'Here' map= Basemap(projection='merc', resolution='l',area_thresh=1., **loc_dict) longr, latgr=meshgrid(lons,lats) xx, yy = map(longr, latgr) #print 'there' map.drawmapboundary() darwin_loc=[-12.5, 130.85] disp_from_darwin=mathematics.corner_to_point(darwin_loc, radar_loc) dist_from_darwin=sqrt(disp_from_darwin[0]**2+disp_from_darwin[1]**2) if dist_from_darwin < 500.*1000.: map.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstntcd_r','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) else: map.drawcoastlines() map.drawmeridians(array([129,130,131,132,133]), labels=[1,0,0,1]) map.drawparallels(array([-14,-13,-12,-11,-10]), labels=[1,0,0,1]) comp_levs=linspace(-1.,1., 30) #print 'everywhere' levs_dict={'VR':linspace(-15,15,31), 'CZ': linspace(-8,64,10), 'PH': linspace(0,185,255), "RH": linspace(0,1.5,16), "SW":linspace(0, 5, 11), "ZD":linspace(-10,10,21), 'VE':linspace(-30,30,31), 'TI':linspace(-30,30,31)} #print 'or here?' titles_dict={'VR': 'Velocity m/s', 'CZ':'Corrected Reflectivity dBz', 'PH': 'Differential Prop Phase (degrees)', 'RH':'Correlation Co-ef', 'SW':'Spectral Width (m/s)', 'ZD':'Differentail Reflectivity dBz', 'VE':'Edited Velocity (m/s)', 'TI':'Simualated winds,(m/s)'} #print parm if 'mask' in kwargs.keys(): mask=kwargs['mask'][:,:,lnum] mdata=M.masked_where(M.array(mask) < 0.5, M.array(data[parm][:,:,lnum])) map.contourf(xx,yy,mdata, levels=levs_dict[parm]) else: map.contourf(xx,yy,data[parm][:,:,lnum], levels=levs_dict[parm]) colorbar() if 'angs' in kwargs.keys(): map.contour(xx,yy,kwargs['angs'], levels=[30.0, 150.0],colors=['r']) p=data['date'] dtstr='%(#1)02d-%(#2)02d-%(#3)04d %(#4)02d%(#5)02dZ ' %{"#1":p.day, "#2":p.month, "#3":p.year, "#4":p.hour, '#5':p.minute} title(radar_name+' '+dtstr+titles_dict[parm]) savefig(getenv('HOME')+'/bom_mds/output/'+fig_name) close(f)
def plot_soilw_from_gfs(file_name, cntr_lvl=None): file, vars = peek(file_name, show_vars=False) lon = vars["lon_3"].get_value() lat = vars["lat_3"].get_value() soilw_var = vars["SOILW_3_DBLY_10"] soilw = soilw_var.get_value() soilw_m = ma.masked_where(soilw == soilw_var._FillValue, soilw) for lvl_idx in range(len(soilw)): p.figure() if cntr_lvl is not None: p.contourf(lon, lat, soilw_m[lvl_idx], cntr_lvl) else: p.contourf(lon, lat, soilw_m[lvl_idx]) p.colorbar() # flip the y-axis p.ylim((lat[-1], lat[0])) p.ylabel("degrees North") p.xlabel("degrees East") lvl_bounds = vars["lv_DBLY5_l" + str(lvl_idx)] valid_when = soilw_var.initial_time valid_when = ( valid_when[3:5] + " " + cardinal_2_month(int(valid_when[:2])) + " " + valid_when[6:10] + " " + valid_when[12:17] + " UTC" ) title_string = ( "Volumetric soil moisture (fraction) valid at " + "\n" + valid_when + " " + str(lvl_bounds[0]) + "-" + str(lvl_bounds[1]) + " cm from GFS" ) p.title(title_string) return
#!/usr/bin/env python from pylab import * import matplotlib.numerix.ma as ma N = 100 r0 = 0.6 x = 0.9 * rand(N) y = 0.9 * rand(N) area = pi * (10 * rand(N)) ** 2 # 0 to 10 point radiuses c = sqrt(area) r = sqrt(x * x + y * y) area1 = ma.masked_where(r < r0, area) area2 = ma.masked_where(r >= r0, area) scatter(x, y, s=area1, marker="^", c=c, hold="on") scatter(x, y, s=area2, marker="o", c=c) # Show the boundary between the regions: theta = arange(0, pi / 2, 0.01) plot(r0 * cos(theta), r0 * sin(theta)) show()
#!/bin/env python ''' Plot lines with points masked out. This would typically be used with gappy data, to break the line at the data gaps. ''' import matplotlib.numerix.ma as M from pylab import * x = M.arange(0, 2 * pi, 0.02) y = M.sin(x) y1 = sin(2 * x) y2 = sin(3 * x) ym1 = M.masked_where(y1 > 0.5, y1) ym2 = M.masked_where(y2 < -0.5, y2) lines = plot(x, y, 'r', x, ym1, 'g', x, ym2, 'bo') setp(lines[0], linewidth=4) setp(lines[1], linewidth=2) setp(lines[2], markersize=10) legend(('No mask', 'Masked if > 0.5', 'Masked if < -0.5'), loc='upper right') title('Masked line demo') savefig('test.svg') #savefig('test.ps') show()
return size def parse_data(infile, size): """ Populate matrix with data from infile """ m = numpy.zeros((size,size)) for (lineno, line) in enumerate(infile.readlines()): try : (pre, post, val) = string.split(line) except ValueError : print "Malformed data in line %s: %s" % (lineno, line) return except Exception, e: raise e m[(int(pre), int(post))] = float(val) return M.masked_where(m == 0, m) def color_map(): """ Return colour map using blues for negative values and reds for positive values """ cdict = { 'red': ((0.0, 0.0, 0.0), (0.5, 0.0, 0.1), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.3, 0.3), (0.5, 0.0, 0.0), (1.0, 0.3, 0.3)), 'blue': ((0.0, 1.0, 1.0), (0.5, 0.1, 0.0), (1.0, 0.0, 0.0))}
import matplotlib.numerix as nx from pylab import figure,show import matplotlib.numerix.ma as ma from matplotlib import cm, colors n = 56 x = linspace(-1.5,1.5,n) X,Y = meshgrid(x,x); Qx = nx.cos(Y) - nx.cos(X) Qz = nx.sin(Y) + nx.sin(X) Qx = (Qx + 1.1) Z = nx.sqrt(X**2 + Y**2)/5; Z = (Z - nx.mlab.amin(Z)) / (nx.mlab.amax(Z) - nx.mlab.amin(Z)) # The color array can include masked values: Zm = ma.masked_where(nx.fabs(Qz) < 0.5*nx.mlab.amax(Qz), Z) fig = figure() ax = fig.add_subplot(121) ax.pcolormesh(Qx,Qz,Z) ax.set_title('Without masked values') ax = fig.add_subplot(122) # You can control the color of the masked region: #cmap = cm.jet #cmap.set_bad('r', 1.0) #ax.pcolormesh(Qx,Qz,Zm, cmap=cmap) # Or use the default, which is transparent: col = ax.pcolormesh(Qx,Qz,Zm) ax.set_title('With masked values')
# use masked arrays to plot a line with different colors by y-value import matplotlib.numerix.ma as ma from matplotlib.numerix import logical_or from pylab import plot, show, arange, sin, pi t = arange(0.0, 2.0, 0.01) s = sin(2 * pi * t) upper = 0.77 lower = -0.77 supper = ma.masked_where(s < upper, s) slower = ma.masked_where(s > lower, s) smiddle = ma.masked_where(logical_or(s < lower, s > upper), s) plot(t, slower, 'r', t, smiddle, 'b', t, supper, 'g') show()
import matplotlib.numerix as nx from pylab import figure, show import matplotlib.numerix.ma as ma from matplotlib import cm, colors n = 56 x = linspace(-1.5, 1.5, n) X, Y = meshgrid(x, x) Qx = nx.cos(Y) - nx.cos(X) Qz = nx.sin(Y) + nx.sin(X) Qx = (Qx + 1.1) Z = nx.sqrt(X**2 + Y**2) / 5 Z = (Z - nx.mlab.amin(Z)) / (nx.mlab.amax(Z) - nx.mlab.amin(Z)) # The color array can include masked values: Zm = ma.masked_where(nx.fabs(Qz) < 0.5 * nx.mlab.amax(Qz), Z) fig = figure() ax = fig.add_subplot(121) ax.pcolormesh(Qx, Qz, Z) ax.set_title('Without masked values') ax = fig.add_subplot(122) # You can control the color of the masked region: #cmap = cm.jet #cmap.set_bad('r', 1.0) #ax.pcolormesh(Qx,Qz,Zm, cmap=cmap) # Or use the default, which is transparent: col = ax.pcolormesh(Qx, Qz, Zm) ax.set_title('With masked values') show()
if cowid != lastcowid: #print 'Cowid changed from %s to %s' % ( lastcowid, cowid ) _cowid = lastcowid _lacnum = lastlacnum else: _cowid = cowid _lacnum = lacnum if trait != lasttrait: #print 'Trait changed from %s to %s' % ( lasttrait, trait ) _trait = lasttrait else: _trait = trait # We're processing a new animal plotdim = M.array(dim) plottd_ = M.array(tdy) plottdy = M.masked_where(plottd_ == threshold, plottd_) plotla_ = M.array(lac) plotlac = M.masked_where(plotla_ == -2.0, plotla_) plotst_ = M.array(std) plotstd = M.masked_where(plotst_ == threshold, plotst_) plotdb_ = M.array(dbp) plotdbp = M.masked_where(plotdb_ == threshold, plotdb_) plotde_ = M.array(dev) plotdev = M.masked_where(plotde_ == threshold, plotde_) maxdim = plotdim.max() if lbtokg == 1 and int(_trait) < 4: plottdy = plottdy / 2.2 plotlac = plotlac / 2.2 plotstd = plotstd / 2.2 stdsum = stdsum / 2.2
#!/bin/env python ''' Plot lines with points masked out. This would typically be used with gappy data, to break the line at the data gaps. ''' import matplotlib.numerix.ma as M from pylab import * x = M.arange(0, 2*pi, 0.02) y = M.sin(x) y1 = sin(2*x) y2 = sin(3*x) ym1 = M.masked_where(y1 > 0.5, y1) ym2 = M.masked_where(y2 < -0.5, y2) lines = plot(x, y, 'r', x, ym1, 'g', x, ym2, 'bo') setp(lines[0], linewidth = 4) setp(lines[1], linewidth = 2) setp(lines[2], markersize = 10) legend( ('No mask', 'Masked if > 0.5', 'Masked if < -0.5') , loc = 'upper right') title('Masked line demo') savefig('test.svg') #savefig('test.ps') show()
#!/usr/bin/env python from pylab import * import matplotlib.numerix.ma as ma N = 100 r0 = 0.6 x = 0.9 * rand(N) y = 0.9 * rand(N) area = pi * (10 * rand(N))**2 # 0 to 10 point radiuses c = sqrt(area) r = sqrt(x * x + y * y) area1 = ma.masked_where(r < r0, area) area2 = ma.masked_where(r >= r0, area) scatter(x, y, s=area1, marker='^', c=c, hold='on') scatter(x, y, s=area2, marker='o', c=c) # Show the boundary between the regions: theta = arange(0, pi / 2, 0.01) plot(r0 * cos(theta), r0 * sin(theta)) show()
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = 10 * (Z2 - Z1) # difference of Gaussians # Set up a colormap: palette = cm.gray palette.set_over('r', 1.0) palette.set_under('g', 1.0) palette.set_bad('b', 1.0) # Alternatively, we could use # palette.set_bad(alpha = 0.0) # to make the bad region transparent. This is the default. # If you comment out all the palette.set* lines, you will see # all the defaults; under and over will be colored with the # first and last colors in the palette, respectively. Zm = ma.masked_where(Z > 1.2, Z) # By setting vmin and vmax in the norm, we establish the # range to which the regular palette color scale is applied. # Anything above that range is colored based on palette.set_over, etc. im = imshow(Zm, interpolation='bilinear', cmap=palette, norm=colors.normalize(vmin=-1.0, vmax=1.0, clip=False), origin='lower', extent=[-3, 3, -3, 3]) title('Green=low, Red=high, Blue=bad') colorbar(im, extend='both', shrink=0.8) show()
def draw(self): if len(self._series) == 0 \ or len(self._data) == 0 \ or len(self.keys) == 0: return Chart.draw(self) (fig, canvas, ax) = self.prepare() w, h = float(self.get('width')), float(self.get('height')) dpif = float(self.get('dpi')) / 72 axrect = ax.get_position().get_points() nkeys = len(self.keys) cmap = cm.Paired tickfont = self.font wlabels = nkeys*tickfont.get_size()*dpif if wlabels / w > (axrect[1, 0]-axrect[0, 0]) / 1.2: tickfont = tickfont.copy() tickfont.set_size(max(5, w * (axrect[1, 0]-axrect[0, 0]) / nkeys / 1.2)) maxname = max(len(i['name']) for i in self.keys) maxname = 0.6*(1 + maxname)*tickfont.get_size()*dpif/h cbartitle = 1.2*self.afont.get_size()*dpif/h; ax.set_position((axrect[0, 0], maxname, axrect[1, 0]-axrect[0, 0]-cbartitle, axrect[1, 1]-maxname)) valuef = self.get('yAxisValue') nbins = self.get('yAxisBins') xmax = max(nkeys, 16) x, y = numpy.meshgrid(numpy.arange(xmax+1), [valuef(bin) for bin in xrange(0, nbins+1)]) c = numpy.zeros((nbins+1, xmax)) for i in xrange(0, nkeys): item = self.keys[i] d = self._data[item['key']] hmin = hmax = None for hbin, n in d.iteritems(): c[hbin, i] = n if hmin == None: hmin = valuef(hbin) hmax = valuef(hbin+1) else: hmin = min(hmin, valuef(hbin)) hmax = max(hmax, valuef(hbin+1)) if hmin != None: ax.axhline(hmin, float(i)/xmax, float(i+1)/xmax, color="#000000", linewidth=.95) ax.axhline(hmax, float(i)/xmax, float(i+1)/xmax, color="#000000", linewidth=.95) map = ax.pcolor(x, y, ma.masked_where(c == 0, c), shading='flat', cmap=cmap) cb = fig.colorbar(map, aspect=50, fraction=0.025, pad=0.01) cb.ax.set_ylabel(self.get("yScaleAxisTitle", ""), fontproperties=self.afont) setp(cb.ax.get_yticklabels(), fontproperties=self.font) setp(ax.get_xticklines(), markeredgewidth=0, zorder=4.0) ax.set_xticks(numpy.arange(0, xmax, 1) + 0.5) ax.set_xticklabels([x['name'] for x in self.keys], rotation='vertical', horizontalalignment='center', fontproperties=tickfont) ax.set_xlim(xmin=0, xmax=xmax) ax.set_ylim(ymin=valuef(0), ymax=valuef(nbins+1)) return self.save(fig, canvas)
def plot_slice( ordinate, data, abscissa = None, abscissa_label = None, land_mask = None, cntr_lvl = None, wind_vector = None, log_scale = False, pressure = True, ordinate_quiv_skip = 1, abscissa_quiv_skip = 3, xmin = None, xmax = None, ymin = None, ymax = None, significant_digits = 0, title_string = 'N/A', file_name = None, dpi = 100 ): ''' plot a slice Usage: >>> plot_vertical_slice(ordinate, data, abscissa, wind_vector) where ordinate is either pressure or height. By default pressure is assumed data is a vertical slice abscissa is either 1D or 2D ''' if log_scale: ordinate = n.log10(ordinate) # if the abscissa is not supplied than simply use the record numbers if abscissa is None: x = n.arange(1,data.shape[1]+1) abscissa = n.zeros(data.shape) for y_idx in range(data.shape[0]): abscissa[y_idx] = x if cntr_lvl is not None: cset = p.contourf(abscissa, ordinate, data, cntr_lvl) else: cset = p.contourf(abscissa, ordinate, data) p.xlabel('record number') else: # let's handle 1D abscissa arrays if len(abscissa.shape) == 1: dummy = n.zeros(data.shape) for lvl_idx in range(data.shape[0]): dummy[lvl_idx] = abscissa abscissa = dummy del dummy if cntr_lvl is not None: cset = p.contourf(abscissa, ordinate, data, cntr_lvl) else: cset = p.contourf(abscissa, ordinate, data) if abscissa_label: p.xlabel(abscissa_label) else: p.xlabel('N/A') if wind_vector: p.quiver(abscissa[::ordinate_quiv_skip,::abscissa_quiv_skip], ordinate[::ordinate_quiv_skip,::abscissa_quiv_skip], wind_vector[0][::ordinate_quiv_skip,::abscissa_quiv_skip], wind_vector[1][::ordinate_quiv_skip,::abscissa_quiv_skip]) if land_mask is not None: land = ma.masked_where(land_mask == 2,ordinate[0]) p.plot(abscissa[0], land, color=(0.59,0.29,0.0), linewidth=2.) # if you also want to plot the ocean uncomment the following lines #if log_scale: # ocean = ma.masked_where(land_mask == 1, n.log10(1013.25)) #else: # ocean = ma.masked_where(land_mask == 1, 1013.25) #p.plot(abscissa[0], ocean, color=(0.0,0.0,1.0), linewidth=2.) if pressure: # I am assuming pressure will be expressed in hPa yticks_location = n.arange(1000.,99.,-100.) if log_scale: p.yticks(n.log10(yticks_location), [str(int(e)) for e in yticks_location]) p.ylabel('log10 of pressure') for e in n.log10(yticks_location): p.axhline(e,linestyle='--',color=(0.7,0.7,0.7)) # the -5. is there to create a bit of a top margin if ordinate.max() > n.log10(1013.25): cheat_ymin = ordinate.max() else: cheat_ymin = n.log10(1013.25 + 5.) p.ylim(ymin=cheat_ymin, ymax=n.log10(10**ordinate.min() - 5.)) else: p.yticks( yticks_location, [str(int(e)) for e in yticks_location]) p.ylabel('pressure (hPa)') for e in yticks_location: p.axhline(e,linestyle='--',color=(0.7,0.7,0.7)) # the -25. is there to create a bit of a top margin if ordinate.max() > 1013.25: cheat_ymin = ordinate.max() else: cheat_ymin = 1013.25 + 10. p.ylim(ymin=cheat_ymin, ymax=ordinate.min() - 25.) # p.ylim(ymin=ordinate.max(), ymax=ordinate.min() - 25.) # if any of the axes boundaries have been given explicitly, we'll # them if log_scale: if xmin is not None: p.xlim(xmin=n.log10(xmin)) if xmax is not None: p.xlim(xmax=n.log10(xmax)) if ymin is not None: p.ylim(ymin=n.log10(ymin)) if ymax is not None: p.ylim(ymax=n.log10(ymax)) else: if xmin is not None: p.xlim(xmin=xmin) if xmax is not None: p.xlim(xmax=xmax) if ymin is not None: p.ylim(ymin=ymin) if ymax is not None: p.ylim(ymax=ymax) else: print 'I assume you are trying to plot in z coordinate: ' \ + 'sorry not implemented yet' format = '%.'+ str(significant_digits) + 'f' p.colorbar(cset, orientation='horizontal', shrink=0.7, #fraction=0.02, pad=0.095, aspect=70, fraction=0.02, pad=0.1, aspect=70, format = format) p.title(title_string) if file_name: p.savefig(file_name,dpi=dpi) p.close()
def plot_head_topography(topography, sensorlocations, plotsensors=False, resolution=51, masked=True, plothead=True, plothead_kwargs=None, **kwargs): """Plot distribution to a head surface, derived from some sensor locations. The sensor locations are first projected onto the best fitting sphere and finally projected onto a circle (by simply ignoring the z-axis). Parameters ---------- topography : array A vector of some values corresponding to each sensor. sensorlocations : (nsensors x 3) array 3D coordinates of each sensor. The order of the sensors has to match with the `topography` vector. plotsensors : bool If True, sensor will be plotted on their projected coordinates. No sensor are shown otherwise. plothead : bool If True, a head outline is plotted. plothead_kwargs : dict Additional keyword arguments passed to `plot_head_outline()`. resolution : int Number of surface samples along both x and y-axis. masked : bool If True, all surface sample extending to head outline will be masked. **kwargs All additional arguments will be passed to `pylab.imshow()`. Returns ------- (map, head, sensors) The corresponding matplotlib objects are returned if plotted, ie. if plothead is set to `False`, `head` will be `None`. map The colormap that makes the actual plot, a matplotlib.image.AxesImage instance. head What is returned by `plot_head_outline()`. sensors The dots marking the electrodes, a matplotlib.lines.Line2d instance. """ # give sane defaults if plothead_kwargs is None: plothead_kwargs = {} # error function to fit the sensor locations to a sphere def err(params): r, cx, cy, cz = params return (sensorlocations[:, 0] - cx) ** 2 \ + (sensorlocations[:, 1] - cy) ** 2 \ + (sensorlocations[:, 2] - cz) ** 2 \ - r ** 2 # initial guess of sphere parameters (radius and center) params = (1, 0, 0, 0) # do fit (r, cx, cy, cz), stuff = leastsq(err, params) # size of each square ssh = float(r) / resolution # half-size ss = ssh * 2.0 # full-size # Generate a grid and interpolate using the griddata module x = np.arange(cx - r, cx + r, ss) + ssh y = np.arange(cy - r, cy + r, ss) + ssh x, y = pl.meshgrid(x, y) # project the sensor locations onto the sphere sphere_center = np.array((cx, cy, cz)) sproj = sensorlocations - sphere_center sproj = r * sproj / np.c_[np.sqrt(np.sum(sproj ** 2, axis=1))] sproj += sphere_center # fit topology onto xy projection of sphere topo = griddata(sproj[:, 0], sproj[:, 1], np.ravel(np.array(topography)), x, y) # mask values outside the head if masked: notinhead = np.greater_equal((x - cx) ** 2 + (y - cy) ** 2, (1.0 * r) ** 2) topo = M.masked_where(notinhead, topo) # show surface map = pl.imshow(topo, origin="lower", extent=(-r, r, -r, r), **kwargs) pl.axis('off') if plothead: # plot scaled head outline head = plot_head_outline(scale=r, shift=(cx/2.0, cy/2.0), **plothead_kwargs) else: head = None if plotsensors: # plot projected sensor locations # reorder sensors so the ones below plotted first # TODO: please fix with more elegant solution zenum = [x[::-1] for x in enumerate(sproj[:, 2].tolist())] zenum.sort() indx = [ x[1] for x in zenum ] sensors = pl.plot(sproj[indx, 0] - cx/2.0, sproj[indx, 1] - cy/2.0, 'wo') else: sensors = None return map, head, sensors
# use masked arrays to plot a line with different colors by y-value import matplotlib.numerix.ma as ma from matplotlib.numerix import logical_or from pylab import plot, show, arange, sin, pi t = arange(0.0, 2.0, 0.01) s = sin(2*pi*t) upper = 0.77 lower = -0.77 supper = ma.masked_where(s < upper, s) slower = ma.masked_where(s > lower, s) smiddle = ma.masked_where(logical_or(s<lower, s>upper), s) plot(t, slower, 'r', t, smiddle, 'b', t, supper, 'g') show()
X, Y = meshgrid(x, y) Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = 10 * (Z2-Z1) # difference of Gaussians # Set up a colormap: palette = cm.gray palette.set_over('r', 1.0) palette.set_under('g', 1.0) palette.set_bad('b', 1.0) # Alternatively, we could use # palette.set_bad(alpha = 0.0) # to make the bad region transparent. This is the default. # If you comment out all the palette.set* lines, you will see # all the defaults; under and over will be colored with the # first and last colors in the palette, respectively. Zm = ma.masked_where(Z > 1.2, Z) # By setting vmin and vmax in the norm, we establish the # range to which the regular palette color scale is applied. # Anything above that range is colored based on palette.set_over, etc. im = imshow(Zm, interpolation='bilinear', cmap=palette, norm = colors.normalize(vmin = -1.0, vmax = 1.0, clip = False), origin='lower', extent=[-3,3,-3,3]) title('Green=low, Red=high, Blue=bad') colorbar(im, extend='both', shrink=0.8) show()
def plot_head_topography(topography, sensorlocations, plotsensors=False, resolution=51, masked=True, plothead=True, plothead_kwargs=None, **kwargs): """Plot distribution to a head surface, derived from some sensor locations. The sensor locations are first projected onto the best fitting sphere and finally projected onto a circle (by simply ignoring the z-axis). Parameters ---------- topography : array A vector of some values corresponding to each sensor. sensorlocations : (nsensors x 3) array 3D coordinates of each sensor. The order of the sensors has to match with the `topography` vector. plotsensors : bool If True, sensor will be plotted on their projected coordinates. No sensor are shown otherwise. plothead : bool If True, a head outline is plotted. plothead_kwargs : dict Additional keyword arguments passed to `plot_head_outline()`. resolution : int Number of surface samples along both x and y-axis. masked : bool If True, all surface sample extending to head outline will be masked. **kwargs All additional arguments will be passed to `pylab.imshow()`. Returns ------- (map, head, sensors) The corresponding matplotlib objects are returned if plotted, ie. if plothead is set to `False`, `head` will be `None`. map The colormap that makes the actual plot, a matplotlib.image.AxesImage instance. head What is returned by `plot_head_outline()`. sensors The dots marking the electrodes, a matplotlib.lines.Line2d instance. """ # give sane defaults if plothead_kwargs is None: plothead_kwargs = {} # error function to fit the sensor locations to a sphere def err(params): r, cx, cy, cz = params return (sensorlocations[:, 0] - cx) ** 2 \ + (sensorlocations[:, 1] - cy) ** 2 \ + (sensorlocations[:, 2] - cz) ** 2 \ - r ** 2 # initial guess of sphere parameters (radius and center) params = (1, 0, 0, 0) # do fit (r, cx, cy, cz), stuff = leastsq(err, params) # size of each square ssh = float(r) / resolution # half-size ss = ssh * 2.0 # full-size # Generate a grid and interpolate using the griddata module x = np.arange(cx - r, cx + r, ss) + ssh y = np.arange(cy - r, cy + r, ss) + ssh x, y = pl.meshgrid(x, y) # project the sensor locations onto the sphere sphere_center = np.array((cx, cy, cz)) sproj = sensorlocations - sphere_center sproj = r * sproj / np.c_[np.sqrt(np.sum(sproj**2, axis=1))] sproj += sphere_center # fit topology onto xy projection of sphere topo = griddata(sproj[:, 0], sproj[:, 1], np.ravel(np.array(topography)), x, y) # mask values outside the head if masked: notinhead = np.greater_equal((x - cx)**2 + (y - cy)**2, (1.0 * r)**2) topo = M.masked_where(notinhead, topo) # show surface map = pl.imshow(topo, origin="lower", extent=(-r, r, -r, r), **kwargs) pl.axis('off') if plothead: # plot scaled head outline head = plot_head_outline(scale=r, shift=(cx / 2.0, cy / 2.0), **plothead_kwargs) else: head = None if plotsensors: # plot projected sensor locations # reorder sensors so the ones below plotted first # TODO: please fix with more elegant solution zenum = [x[::-1] for x in enumerate(sproj[:, 2].tolist())] zenum.sort() indx = [x[1] for x in zenum] sensors = pl.plot(sproj[indx, 0] - cx / 2.0, sproj[indx, 1] - cy / 2.0, 'wo') else: sensors = None return map, head, sensors
def analyze(filter): sink = filter() #from mpl_toolkits.mplot3d import Axes3D import matplotlib.axes import matplotlib.pyplot as plt import numpy as np import random import matplotlib.numerix.ma as M fig = plt.figure() ax=fig.add_subplot(111) X = [] Y = [] Z = [] for k in sink: X += [k[0][0]] Y += [k[0][1]] Z += [k[1]] threshold = 1 #prepare for masking arrays - 'conventional' arrays won't do it Y = M.array(Y) #mask values below a certain threshold Y = M.masked_where(Y < threshold , Y) X_min = min(X) X_range = max(X)-min(X) X_scale = 20.0/X_range Y_min = min(Y) Y_range = max(Y)-min(Y) Y_scale = 20.0/Y_range Z_min = min(Z) Z_range = max(Z)-min(Z) Z_scale = 1.0/Z_range colors = [] for i in range(len(sink)): X[i] = (X[i]-X_min)*110.83575 #* X_scale Y[i] = (Y[i]-Y_min)*97.43888 #* Y_scale colors.append(tuple([0.2,0.1]+[1-Z[i]/max(Z)]*1+[1])) z = zip(*filter.coords) coords = zip( (np.array(z[0])-X_min)*110.83575, (np.array(z[1])-Y_min)*97.43888) X = np.array(X) Y = np.array(Y) Z = np.array(Z) ax.scatter(X, Y, marker = 's', color=colors, s = ((Z-Z_min+Z_min/Z_range)*Z_scale)**2*100)# color = [['r','b','y'][random.randint(0,2)] for i in range(len(sink))]) ax.scatter(*zip(*coords), marker = '+') for i in range(len(filter.intersections)): ax.text(coords[i][0], coords[i][1], filter.intersections[i].replace(", Houston TX", "").replace("and", "\n"), fontsize=8, alpha = 0.5) #print ((Z-Z_min)*Z_scale)**4*15 ax.set_xlabel('Latitudinal Offset') ax.set_ylabel('Longitudinal Offset') return plt