- Timestamp:
- Mar 8, 2017, 10:16:31 PM (8 years ago)
- Location:
- trunk/tools
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/tools/drawing.py
r1454 r1466 36 36 ## e.g. # drawing.py -o draw_timeSeries -f ~/PY/ERAI_pl199501_131-132.nc -S 'lon|240,lat|120,time|-1,lev|0:Srange,Srange:ua:date|($[MM]^{[DD]}$):exct,15,d:$%m^{%d}$:January|1995|ERA-Interim|x-wind|at|i=240,|j=120,|k=0:ua:0|12:png:r:-:2:x:2:20:yes' -v var131,time 37 37 ## e.g. # drawing.py -o draw_trajectories -f 'medic950116/control/trajectory.dat@-1@etudes/domains/WL_HyMeX_HighRes_C/geo_em.d01.nc#XLONG_M#XLAT_M@t-step|3600.|19950115000000,medic950116/wlmdza/trajectory.dat@-1@etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M@t-step|3600.|19950115000000,medic950116/wlmdzb/trajectory.dat@-1@etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M@t-step|3600.|19950115000000,medic950116/wlmdzb_cyc/trajectory.dat@-1@etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M@t-step|3600.|19950115000000' -S 'spaghetti_date@-@None@1@o@1@$%d^{%H}$@8@6@4@4|$WRF_{CRM}$,$LMDZ_{AR4.0}$,$LMDZ_{NPv3.1}$,$LMDZ_{NPv3.1b}$|15,28,26,39|medicane trajectories|png|cyl,i|0@8|yes' -v 'medic950116/obs/trajectory.dat,satellite,-1,0.9999998779E+03,t-step|1800.|19950115000000@auto' 38 ## e.g. # drawing.py -o draw_2D_shad_2cont -f hur_157_100000_20051214000000-20051218000000.nc,z_129_100000_20051214000000-20051218000000.nc,ta_130_100000_20051214000000-20051218000000.nc -S 'hur@100000,z@100000,ta@100000:time|0,lev|0,lat|-1,lon|-1:time|0,lev|0,lat|-1,lon|-1:time|0,lev|0,lat|-1,lon|-1:lon:lat:auto:BuPu,auto,auto:fixc,green:None:fixc,red:None:60.,100.:-700.,4000.,8:265.,300.,8:hur|z|ta|@100000|on|20051214000000:png:flip@y:cyl,l:yes' -v hur,z,ta 39 ## e.g. # drawing.py -o draw_ptZvals -f MountainPeaks.nc -S 'height:lon,lat:auto:x:5.:-180.,-90.,180.,90.:0,9000.:ptlabel,name,8,0,4:Mountain!peaks:rainbow,auto,auto:cyl,l:png:yes' -v height 40 ## e.g. # drawing.py -o draw_vectors -f wrfout_d01_1995-01-01_00:00:00 -S 'T|Time|Times|2,Y|south_north|XLAT|-1,X|west_east|XLONG|-1:auto:3@3,wind@rainbow@Srange|Srange,9:10m wind,ms-1:cyl,l:WRF!10!m!winds!on!Dec.!1st!1995!06!UTC:png:winds:yes' -v U10,V10 38 41 39 42 … … 62 65 # draw_2D_shad: plotting a fields with shading 63 66 # draw_2D_shad_cont: plotting two fields, one with shading and the other with contour lines 67 # draw_2D_shad_2cont: plotting three fields, one with shading and the other two with contour lines 64 68 # draw_2D_shad_cont_time: plotting two fields, one with shading and the other with contour lines being 65 69 # one of the dimensions of time characteristics … … 76 80 # draw_points: Function to plot a series of points 77 81 # draw_points_lonlat: Function to plot a series of lon/lat points 78 # draw_ptZvals: Function to plot a given list of points and values82 # draw_ptZvals: Function to plot a given list of points by their Z value and a colorbar 79 83 # draw_timeSeries: Function to draw a time-series 80 84 # draw_topo_geogrid: plotting geo_em.d[nn].nc topography from WPS files … … 98 102 99 103 namegraphics = ['create_movie', 'draw_2D_shad', 'draw_2D_shad_time', \ 100 'draw_2D_shad_cont', 'draw_2D_shad_cont_time', 'draw_2D_shad_line', \ 104 'draw_2D_shad_cont', 'draw_2D_shad_2cont', 'draw_2D_shad_cont_time', \ 105 'draw_2D_shad_line', \ 101 106 'draw_2D_shad_line_time', 'draw_barbs', 'draw_basins', \ 102 107 'draw_2lines', 'draw_2lines_time', 'draw_lines', 'draw_lines_time', \ … … 4102 4107 4103 4108 def draw_ptZvals(ncfile, values, variable): 4104 """ Function to plot a given list of points and values4109 """ Function to plot a given list of points by their Z values according to a colorbar 4105 4110 ncfile= netCDF file to use 4106 values= [fvname]:[XYvar]:[pointype]:[pointsize]:[graphlimits]:[nxtype]: 4107 [figuretitle]:[colorbar]:[mapvalue]:[kindfig] 4108 fvname: name of the variable in the graph 4109 XYvar: [lon],[lat] variable names 4110 ptype: type of the point 4111 ptsize: size of the point 4112 graphlimits: minLON,minLAT,maxLON,maxLAT limits of the graph 'None' for the full size 4113 nxtype: minimum and maximum type 4111 values= [fvname]:[XYvar]:[dimxyfmt]:[pointype]:[pointsize]:[graphlimits]:[nxtype]: 4112 [legend]:[figuretitle]:[cbarv]:[mapvalue]:[kindfig]:[figclose] 4113 [fvname]: name of the variable in the graph 4114 [XYvar]: [x],[y] variable names 4115 [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordy]: format of the values at each axis ('auto', for 4116 'pretty' at both axes) 4117 [dxs]: style of x-axis ('auto' for 'pretty') 4118 'Nfix', values computed at even 'Ndx' 4119 'Vfix', values computed at even 'Ndx' increments 4120 'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals 2.,2.5,4,5,10) 4121 [dxf]: format of the labels at the x-axis 4122 [Ndx]: Number of ticks at the x-axis 4123 [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal) 4124 [dys]: style of y-axis ('auto' for 'pretty') 4125 [dyf]: format of the labels at the y-axis 4126 [Ndy]: Number of ticks at the y-axis 4127 [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal) 4128 [ptype]: type of the point 4129 [ptsize]: size of the point 4130 [graphlimits]: minX,minY,maxX,maxY limits of the graph 'None' for the full size 4131 [nxtype]: minimum and maximum type 4114 4132 'auto': values taken from the extrems of the data 4115 4133 [min],[max]: given minimum and maximum values 4116 figtitle: title of the figure 4117 cbar: color bar 4118 mapv: map characteristics: [proj],[res] 4134 [legend]: kind of legend 4135 'None': no legend 4136 'ptlabel',[varlabels],[fontsize],[xoffset],[yoffset]: label at the side of the point 4137 [varlabels]: variable in file with the labels for the points 4138 [fontsize]: font-size of the label 4139 [xoffset]: x-offset of the label respect the point in pixels 4140 [yoffset]: y-offset of the label respect the point in pixels 4141 'legend',[varlabels],[location],[fontsize]: standard legend 4142 [varlabels]: variable in file with the labels for the points 4143 [location]: location of the legend ('0', for automatic) 4144 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 4145 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 4146 9: 'upper center', 10: 'center' 4147 [fontsize]: size of the font for the legend ('auto' for 12) 4148 [figtitle]: title of the figure ('!' for spaces) 4149 [colorbarv]: list with the parameters of the color bar [colorbar, cbarfmt, cbaror] 4150 colorbar= name of the color bar to use 4151 cbarfmt= format of the numbers in the colorbar ('auto' for %6g) 4152 cbaror= orientation of the colorbar ('auto' for vertical) 4153 [mapv]: map characteristics: [proj],[res] 4119 4154 see full documentation: http://matplotlib.org/basemap/ 4120 4155 [proj]: projection … … 4127 4162 * 'h', high 4128 4163 * 'f', full 4129 kfig: kind of figure 4164 [kfig]: kind of figure 4165 [closefig]: boolean value whether figure should be close (finish) or not 4130 4166 variable= name of the variable to plot 4131 4167 """ … … 4138 4174 quit() 4139 4175 4140 expectargs = '[fvname]:[XYvar]:[ pointype]:[pointsize]:[graphlmits]:[nxtype]:' +\4141 '[ figuretit]:[colorbar]:[mapvalue]:[kindfig]'4176 expectargs = '[fvname]:[XYvar]:[dimxyfmt]:[pointype]:[pointsize]:[graphlmits]:'+ \ 4177 '[nxtype]:[legend]:[figuretit]:[colorbarv]:[mapvalue]:[kindfig]:[closefig]' 4142 4178 4143 4179 drw.check_arguments(fname,values,expectargs,':') … … 4145 4181 fvname = values.split(':')[0] 4146 4182 XYvar = values.split(':')[1] 4147 pointype = values.split(':')[2] 4148 pointsize = int(values.split(':')[3]) 4149 graphlimits = values.split(':')[4] 4150 nxtype = values.split(':')[5] 4151 figuretitle = values.split(':')[6].replace('!',' ') 4152 colorbar = values.split(':')[7] 4153 mapvalue = values.split(':')[8] 4154 kindfig = values.split(':')[9] 4183 dimxyfmt = values.split(':')[2] 4184 pointype = values.split(':')[3] 4185 pointsize = np.float(values.split(':')[4]) 4186 graphlimits = values.split(':')[5] 4187 nxtype = values.split(':')[6] 4188 legend = values.split(':')[7] 4189 figuretitle = values.split(':')[8].replace('!',' ') 4190 colorbarv = values.split(':')[9] 4191 mapvalue = values.split(':')[10] 4192 kindfig = values.split(':')[11] 4193 closefig = gen.Str_Bool(values.split(':')[12]) 4155 4194 4156 4195 onc = NetCDFFile(ncfile, 'r') … … 4163 4202 4164 4203 # points 4165 lonvarn = XYvar.split(',')[0]4166 latvarn = XYvar.split(',')[1]4167 4168 if not onc.variables.has_key( lonvarn):4204 xvarn = XYvar.split(',')[0] 4205 yvarn = XYvar.split(',')[1] 4206 4207 if not onc.variables.has_key(xvarn): 4169 4208 print errormsg 4170 4209 print ' ' + fname + ": file '" + ncfile + "' does not have longitude " + \ 4171 "variable '" + lonvarn + "' !!"4210 "variable '" + xvarn + "' !!" 4172 4211 quit(-1) 4173 4212 4174 if not onc.variables.has_key( latvarn):4213 if not onc.variables.has_key(yvarn): 4175 4214 print errormsg 4176 4215 print ' ' + fname + ": file '" + ncfile + "' does not have latitude " + \ 4177 "variable '" + latvarn + "' !!"4178 quit(-1) 4179 4180 o lonvar = onc.variables[lonvarn]4181 o latvar = onc.variables[latvarn]4216 "variable '" + yvarn + "' !!" 4217 quit(-1) 4218 4219 oxvar = onc.variables[xvarn] 4220 oyvar = onc.variables[yvarn] 4182 4221 ovarvar = onc.variables[variable] 4183 4222 4184 Lpts = len(o lonvar[:].flatten())4223 Lpts = len(oxvar[:].flatten()) 4185 4224 4186 4225 pointvalues = ma.masked_array(np.zeros((Lpts,3), dtype=np.float)) 4187 pointvalues[:,0] = o lonvar[:].flatten()4188 pointvalues[:,1] = o latvar[:].flatten()4226 pointvalues[:,0] = oxvar[:].flatten() 4227 pointvalues[:,1] = oyvar[:].flatten() 4189 4228 pointvalues[:,2] = ovarvar[:].flatten() 4190 4229 … … 4195 4234 fvunits = drw.variables_values(variable)[5] 4196 4235 4197 # map value 4236 varattrs = oxvar.ncattrs() 4237 if drw.searchInlist(varattrs, 'units'): 4238 xvunits = oxvar.getncattr('units') 4239 else: 4240 xvunits = drw.variables_values(xvarn)[5] 4241 varattrs = oyvar.ncattrs() 4242 if drw.searchInlist(varattrs, 'units'): 4243 yvunits = oxvar.getncattr('units') 4244 else: 4245 yvunits = drw.variables_values(yvarn)[5] 4246 4247 # Axis format 4248 xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyfmt,',') 4249 xaxis = [xstyl, xaxf, Nxax, xaxor] 4250 yaxis = [ystyl, yaxf, Nyax, yaxor] 4251 4252 # legend 4253 if legend.find(',') == -1: 4254 legvals = ['None'] 4255 else: 4256 legvals = legend.split(',') 4257 if not onc.variables.has_key(legvals[1]): 4258 print errormsg 4259 print ' ' + fname + ": file '" + ncfile + "' does not have labels " + \ 4260 "variable '" + legvals[1] + "' !!" 4261 quit(-1) 4262 ovarleg = onc.variables[legvals[1]] 4263 Lchar = ovarleg.shape[1] 4264 labs = ncvar.get_str_nc(ovarleg, Lchar) 4265 4266 if legvals[0] == 'None': 4267 legendv = None 4268 elif legvals[0] == 'ptlabel': 4269 legendv = [legvals[0]] 4270 legendv.append(legvals[2]) 4271 legendv.append(np.float(legvals[3])) 4272 legendv.append(np.float(legvals[4])) 4273 legendv = legendv + labs 4274 elif legvals[0] == 'legend': 4275 legendv = [legvals[0]] 4276 legendv.append(int(legvals[2])) 4277 legendv.append(int(legvals[3])) 4278 legendv = legendv + labs 4279 else: 4280 print errormsg 4281 print ' ' + fname + ": kind of legend '" + legvals[0] + "' not ready !!" 4282 print ' available ones:', ['None', 'ptlabel', 'legend'] 4283 quit(-1) 4284 4285 # colorbar values 4286 colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarv,',') 4287 4288 # map value 4198 4289 if mapvalue == 'None': mapvalue = None 4199 4290 4200 # Graph limits4291 # Graph limits 4201 4292 if graphlimits != 'None': 4202 4293 graphlts = np.zeros((4), dtype=np.float) … … 4204 4295 pointvalues[:,0] = ma.masked_outside(pointvalues[:,0], graphlts[0], \ 4205 4296 graphlts[2]) 4206 pointvalues[:,1] = ma.masked_outside(pointvalues[:,1], graphlts[3], \ 4207 graphlts[2]) 4208 4209 # for ip in range(Lpts): 4210 # if pointvalues[ip,0] < graphlts[0] or pointvalues[ip,0] > graphlts[2] \ 4211 # or pointvalues[ip,1] < graphlts[1] or pointvalues[ip,1] > graphlts[3]: 4212 # print ip,pointvalues[ip,0:2], graphlts 4213 # pointvalues[ip,2] = None 4297 pointvalues[:,1] = ma.masked_outside(pointvalues[:,1], graphlts[1], \ 4298 graphlts[3]) 4214 4299 else: 4215 4300 graphlts = None 4216 4301 4217 drw.plot_ptZvals(fvname,fvunits,pointvalues,pointype,pointsize,graphlts, nxtype, \ 4218 figuretitle,colorbar,mapvalue,kindfig) 4302 drw.plot_ptZvals(fvname, fvunits, xvarn, yvarn, xvunits, yvunits, pointvalues, \ 4303 xaxis, yaxis, pointype, pointsize, graphlts, nxtype, figuretitle, [colbarn, \ 4304 fmtcolbar, colbaror], legendv, mapvalue, kindfig, closefig) 4219 4305 4220 4306 return … … 4224 4310 def draw_vectors(ncfile, values, varns): 4225 4311 """ Function to plot wind vectors 4226 values= [dimname]|[vardimname]|[value]:[ vecvals]:[windlabs]:[mapvalues]:4227 [gtit]:[kindfig]:[figuren]4312 values= [dimname]|[vardimname]|[value]:[dimxyfmt]:[vecvals]:[windlabs]:[mapvalues]:[gtit]:[kindfig]:[figuren]: 4313 [closefig] 4228 4314 'X/Y/Z/T'|[dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of: 4229 4315 [dimname]: name of the dimension in the file … … 4236 4322 * NOTE, no dim name all the dimension size 4237 4323 No value takes all the range of the dimension 4324 [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordy]: format of the values at each axis ('auto', for 4325 'pretty' at both axes) 4326 [dxs]: style of x-axis ('auto' for 'pretty') 4327 'Nfix', values computed at even 'Ndx' 4328 'Vfix', values computed at even 'Ndx' increments 4329 'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals 2.,2.5,4,5,10) 4330 [dxf]: format of the labels at the x-axis 4331 [Ndx]: Number of ticks at the x-axis 4332 [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal) 4333 [dys]: style of y-axis ('auto' for 'pretty') 4334 [dyf]: format of the labels at the y-axis 4335 [Ndy]: Number of ticks at the y-axis 4336 [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal) 4238 4337 [vecvals]= [frequency],[color],[length] 4239 4338 [frequency]: [xfreq]@[yfreq] frequency of values allong each axis ('None', all grid points; 4240 4339 'auto', computed automatically to have 20 vectors along each axis) 4241 4340 [color]: color of the vectors 4242 'singlecol'@[colorn]: all the vectors same color ('auto': for 'red') 4243 'wind'@[colorbar] ,[sminv]|[smaxv]: color of the vectors according to wind speed sqrt(u^2+v^2) and given [colorbar]4244 a ll vectors the same length4341 'singlecol'@[colorn]: all the vectors same color ('auto': for 'red') and lengths according to wind's module 4342 'wind'@[colorbar]@[sminv]|[smaxv]: color of the vectors according to wind speed sqrt(u^2+v^2) 4343 and given [colorbar] all vectors the same length 4245 4344 [smin/axv]: minimum and maximum value for the shading or: 4246 4345 'Srange': for full range … … 4252 4351 'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median) 4253 4352 'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val), 4254 percentile_(100-val)-median) 4255 4256 '3rdvar'@[colorbar]@[varn]@[units],[sminv]|[smaxv]: color of the vectors according to a 3rd variable (to be added at -v) and given [colorbar] 4257 all vectors the same length 4353 percentile_(100-val)-median) 4354 '3rdvar'@[colorbar]@[varn]@[units]@[sminv]|[smaxv]: color of the vectors according to a 3rd variable 4355 (to be added at -v) and given [colorbar] all vectors the same length 4356 [colorbar]: name of the colornbar to use 4357 [varn]: name of the variable to pick up values 4358 [units]: units of the variable 4359 [sminv]|[smaxv]: minimum and maximum value for the shading or: 4360 'Srange': for full range 4361 'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean) 4362 'Saroundminmax@val': for min*val,max*val 4363 'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val), 4364 percentile_(100-val)-median) 4365 'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean) 4366 'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median) 4367 'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val), 4368 percentile_(100-val)-median) 4258 4369 [length]: length of the wind vectors ('auto', for 9) 4259 4370 [windlabs]= [windname],[windunits] … … 4271 4382 * 'h', high 4272 4383 * 'f', full 4273 gtit= title of the graph (' |', for spaces)4384 gtit= title of the graph ('!', for spaces) 4274 4385 kindfig= kind of figure 4275 4386 figuren= name of the figure 4387 closefig= whether the figure should be closed 4276 4388 ncfile= file to use 4277 4389 varns= [uwind],[ywind] ',' list of the name of the variables with the u-wind,y-wind component … … 4284 4396 quit() 4285 4397 4286 expectargs = '[X/Y/Z/T]|[dimname]|[vardimname]|[value]:[ vecvals]:[windlabs]:' + \4287 '[ mapvalues]:[gtit]:[kindfig]:[figuren]'4398 expectargs = '[X/Y/Z/T]|[dimname]|[vardimname]|[value]:[dimxyfmt]:[vecvals]:' + \ 4399 '[windlabs]:[mapvalues]:[gtit]:[kindfig]:[figuren]:[closefig]' 4288 4400 4289 4401 drw.check_arguments(fname,values,expectargs,':') 4290 4402 4291 4403 dimvals = values.split(':')[0] 4292 vecvals = values.split(':')[1] 4293 windlabels = values.split(':')[2] 4294 mapvalues = values.split(':')[3] 4295 gtit = values.split(':')[4] 4296 kindfig = values.split(':')[5] 4297 figuren = values.split(':')[6] 4404 dimxyfmt = values.split(':')[1] 4405 vecvals = values.split(':')[2] 4406 windlabels = values.split(':')[3] 4407 mapvalues = values.split(':')[4] 4408 gtit = values.split(':')[5].replace('!',' ') 4409 kindfig = values.split(':')[6] 4410 figuren = values.split(':')[7] 4411 closefig = gen.Str_Bool(values.split(':')[8]) 4298 4412 4299 4413 of = NetCDFFile(ncfile,'r') … … 4309 4423 varNs.append(dims[dn][1]) 4310 4424 dimx = len(of.dimensions[dims[dn][0]]) 4425 xaxisvn = dims[dn][1] 4311 4426 elif dn == 'Y': 4312 4427 varNs.append(dims[dn][1]) 4313 4428 dimy = len(of.dimensions[dims[dn][0]]) 4429 yaxisvn = dims[dn][1] 4314 4430 4315 4431 ivar = 0 … … 4349 4465 if varN == dims['X'][1]: 4350 4466 lonvals0 = np.squeeze(ovarN[tuple(varslice)]) 4467 xaxisu = ncvar.get_varunits(ovarN) 4351 4468 elif varN == dims['Y'][1]: 4352 4469 latvals0 = np.squeeze(ovarN[tuple(varslice)]) 4470 yaxisu = ncvar.get_varunits(ovarN) 4353 4471 elif ivar == 2: 4354 4472 uwvals = np.squeeze(np.array(ovarN[tuple(varslice)])) … … 4390 4508 colorv = np.sqrt(uwvals**2 + vwvals**2) 4391 4509 # Min/Max colorbar 4392 shadminmax = vecvals.split(',')[3]4510 shadminmax = colorvals.split('@')[2] 4393 4511 shading_nx = shadminmax.split('|') 4394 print ' Lluis shading_nx:', shading_nx4395 4512 elif coln == '3rdvar': 4396 if len(varn .split(',')) != 3:4513 if len(varns.split(',')) != 3: 4397 4514 print errormsg 4398 4515 print ' ' + fname + ": color of vectors should be according to '" + \ 4399 4516 coln + "' but a third varibale is not provided !!" 4517 print ' values provided:', varns.split(',') 4400 4518 quit(-1) 4401 ocolvec = of.variables[var Ns[4]]4519 ocolvec = of.variables[varns.split(',')[2]] 4402 4520 colorv = ocolvec[:] 4403 4521 stdvn, lonvn, unitsvn = drw.var_3desc(ocolvec) 4404 4522 colorvals = colorvals + '@' + stdvn + '@' + unitsvn 4405 4523 # Min/Max colorbar 4406 shadminmax = vecvals.split(',')[5]4524 shadminmax = colorvals.split('@')[4] 4407 4525 shading_nx = shadminmax.split('|') 4408 4526 else: … … 4413 4531 lengthv = vecvals.split(',')[2] 4414 4532 4415 # Vector labels 4533 # Axis format 4534 xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyfmt,',') 4535 xaxis = [xstyl, xaxf, Nxax, xaxor] 4536 yaxis = [ystyl, yaxf, Nyax, yaxor] 4537 4538 # Vector labels 4416 4539 windname = windlabels.split(',')[0] 4417 4540 windunits = windlabels.split(',')[1] 4418 4541 4419 drw.plot_vector(lonvals, latvals, uwvals, vwvals, freqv, colorvals, colorv, \ 4420 lengthv, shading_nx, windname, windunits, mapvalues, gtit, kindfig, figuren) 4542 drw.plot_vector(lonvals, latvals, uwvals, vwvals, xaxisvn, yaxisvn, xaxisu, \ 4543 yaxisu, freqv, xaxis, yaxis, colorvals, colorv, lengthv, shading_nx, windname, \ 4544 windunits, mapvalues, gtit, kindfig, figuren) 4421 4545 4422 4546 of.close() … … 6038 6162 return 6039 6163 6164 def draw_2D_shad_2cont(ncfile, values, varn): 6165 """ plotting three fields, one with shading and the other two with contour lines 6166 draw_2D_shad_2cont(ncfile, values, varn) 6167 ncfile= [ncfilevars],[ncfilevarc1],[ncfilevarc2] files to use (one value, same file) 6168 values=[vnamefs],[vnamefc1],[vnamefc2]:[dimvals]:[dimvalc1]:[dimvalc2]:[dimxvn]:[dimyvn]:[dimxyfmt]:[colorbarvals]: 6169 [ckind1]:[clabfmt1]:[ckind2]:[clabfmt2]:[sminv],[smaxv]:[sminc1],[smaxc1],[Nlev1]:[sminc2],[smaxc2],[Nlev2]: 6170 [figt]:[kindfig]:[reverse]:[mapv]:[close] 6171 [vnamefs],[vnamefc1],[vnamefc2]: Name in the figure of the shaded and the contour variable1 and contour variable2 6172 [dimvals/c1/c2]: ',' list of [dimname]|[value] telling at which dimension of the 6173 variable a given value is required: 6174 * [integer]: which value of the dimension 6175 * -1: all along the dimension 6176 * -9: last value of the dimension 6177 * [beg]@[end]@[inc] slice from [beg] to [end] every [inc] 6178 * NOTE, no dim name all the dimension size 6179 [dimx/yvn]: names of the variables with the values of the dimensions for the plot 6180 [dimxyfmt]=[dxf],[Ndx],[dyf],[Ndy]: format of the values at each axis 6181 [dxs]: style of x-axis ('auto' for 'pretty') 6182 'Nfix', values computed at even 'Ndx' 6183 'Vfix', values computed at even 'Ndx' increments 6184 'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10) 6185 [dxf]: format of the labels at the x-axis 6186 [Ndx]: Number of ticks at the x-axis 6187 [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal) 6188 [dys]: style of y-axis ('auto' for 'pretty') 6189 [dyf]: format of the labels at the y-axis 6190 [Ndy]: Number of ticks at the y-axis 6191 [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal) 6192 [colorbarvals]=[colbarn],[fmtcolorbar],[orientation] 6193 [colorbarn]: name of the color bar 6194 [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g) 6195 [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal') 6196 [ckind1/2]: kind of contours for variable 1 andf variable 2 6197 'cmap': as it gets from colorbar 6198 'fixc,[colname]': fixed color [colname], all stright lines 6199 'fixsigc,[colname]': fixed color [colname], >0 stright, <0 dashed line 6200 [clabfmt1/2]: format of the labels in the contour 1 and 2 (C-like, 'None', also possible) 6201 [smin/axv]: minimum and maximum value for the shading or 6202 'Srange': for full range 6203 'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean) 6204 'Saroundminmax@val': for min*val,max*val 6205 'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val), 6206 percentile_(100-val)-median) 6207 'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean) 6208 'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median) 6209 'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val), 6210 percentile_(100-val)-median) 6211 [sminc1/2]:[smaxv1/2]:[Nlev1/2]: minimum, maximum and number of values for the contour 1 and 2 6212 [figt]: title of the figure ('|' for spaces) 6213 [kindfig]: kind of figure 6214 [reverse]: does the values be transposed? 'True/False', 6215 [mapv]: map characteristics: [proj],[res] 6216 see full documentation: http://matplotlib.org/basemap/ 6217 [proj]: projection 6218 * 'cyl', cilindric 6219 * 'lcc', lamvbert conformal 6220 [res]: resolution: 6221 * 'c', crude 6222 * 'l', low 6223 * 'i', intermediate 6224 * 'h', high 6225 * 'f', full 6226 [close]: Whether figure should be finished or not 6227 varn= [varsn],[varcn1],[varcn2] name of the variable to plot with shading variable with contour 1 and contour 2 6228 """ 6229 fname = 'draw_2D_shad_2cont' 6230 6231 if values == 'h': 6232 print fname + '_____________________________________________________________' 6233 print draw_2D_shad_2cont.__doc__ 6234 quit() 6235 6236 expectargs = '[vnamefs],[vnamefc1],[vnamefc2]:[dimvals]:[dimvalc1]:[dimvalc2]:'+ \ 6237 '[dimxvn]:[dimyvn]:[dimxyfmt]:[colorbarvals]:[ckind1]:[clabfmt1]:[ckind2]:' + \ 6238 '[clabfmt2]:[sminv],[smaxv]:[sminc1],[smaxc1],[Nlev1]:[sminc2],[smaxc2],' + \ 6239 '[Nlev2]:[figt]:[kindfig]:[reverse]:[mapv]:[close]' 6240 6241 drw.check_arguments(fname,values,expectargs,':') 6242 6243 vnamesfig = values.split(':')[0].split(',') 6244 dimvals= values.split(':')[1].replace('|',':') 6245 dimvalc1= values.split(':')[2].replace('|',':') 6246 dimvalc2= values.split(':')[3].replace('|',':') 6247 vdimxn = values.split(':')[4] 6248 vdimyn = values.split(':')[5] 6249 dimxyf = values.split(':')[6] 6250 colorbarvals = values.split(':')[7] 6251 countkind1 = values.split(':')[8] 6252 countlabelfmt1 = values.split(':')[9] 6253 countkind2 = values.split(':')[10] 6254 countlabelfmt2 = values.split(':')[11] 6255 shadminmax = values.split(':')[12].split(',') 6256 contlevels1 = values.split(':')[13] 6257 contlevels2 = values.split(':')[14] 6258 figtitle = values.split(':')[15].replace('|',' ') 6259 figkind = values.split(':')[16] 6260 revals = values.split(':')[17] 6261 mapvalue = values.split(':')[18] 6262 close = gen.Str_Bool(values.split(':')[19]) 6263 6264 if2filenames = ncfile.find(',') 6265 6266 if if2filenames != -1: 6267 ncfiles = ncfile.split(',')[0] 6268 ncfilec1 = ncfile.split(',')[1] 6269 ncfilec2 = ncfile.split(',')[2] 6270 else: 6271 ncfiles = ncfile 6272 ncfilec1 = ncfile 6273 ncfilec2 = ncfile 6274 6275 if not os.path.isfile(ncfiles): 6276 print errormsg 6277 print ' ' + fname + ': shading file "' + ncfiles + '" does not exist !!' 6278 quit(-1) 6279 6280 if not os.path.isfile(ncfilec1): 6281 print errormsg 6282 print ' ' + fname + ': contour file 1 "' + ncfilec1 + '" does not exist !!' 6283 quit(-1) 6284 6285 if not os.path.isfile(ncfilec2): 6286 print errormsg 6287 print ' ' + fname + ': contour file 2 "' + ncfilec2 + '" does not exist !!' 6288 quit(-1) 6289 6290 objsf = NetCDFFile(ncfiles, 'r') 6291 objcf1 = NetCDFFile(ncfilec1, 'r') 6292 objcf2 = NetCDFFile(ncfilec2, 'r') 6293 6294 VarNs = varn.split(',') 6295 if len(VarNs) != 3: 6296 print errormsg 6297 print ' ' + fname + ': 3 variables are required and there are:', len(VarNs),\ 6298 'with names:', VarNs, '!!' 6299 print ' excpected vames for:', ['[varshad]', '[varcont1]', '[varcont2]'] 6300 quit(-1) 6301 6302 varns = varn.split(',')[0] 6303 varnc1 = varn.split(',')[1] 6304 varnc2 = varn.split(',')[2] 6305 6306 if not objsf.variables.has_key(varns): 6307 print errormsg 6308 print ' ' + fname + ': shading file "' + ncfiles + \ 6309 '" does not have variable "' + varns + '" !!' 6310 quit(-1) 6311 6312 if not objcf1.variables.has_key(varnc1): 6313 print errormsg 6314 print ' ' + fname + ': contour file 1 "' + ncfilec1 + \ 6315 '" does not have variable "' + varnc1 + '" !!' 6316 quit(-1) 6317 6318 if not objcf2.variables.has_key(varnc2): 6319 print errormsg 6320 print ' ' + fname + ': contour file 2 "' + ncfilec2 + \ 6321 '" does not have variable "' + varnc2 + '" !!' 6322 quit(-1) 6323 6324 # Variables' values 6325 objvars = objsf.variables[varns] 6326 objvarc1 = objcf1.variables[varnc1] 6327 objvarc2 = objcf2.variables[varnc2] 6328 6329 print dimvals.replace('|',':').replace(',','|') 6330 valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace('|',':').replace(',','|')) 6331 valcont1, dimscont1 = drw.slice_variable(objvarc1, dimvalc1.replace('|',':').replace(',','|')) 6332 valcont2, dimscont2 = drw.slice_variable(objvarc2, dimvalc2.replace('|',':').replace(',','|')) 6333 6334 # Checking consistency of matrices 6335 gen.same_shape(valshad, valcont1) 6336 gen.same_shape(valshad, valcont2) 6337 6338 dimnamesv = [vdimxn, vdimyn] 6339 6340 varunits = [] 6341 varunits.append(objvars.getncattr('units')) 6342 varunits.append(objvarc1.getncattr('units')) 6343 varunits.append(objvarc2.getncattr('units')) 6344 6345 if not objsf.variables.has_key(vdimxn): 6346 print errormsg 6347 print ' ' + fname + ': shading file "' + ncfiles + \ 6348 '" does not have dimension variable "' + vdimxn + '" !!' 6349 quit(-1) 6350 if not objsf.variables.has_key(vdimyn): 6351 print errormsg 6352 print ' ' + fname + ': shading file "' + ncfiles + \ 6353 '" does not have dimension variable "' + vdimyn + '" !!' 6354 quit(-1) 6355 6356 objdimx = objsf.variables[vdimxn] 6357 objdimy = objsf.variables[vdimyn] 6358 odimxu = objdimx.getncattr('units') 6359 odimyu = objdimy.getncattr('units') 6360 6361 # Getting only that dimensions with coincident names 6362 odimxv, odimyv = drw.dxdy_lonlatDIMS(objdimx[:], objdimy[:], objdimx.dimensions, \ 6363 objdimy.dimensions, dimvals.replace(':','|').split(',')) 6364 6365 # Contour formats 6366 if countlabelfmt1 == 'None': 6367 countlfmt1 = None 6368 else: 6369 countlfmt1 = countlabelfmt1 6370 if countlabelfmt2 == 'None': 6371 countlfmt2 = None 6372 else: 6373 countlfmt2 = countlabelfmt2 6374 6375 # Shading limits 6376 shading_nx = drw.graphic_range(shadminmax,valshad) 6377 6378 # Contour limits 6379 c1levmin = np.float(contlevels1.split(',')[0]) 6380 c1levmax = np.float(contlevels1.split(',')[1]) 6381 Nc1levels = int(contlevels1.split(',')[2]) 6382 c2levmin = np.float(contlevels2.split(',')[0]) 6383 c2levmax = np.float(contlevels2.split(',')[1]) 6384 Nc2levels = int(contlevels2.split(',')[2]) 6385 6386 levels_cont1 = gen.pretty_int(c1levmin, c1levmax, Nc1levels) 6387 levels_cont2 = gen.pretty_int(c2levmin, c2levmax, Nc2levels) 6388 6389 # Checking range of contours 6390 if c1levmin > np.min(valcont1) or c1levmax < np.max(valcont1): 6391 print warnmsg 6392 print ' ' + fname + " variable '" + varnc1 + "' range contour 1:", \ 6393 np.min(valcont1), ',', np.max(valcont1), 'beyond provided range:', \ 6394 c1levmin, ',', c1levmax 6395 if c2levmin > np.min(valcont2) or c2levmax < np.max(valcont2): 6396 print warnmsg 6397 print ' ' + fname + " variable '" + varnc2 + "' range contour 2:", \ 6398 np.min(valcont2), ',', np.max(valcont2), 'beyond provided range:', \ 6399 c2levmin, ',', c2levmax 6400 6401 if len(levels_cont1) <= 1: 6402 print warnmsg 6403 print ' ' + fname + ': wrong contour 1 levels:', levels_cont1, ' !!' 6404 del(levels_cont1) 6405 levels_cont1 = np.zeros((Nclevels1), dtype=np.float) 6406 levels_cont1 = np.arange(7)*(clevmax1 - clevmin1)/(Nclevels1-1) 6407 print ' generating default ones: ',levels_cont1 6408 if len(levels_cont2) <= 1: 6409 print warnmsg 6410 print ' ' + fname + ': wrong contour 2 levels:', levels_cont2, ' !!' 6411 del(levels_cont2) 6412 levels_cont2 = np.zeros((Nclevels2), dtype=np.float) 6413 levels_cont2 = np.arange(7)*(clevmax2 - clevmin2)/(Nclevels2-1) 6414 print ' generating default ones: ',levels_cont2 6415 6416 if mapvalue == 'None': mapvalue = None 6417 6418 colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',') 6419 6420 xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyf,',') 6421 xaxis = [xstyl, xaxf, Nxax, xaxor] 6422 yaxis = [ystyl, yaxf, Nyax, yaxor] 6423 6424 if revals == 'None': revals = None 6425 6426 drw.plot_2D_shadow_2contour(valshad, valcont1, valcont2, vnamesfig, odimxv, \ 6427 odimyv, odimxu, odimyu, xaxis, yaxis, dimnamesv, [colbarn,fmtcolbar,colbaror], \ 6428 countkind1, countlfmt1, countkind2, countlfmt2, shading_nx, levels_cont1, \ 6429 levels_cont2, varunits, figtitle, figkind, revals, mapvalue, close) 6430 6431 return 6432 6040 6433 6041 6434 #quit() … … 6058 6451 6059 6452 # Not checking file operation 6060 Notcheckingfile = ['draw_2D_shad_cont', 'draw_2D_shad_cont_time', \ 6453 Notcheckingfile = ['draw_2D_shad_cont', 'draw_2D_shad_2cont', \ 6454 'draw_2D_shad_cont_time', \ 6061 6455 'draw_2D_shad_line', 'draw_2D_shad_line_time', 'draw_2lines', 'draw_2lines_time', \ 6062 6456 'draw_lines', \ … … 6108 6502 elif oper == 'draw_2D_shad_cont': 6109 6503 draw_2D_shad_cont(opts.ncfile, opts.values, opts.varname) 6504 elif oper == 'draw_2D_shad_2cont': 6505 draw_2D_shad_2cont(opts.ncfile, opts.values, opts.varname) 6110 6506 elif oper == 'draw_2D_shad_cont_time': 6111 6507 draw_2D_shad_cont_time(opts.ncfile, opts.values, opts.varname) -
trunk/tools/drawing_tools.py
r1454 r1466 78 78 # plot_Trajectories 79 79 # plot_2D_shadow_contour: 80 # plot_2D_shadow_2contour: Plotting 3 2D fields, 1 with shadow and two with contour lines 80 81 # plot_2D_shadow_contour_time: 81 82 # dxdy_lonlat: Function to provide lon/lat 2D lilke-matrices from any sort of dx,dy values … … 1541 1542 # values 1542 1543 wdvx = False 1543 if dxv != '0': 1544 if type(dxv) == type('S') and dxv == '0': 1545 newdxv = None 1546 else: 1544 1547 newdxv = dxv.copy() 1545 1548 wdvx = True 1546 else: 1547 newdxv = None 1549 1548 1550 wdvy = False 1549 if dyv != '0': 1551 if type(dyv) == type('S') and dyv == '0': 1552 newdyv = None 1553 else: 1550 1554 newdyv = dyv.copy() 1551 1555 wdvy = True 1552 else:1553 newdyv = None1554 1556 1555 1557 # ticks 1556 1558 wdtx = False 1557 if dxt != '0': 1559 if type(dxt) == type('S') and dxt == '0': 1560 newdxt = None 1561 else: 1558 1562 newdxt = dxt.copy() 1559 1563 wdtx = True 1560 else: 1561 newdxt = None 1564 1562 1565 wdty = False 1563 if dyt != '0': 1566 if type(dyt) == type('S') and dyt == '0': 1567 newdyt = None 1568 else: 1564 1569 newdyt = dyt.copy() 1565 1570 wdty = True 1566 else:1567 newdyt = None1568 1571 1569 1572 # label in ticks 1570 1573 wdlx = False 1571 if dxl != '0': 1574 if type(dxl) == type('S') and dxl == '0': 1575 newdxl = None 1576 else: 1572 1577 newdxl = list(dxl) 1573 1578 wdlx = True 1574 else: 1575 newdxl = None 1579 1576 1580 wdly = False 1577 if dyl != '0': 1581 if type(dyl) == type('S') and dyl == '0': 1582 newdyl = None 1583 else: 1578 1584 newdyl = list(dyl) 1579 1585 wdly = True 1580 else:1581 newdyl = None1582 1586 1583 1587 # axes' title 1584 1588 wdTx = False 1585 if dxt != '0':1589 if type(dxt) == type('S') and dxt != 0: 1586 1590 newdxtit = str(dxtit) 1587 1591 wdTx = True 1588 1592 else: 1589 1593 newdxtit = None 1594 1590 1595 wdTy = False 1591 if dyt != '0':1596 if type(dyt) == type('S') and dyt != '0': 1592 1597 newdytit = str(dytit) 1593 1598 wdTy = True … … 1828 1833 elif u == 'degrees_east': lu='$degrees\ East$' 1829 1834 elif u == 'degree_east': lu='$degrees\ East$' 1835 elif u == 'degree east': lu='$degrees\ East$' 1830 1836 elif u == 'degrees longitude': lu='$degrees\ East$' 1831 1837 elif u == 'degrees latitude': lu='$degrees\ North$' … … 1833 1839 elif u == 'degrees_north': lu='$degrees\ North$' 1834 1840 elif u == 'degree_north': lu='$degrees\ North$' 1841 elif u == 'degree north': lu='$degrees\ North$' 1835 1842 elif u == 'deg C': lu='$^{\circ}C$' 1836 1843 elif u == 'degC': lu='$^{\circ}C$' … … 1876 1883 elif u == 'm2s-1': lu='$m2s^{-1}$' 1877 1884 elif u == 'm2/s2': lu='$m2s^{-2}$' 1885 elif u == 'm**2 s**-2': lu='$m2s^{-2}$' 1878 1886 elif u == 'm3/s': lu='$m^{3}s^{-1}$' 1879 1887 elif u == 'm^3/s': lu='$m^{3}s^{-1}$' … … 6661 6669 return 6662 6670 6663 def plot_ptZvals(vname, vunits,points,ptype,ptsize,graphlims,minmax,figtitle,cbar,\6664 mapv,kfig):6671 def plot_ptZvals(vname, vunits, xvn, yvn, xvu, yvu, points, xaxv, yaxv, ptype, \ 6672 ptsize, graphlims, minmax, figtitle, cbarv, legv, mapv, kfig, ifclose): 6665 6673 """ Function to plot a given list of points and values 6666 6674 vname= name of the variable in the graph 6667 6675 vunits= units of the variable 6676 xvn= variable name for x-axis 6677 yvn= variable name for y-axis 6678 xvu= units for x-axis 6679 yvu= units for y-axis 6668 6680 points= [lon,lat,val] matrix of values 6681 xaxv= list with the x-axis paramteres [style, format, number and orientation] 6682 yaxv= list with the y-axis paramteres [style, format, number and orientation] 6669 6683 ptype= type of the point 6670 6684 ptsize= size of the point … … 6674 6688 [min],[max]: given minimum and maximum values 6675 6689 figtitle= title of the figure 6676 cbar= color bar 6690 cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror] 6691 colorbar: name of the color bar to use 6692 cbarfmt: format of the numbers in the colorbar 6693 cbaror: orientation of the colorbar 6694 legv= kind of legend 6695 'None': no legend 6696 'ptlabel',[varlabels],[xoffset],[yoffset]: label at the side of the point 6697 [varlabels]: variable in file with the labels for the points 6698 [xoffset]: x-offset of the label respect the point in pixels 6699 [yoffset]: y-offset of the label respect the point in pixels 6700 'legend',[location],[fontsize]: standard legend 6701 [location]: location of the legend ('0', for automatic) 6702 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 6703 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 6704 9: 'upper center', 10: 'center' 6705 [fontsize]: size of the font for the legend ('auto' for 12) 6677 6706 mapv= map characteristics: [proj],[res] 6678 6707 see full documentation: http://matplotlib.org/basemap/ … … 6687 6716 * 'f', full 6688 6717 kfig= kind of figure 6718 ifclose= whether figure should be closed or not 6689 6719 """ 6690 6720 fname = 'plot_ptZvals' … … 6692 6722 figname = 'pointsZval' 6693 6723 6724 if graphlims is None: 6725 dxn = points[:,0].min() 6726 dxx = points[:,0].max() 6727 dyn = points[:,1].min() 6728 dyx = points[:,1].max() 6729 else: 6730 dxn = graphlims[0] 6731 dxx = graphlims[2] 6732 dyn = graphlims[1] 6733 dyx = graphlims[3] 6734 6735 if xaxv[0] == 'pretty': 6736 dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) 6737 elif xaxv[0] == 'Nfix': 6738 dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*xaxv[2])) 6739 elif xaxv[0] == 'Vfix': 6740 dimxt0 = np.arange(0,dxx,xaxv[2]) 6741 if yaxv[0] == 'pretty': 6742 dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) 6743 elif yaxv[0] == 'Nfix': 6744 dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2])) 6745 elif yaxv[0] == 'Vfix': 6746 dimyt0 = np.arange(0,dyx,yaxv[2]) 6747 6748 dimxl0 = [] 6749 for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1])) 6750 dimyl0 = [] 6751 for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1])) 6752 6753 dimxT0 = variables_values(xvn)[0] + ' (' + units_lunits(xvu) + ')' 6754 dimyT0 = variables_values(yvn)[0] + ' (' + units_lunits(yvu) + ')' 6755 6756 if mapv is not None: 6757 pixkind = 'data' 6758 else: 6759 # No following data values 6760 dimxt0 = np.arange(len(dimxt0),dtype=np.float)/(len(dimxt0)) 6761 dimyt0 = np.arange(len(dimyt0),dtype=np.float)/(len(dimyt0)) 6762 pixkind = 'fixpixel' 6763 6694 6764 minlon = points[:,0].min() 6695 maxlon = points[:,0].max() 6765 maxlon = points[:,0].max() 6696 6766 6697 6767 minlat = points[:,1].min() … … 6703 6773 # print 'min/max val;',minval,maxval 6704 6774 6705 lonrange = (points[:,0] - minlon)/(maxlon - minlon) 6706 latrange = (points[:,1] - minlat)/(maxlat - minlat) 6707 colorrange = (points[:,2] - minval)/(maxval - minval) 6775 # Normalizing x,y for the points 6776 #lonrange = (points[:,0] - minlon)/(maxlon - minlon) 6777 #latrange = (points[:,1] - minlat)/(maxlat - minlat) 6778 #colorrange = (points[:,2] - minval)/(maxval - minval) 6708 6779 6709 6780 plt.rc('text', usetex=True) … … 6729 6800 xlat = graphlims[3] 6730 6801 else: 6731 nlon = np.min(vlon)6732 xlon = np.max(vlon)6733 nlat = np.min(vlat)6734 xlat = np.max(vlat)6802 nlon = vlon.min() 6803 xlon = vlon.max() 6804 nlat = vlat.min() 6805 xlat = vlat.max() 6735 6806 6736 6807 lon2 = vlon[dy/2] … … 6759 6830 m.drawcoastlines() 6760 6831 6761 meridians = gen.pretty_int(nlon,xlon, 5)6832 meridians = gen.pretty_int(nlon,xlon,xaxv[2]) 6762 6833 m.drawmeridians(meridians,labels=[True,False,False,True]) 6763 6834 6764 parallels = gen.pretty_int(nlat,xlat, 5)6835 parallels = gen.pretty_int(nlat,xlat,yaxv[2]) 6765 6836 m.drawparallels(parallels,labels=[False,True,True,False]) 6766 6837 # else: … … 6771 6842 6772 6843 if minmax == 'auto': 6773 plt.scatter(points[:,0], points[:,1], c=points[:,2], s=ptsize, cmap=cbar ,\6844 plt.scatter(points[:,0], points[:,1], c=points[:,2], s=ptsize, cmap=cbarv[0],\ 6774 6845 marker=ptype) 6775 else: 6776 minv = np.float(minmax.split(',')[0]) 6777 maxv = np.float(minmax.split(',')[1]) 6778 6779 plt.scatter(points[:,0], points[:,1], c=points[:,2], s=ptsize, cmap=cbar, \ 6780 marker=ptype, vmin=minv, vmax=maxv) 6781 6782 cbar = plt.colorbar() 6783 cbar.set_label(vname.replace('_','\_') +' ('+ units_lunits(vunits) + ')') 6784 6785 plt.title(figtitle) 6846 zminv = minval 6847 zmaxv = minval 6848 else: 6849 zminv = np.float(minmax.split(',')[0]) 6850 zmaxv = np.float(minmax.split(',')[1]) 6851 6852 plt.scatter(points[:,0], points[:,1], c=points[:,2], s=ptsize, cmap=cbarv[0],\ 6853 marker=ptype, vmin=zminv, vmax=zmaxv) 6854 6855 if cbarv[2] == 'horizontal': 6856 cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) 6857 # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tik-labels-in-matplotlib 6858 ticklabels= cbar.ax.get_xticklabels() 6859 Nticks = len(ticklabels) 6860 ticklabs = [] 6861 for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) 6862 cbar.ax.set_xticklabels(ticklabs,rotation=90) 6863 else: 6864 cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) 6865 6866 cbar.set_label(gen.latex_text(vname) +' ('+ units_lunits(vunits) + ')') 6867 6868 # Legend 6869 if legv is not None: 6870 my_cmap = plt.cm.get_cmap(cbarv[0]) 6871 norm = mpl.colors.Normalize(zminv,zmaxv) 6872 Npts = points.shape[0] 6873 if legv[0] == 'ptlabel': 6874 offx = legv[2] 6875 offy = legv[3] 6876 for ipt in range(Npts): 6877 xpt = points[ipt,0] 6878 ypt = points[ipt,1] 6879 clv = my_cmap(norm(points[ipt,2])) 6880 plt.annotate(gen.latex_text(legv[4+ipt]), xy=(xpt,ypt), color=clv, \ 6881 fontsize=legv[1], horizontalalignment="center", xytext=(offx,offy),\ 6882 textcoords='offset pixels') 6883 elif legv[0] == 'legend': 6884 for ipt in range(Npts): 6885 xpt = points[ipt,0] 6886 ypt = points[ipt,1] 6887 clv = my_cmap(norm(points[ipt,2])) 6888 plt.plot(xpt, ypt, ',', color=clv, marker=ptype, markersize=ptsize/2., \ 6889 label=gen.latex_text(legv[3+ipt])) 6890 plt.legend(loc=legv[1], prop={'size':legv[2]}) 6891 6892 plt.title(gen.latex_text(figtitle)) 6786 6893 if graphlims is not None: 6787 6894 plt.xlim(graphlims[0], graphlims[2]) 6788 6895 plt.ylim(graphlims[1], graphlims[3]) 6789 6896 6790 output_kind(kfig, figname, True)6897 output_kind(kfig, figname, ifclose) 6791 6898 6792 6899 return … … 6814 6921 return 6815 6922 6816 def plot_vector(xvals, yvals, uvals, vvals, vecfreq, vecoln, veccolor, veclength, vs,\6817 windn, wuts, mapv, graphtit, kfig, figname):6923 def plot_vector(xvals, yvals, uvals, vvals, xaxn, yaxn, xaxu ,yaxu, vecfreq, xaxv, \ 6924 yaxv, vecoln, veccolor, veclength, vs, windn, wuts, mapv, graphtit, kfig, figname): 6818 6925 """ Function to plot vectors 6819 6926 xvals= values for the x-axis … … 6821 6928 uvals= values for the x-wind 6822 6929 vvals= values for the y-wind 6930 xaxn= name of the variable for the x-axis 6931 yaxn= name of the variable for the y-axis 6932 xaxu= units of the variable for the x-axis 6933 yaxu= units of the variable for the y-axis 6823 6934 vecfreq= [xfreq],[yfreq] frequency of values allong each axis (None, all grid points; 6824 6935 'auto', computed automatically to have 20 vectors along each axis) 6936 xaxv= list with the x-axis parameteres [style, format, number and orientation] 6937 yaxv= list with the y-axis parameteres [style, format, number and orientation] 6825 6938 veccoln= name for the color of the vectors 6826 6939 'singlecol'@[colorn]: all the vectors same color ('auto': for 'red') … … 6859 6972 """ 6860 6973 fname = 'plot_vector' 6974 6975 dxn = xvals.min() 6976 dxx = xvals.max() 6977 dyn = yvals.min() 6978 dyx = yvals.max() 6979 6980 if xaxv[0] == 'pretty': 6981 dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) 6982 elif xaxv[0] == 'Nfix': 6983 dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*xaxv[2])) 6984 elif xaxv[0] == 'Vfix': 6985 dimxt0 = np.arange(0,dxx,xaxv[2]) 6986 if yaxv[0] == 'pretty': 6987 dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) 6988 elif yaxv[0] == 'Nfix': 6989 dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2])) 6990 elif yaxv[0] == 'Vfix': 6991 dimyt0 = np.arange(0,dyx,yaxv[2]) 6992 6993 dimxl0 = [] 6994 for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1])) 6995 dimyl0 = [] 6996 for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1])) 6997 6998 dimxT0 = variables_values(xaxn)[0] + ' (' + units_lunits(xaxu) + ')' 6999 dimyT0 = variables_values(yaxn)[0] + ' (' + units_lunits(yaxu) + ')' 6861 7000 6862 7001 dx=xvals.shape[1] … … 8624 8763 return 8625 8764 8626 8765 def plot_2D_shadow_2contour(varsv, varcv1, varcv2, vnames, dimxv, dimyv, dimxu, \ 8766 dimyu, xaxv, yaxv, dimn, cbarv, ckind1, clabfmt1, ckind2, clabfmt2, vs, vc1, vc2, \ 8767 uts, vtit, kfig, reva, mapv, ifclose): 8768 """ Plotting 3 2D fields, 1 with shadow and two with contour lines 8769 varsv= 2D values to plot with shading 8770 varcv1= 2D values to plot with contours 1 8771 varcv2= 2D values to plot with contours 2 8772 vnames= variable names for the figure 8773 dim[x/y]v = values at the axes of x and y 8774 dim[x/y]u = units at the axes of x and y 8775 xaxv= list with the x-axis paramteres [style, format, number and orientation] 8776 yaxv= list with the y-axis paramteres [style, format, number and orientation] 8777 dimn= dimension names to plot 8778 cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror] 8779 colorbar= name of the color bar to use 8780 cbarfmt= format of the numbers in the colorbar 8781 cbaror= orientation of the colorbar 8782 ckind1/2= contour kind of contour 1 and 2 8783 'cmap': as it gets from colorbar 8784 'fixc,[colname]': fixed color [colname], all stright lines 8785 'fixsigc,[colname]': fixed color [colname], >0 stright, <0 dashed line 8786 clabfmt1/2= format of the labels in the contour 1 and 2 plot (None, no labels) 8787 vs= minmum and maximum values to plot in shadow 8788 vc1= vector with the levels for the contour 1 8789 vc2= vector with the levels for the contour 2 8790 uts= units of the variable [u-shadow, u-contour1, u-contour2] 8791 vtit= title of the variable 8792 kfig= kind of figure (jpg, pdf, png) 8793 reva= 8794 * 'transpose': reverse the axes (x-->y, y-->x) 8795 * 'flip'@[x/y]: flip the axis x or y 8796 mapv= map characteristics: [proj],[res] 8797 see full documentation: http://matplotlib.org/basemap/ 8798 [proj]: projection 8799 * 'cyl', cilindric 8800 * 'lcc', lamvbert conformal 8801 [res]: resolution: 8802 * 'c', crude 8803 * 'l', low 8804 * 'i', intermediate 8805 * 'h', high 8806 * 'f', full 8807 ifclose= boolean value whether figure should be close (finish) or not 8808 """ 8809 fname = 'plot_2D_shadow_2contour' 8810 8811 if type(varsv) == type('S') and varsv == 'h': 8812 print fname + '_____________________________________________________________' 8813 print plot_2D_shadow_2contour.__doc__ 8814 quit() 8815 8816 if len(varsv.shape) != 2: 8817 print errormsg 8818 print ' ' + fname + ': wrong variable shadow rank:', varsv.shape, \ 8819 'is has to be 2D!!' 8820 quit(-1) 8821 if len(varcv1.shape) != 2: 8822 print errormsg 8823 print ' ' + fname + ': wrong variable contour 1 rank:', varcv1.shape, \ 8824 'is has to be 2D!!' 8825 quit(-1) 8826 if len(varcv2.shape) != 2: 8827 print errormsg 8828 print ' ' + fname + ': wrong variable contour 2 rank:', varcv2.shape, \ 8829 'is has to be 2D!!' 8830 quit(-1) 8831 8832 # Axis ticks 8833 # Usually axis > x must be the lon, thus... 8834 dimxv0 = dimxv.copy() 8835 dimyv0 = dimyv.copy() 8836 8837 dxn = dimxv.min() 8838 dxx = dimxv.max() 8839 dyn = dimyv.min() 8840 dyx = dimyv.max() 8841 8842 # sens of the original x-axis and y-axis 8843 xneg=False 8844 if len(dimxv0.shape) == 1: 8845 if dimxv0[0] > dimxv0[1]: xneg=True 8846 else: 8847 if dimxv0[0,0] > dimxv0[0,1]: xneg=True 8848 8849 yneg=False 8850 if len(dimyv0.shape) == 1: 8851 if dimyv0[0] > dimyv0[1]: yneg=True 8852 else: 8853 if dimyv0[0,0] > dimyv0[1,0]: yneg=True 8854 8855 if xaxv[0] == 'pretty': 8856 dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2])) 8857 axxtype='data' 8858 elif xaxv[0] == 'Nfix': 8859 dimxt0 = np.arange(0.,1.,1./(xaxv[2]+1)) 8860 dimxv0 = np.arange(0.,1.,1./varsv.shape[1]) 8861 axxtype='fixpixel' 8862 elif xaxv[0] == 'Vfix': 8863 dxnvfix = int(dxn/xaxv[2]) 8864 dimxt0 = np.arange(dxnvfix*xaxv[2],dxx,xaxv[2]) 8865 axxtype='data' 8866 if yaxv[0] == 'pretty': 8867 dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2])) 8868 axytype='data' 8869 elif yaxv[0] == 'Nfix': 8870 dimyt0 = np.arange(0.,1.,1./(yaxv[2]+1)) 8871 dimyv0 = np.arange(0.,1.,1./varsv.shape[0]) 8872 axytype='fixpixel' 8873 elif yaxv[0] == 'Vfix': 8874 dynvfix = int(dyn/yaxv[2]) 8875 dimyt0 = np.arange(dynvfix*xaxv[2],dyx,yaxv[2]) 8876 axytype='data' 8877 8878 if xneg: dimxt0 = dimxt0[::-1] 8879 if yneg: dimyt0 = dimyt0[::-1] 8880 8881 dimxl0 = [] 8882 if xaxv[0] != 'Nfix': 8883 for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1])) 8884 else: 8885 for i in range(len(dimxt0)): 8886 xv=dxn+i*(dxx-dxn)/(1.*xaxv[2]) 8887 dimxl0.append('{:{style}}'.format(xv, style=xaxv[1])) 8888 dimyl0 = [] 8889 if yaxv[0] != 'Nfix': 8890 for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1])) 8891 else: 8892 for i in range(len(dimyt0)): 8893 yv=dyn+i*(dyx-dyn)/(1.*yaxv[2]) 8894 dimyl0.append('{:{style}}'.format(yv, style=yaxv[1])) 8895 8896 dimxT0 = variables_values(dimn[0])[0] + ' (' + units_lunits(dimxu) + ')' 8897 dimyT0 = variables_values(dimn[1])[0] + ' (' + units_lunits(dimyu) + ')' 8898 8899 if reva is not None: 8900 varcv1, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ 8901 transform(varcv1, reva) 8902 varcv2, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ 8903 transform(varcv2, reva) 8904 varsv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT = \ 8905 transform(varsv, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \ 8906 dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0, axxkind=axxtype, \ 8907 axykind=axytype) 8908 else: 8909 dimxv = dimxv0 8910 dimyv = dimyv0 8911 dimxt = dimxt0 8912 dimyt = dimyt0 8913 dimxl = dimxl0 8914 dimyl = dimyl0 8915 dimxT = dimxT0 8916 dimyT = dimyT0 8917 8918 if not mapv is None: 8919 if len(dimxv[:].shape) == 3: 8920 lon0 = dimxv[0,] 8921 lat0 = dimyv[0,] 8922 elif len(dimxv[:].shape) == 2: 8923 lon0 = dimxv[:] 8924 lat0 = dimyv[:] 8925 elif len(dimxv[:].shape) == 1: 8926 lon00 = dimxv[:] 8927 lat00 = dimyv[:] 8928 lon0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float ) 8929 lat0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float ) 8930 8931 for iy in range(len(lat00)): 8932 lon0[iy,:] = lon00 8933 for ix in range(len(lon00)): 8934 lat0[:,ix] = lat00 8935 8936 map_proj=mapv.split(',')[0] 8937 map_res=mapv.split(',')[1] 8938 8939 dx = lon0.shape[1] 8940 dy = lon0.shape[0] 8941 8942 nlon = np.min(lon0) 8943 xlon = np.max(lon0) 8944 nlat = np.min(lat0) 8945 xlat = np.max(lat0) 8946 8947 lon2 = lon0[dy/2,dx/2] 8948 lat2 = lat0[dy/2,dx/2] 8949 8950 print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ 8951 xlon, ',', xlat 8952 8953 if map_proj == 'cyl': 8954 m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ 8955 urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) 8956 elif map_proj == 'lcc': 8957 m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ 8958 llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) 8959 8960 if len(dimxv.shape) == 1: 8961 lons, lats = np.meshgrid(dimxv, dimyv) 8962 else: 8963 if len(dimxv.shape) == 3: 8964 lons = dimxv[0,:,:] 8965 lats = dimyv[0,:,:] 8966 else: 8967 lons = dimxv[:] 8968 lats = dimyv[:] 8969 8970 x,y = m(lons,lats) 8971 8972 else: 8973 x,y = gen.lonlat2D(dimxv,dimyv) 8974 8975 plt.rc('text', usetex=True) 8976 plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(cbarv[0]), vmin=vs[0], vmax=vs[1]) 8977 if cbarv[2] == 'horizontal': 8978 cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) 8979 # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib 8980 ticklabels= cbar.ax.get_xticklabels() 8981 Nticks = len(ticklabels) 8982 ticklabs = [] 8983 for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text()) 8984 cbar.ax.set_xticklabels(ticklabs,rotation=90) 8985 else: 8986 cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2]) 8987 8988 # contours 8989 ## 8990 contkind1 = ckind1.split(',')[0] 8991 if contkind1 == 'cmap': 8992 cplot1 = plt.contour(x, y, varcv1, levels=vc1) 8993 elif contkind1 == 'fixc': 8994 plt.rcParams['contour.negative_linestyle'] = 'solid' 8995 coln1 = ckind1.split(',')[1] 8996 cplot1 = plt.contour(x, y, varcv1, levels=vc1, colors=coln1) 8997 elif contkind1 == 'fixsigc': 8998 coln1 = ckind1.split(',')[1] 8999 cplot1 = plt.contour(x, y, varcv1, levels=vc1, colors=coln1) 9000 else: 9001 print errormsg 9002 print ' ' + fname + ': contour kind 1 "' + contkind1 + '" not defined !!' 9003 quit(-1) 9004 9005 if clabfmt1 is not None: 9006 plt.clabel(cplot1, fmt=clabfmt1) 9007 mincntS1 = format(vc1[0], clabfmt1[1:len(clabfmt1)]) 9008 maxcntS1 = format(vc1[len(vc1)-1], clabfmt1[1:len(clabfmt1)]) 9009 else: 9010 mincntS1 = '{:g}'.format(vc1[0]) 9011 maxcntS1 = '{:g}'.format(vc1[len(vc1)-1]) 9012 9013 contkind2 = ckind2.split(',')[0] 9014 if contkind2 == 'cmap': 9015 cplot2 = plt.contour(x, y, varcv2, levels=vc2) 9016 elif contkind2 == 'fixc': 9017 plt.rcParams['contour.negative_linestyle'] = 'solid' 9018 coln2 = ckind2.split(',')[1] 9019 cplot2 = plt.contour(x, y, varcv2, levels=vc2, colors=coln2) 9020 elif contkind2 == 'fixsigc': 9021 coln2 = ckind2.split(',')[1] 9022 cplot2 = plt.contour(x, y, varcv2, levels=vc2, colors=coln2) 9023 else: 9024 print errormsg 9025 print ' ' + fname + ': contour kind 2 "' + contkind2 + '" not defined !!' 9026 quit(-1) 9027 9028 if clabfmt2 is not None: 9029 plt.clabel(cplot2, fmt=clabfmt2) 9030 mincntS2 = format(vc2[0], clabfmt2[1:len(clabfmt2)]) 9031 maxcntS2 = format(vc2[len(vc2)-1], clabfmt2[1:len(clabfmt2)]) 9032 else: 9033 mincntS2 = '{:g}'.format(vc2[0]) 9034 maxcntS2 = '{:g}'.format(vc2[len(vc2)-1]) 9035 9036 if not mapv is None: 9037 m.drawcoastlines() 9038 9039 meridians = gen.pretty_int(nlon,xlon,xaxv[2]) 9040 m.drawmeridians(meridians,labels=[True,False,False,True]) 9041 parallels = gen.pretty_int(nlat,xlat,yaxv[2]) 9042 m.drawparallels(parallels,labels=[False,True,True,False]) 9043 9044 plt.xlabel('W-E') 9045 plt.ylabel('S-N') 9046 else: 9047 plt.xlabel(dimxT) 9048 plt.ylabel(dimyT) 9049 9050 plt.xticks(dimxt, dimxl, rotation=xaxv[3]) 9051 plt.yticks(dimyt, dimyl, rotation=yaxv[3]) 9052 9053 #set the limits of the plot to the limits of the data 9054 plt.axis([x[0,0], x[0,x.shape[1]-1], y[0,0], y[y.shape[0]-1,0]]) 9055 9056 # units labels 9057 cbar.set_label(gen.latex_text(vnames[0]) + ' (' + units_lunits(uts[0]) + ')') 9058 plt.annotate(gen.latex_text(vnames[1]) +' (' + units_lunits(uts[1]) + ') [' + \ 9059 mincntS1 + ', ' + maxcntS1 + ']', xy=(0.05,0.04), xycoords='figure fraction', \ 9060 color=coln1) 9061 plt.annotate(gen.latex_text(vnames[2]) +' (' + units_lunits(uts[2]) + ') [' + \ 9062 mincntS2 + ', ' + maxcntS2 + ']', xy=(0.55,0.04), xycoords='figure fraction', \ 9063 color=coln2) 9064 9065 figname = '2Dfields_shadow-2contour' 9066 graphtit = gen.latex_text(vtit) 9067 9068 plt.title(graphtit) 9069 9070 output_kind(kfig, figname, ifclose) 9071 9072 return 9073
Note: See TracChangeset
for help on using the changeset viewer.