source: trunk/UTIL/PYTHON/planetoplot_v2/ppplot.py @ 925

Last change on this file since 925 was 923, checked in by aslmd, 12 years ago

UTIL PYTHON planetoplot_v2

PPCLASS AND PPPLOT

  • added global plot settings in pp() objects
  • self is returned for each method to allow e.g. one-line get + attribution
  • added labeling of 1D plots
  • fine-tuning of plot appearance (e.g. vector key)
  • corrected a problem with plotin (same object can be referred to all along)
  • fixed meanarea for 1D requests

PP.PY

  • no more -f for pp.py (files are simply given as arguments!)
  • added missing options to pp.py
  • nice informative header

PP_RELOAD.PY

  • pp_reload.py can now change colorbars and 1D markers

EXAMPLES

  • general update of examples + few additions
  • added a nice example tide with mixed 2D+1D plots
File size: 26.1 KB
Line 
1###############################################
2## PLANETOPLOT                               ##
3## --> PPPLOT                                ##
4###############################################
5## Author: Aymeric Spiga. 02-03/2013         ##
6###############################################
7# python built-in librairies
8import time as timelib
9# added librairies
10import numpy as np
11import matplotlib.pyplot as mpl
12from matplotlib.cm import get_cmap
13from mpl_toolkits.basemap import Basemap
14# personal librairies
15import ppcompute
16###############################################
17
18#################################
19# global variables and settings #
20#################################
21
22# matplotlib settings
23# http://matplotlib.org/users/customizing.html
24# -------------------------------
25mpl.rcParams['font.family'] = "serif"
26mpl.rcParams['axes.color_cycle'] = "r,g,b,k"
27mpl.rcParams['contour.negative_linestyle'] = "dashed"
28mpl.rcParams['verbose.level'] = "silent"
29mpl.rcParams['lines.linewidth'] = 1.5
30mpl.rcParams['lines.markersize'] = 10
31mpl.rcParams['xtick.major.pad'] = 10
32mpl.rcParams['ytick.major.pad'] = 10
33
34# global variables
35# -------------------------------
36# - where settings files are located
37#   (None means planetoplot_v2 in PYTHONPATH)
38whereset = None
39# - some good default settings.
40# (bounds)
41how_many_sigma = 3.0 
42# (contours)
43ccol = 'black'
44cline = 0.55
45# (vectors)
46widthvec = 0.002
47reducevec = 30.
48# (colorbar)
49zeorientation="vertical"
50zefrac = 0.05
51# (save figures)
52pad_inches_value=0.25
53###############################################
54
55##########################
56# executed when imported #
57##########################
58###########################################
59# we load user-defined automatic settings #
60###########################################
61# initialize the warning variable about file not present...
62files_not_present = ""
63# ... and the whereset variable
64whereset = ppcompute.findset(whereset)
65
66# - variable settings
67# -------------------------------
68zefile = "set_var.txt"
69vf = {} ; vc = {} ; vl = {}
70try: 
71    f = open(whereset+zefile, 'r')
72    for line in f:
73        if "#" in line: pass
74        else:
75            var, format, colorb, label = line.strip().split(';')
76            ind = var.strip() 
77            vf[ind] = format.strip()
78            vc[ind] = colorb.strip()
79            vl[ind] = label.strip()
80    f.close()
81except IOError: 
82    files_not_present = files_not_present + zefile + " "
83
84## - file settings
85## -------------------------------
86#zefile = "set_file.txt"
87#prefix_t = {} ; suffix_t = {} ; name_t = {} ; proj_t = {} ; vecx_t = {} ; vecy_t = {}
88#try:
89#    f = open(whereset+zefile, 'r')
90#    for line in f:
91#        if "#" in line: pass
92#        else:
93#            prefix, suffix, name, proj, vecx, vecy = line.strip().split(';')
94#            ind = name.strip()
95#            prefix_t[ind] = prefix.strip()
96#            suffix_t[ind] = suffix.strip()
97#            #name_t[ind] = name.strip()
98#            proj_t[ind] = proj.strip()
99#            vecx_t[ind] = vecx.strip()
100#            vecy_t[ind] = vecy.strip()
101#    f.close()
102#except IOError:
103#    files_not_present = files_not_present + zefile + " "
104
105# - multiplot settings
106# -------------------------------
107zefile = "set_multiplot.txt"
108subv_t = {} ; subh_t = {} ; wspace_t = {} ; hspace_t = {} ; font_t = {}
109try:
110    f = open(whereset+zefile, 'r')
111    for line in f:
112        if "#" in line: pass
113        else:
114            num, subv, subh, wspace, hspace, font = line.strip().split(';')
115            ind = int(num.strip())
116            subv_t[ind] = int(subv.strip())
117            subh_t[ind] = int(subh.strip())
118            wspace_t[ind] = float(wspace.strip())
119            hspace_t[ind] = float(hspace.strip())
120            font_t[ind] = float(font.strip())
121    f.close()
122except IOError:
123    files_not_present = files_not_present + zefile + " "
124
125# - background settings
126# -------------------------------
127zefile = "set_back.txt"
128back = {}
129try:
130    f = open(whereset+zefile, 'r')
131    for line in f:
132        if "#" in line: pass
133        else:
134            name, link = line.strip().split(';')
135            ind = name.strip() 
136            back[ind] = link.strip()
137    f.close()
138except IOError:
139    files_not_present = files_not_present + zefile + " "
140
141# - area settings
142# -------------------------------
143zefile = "set_area.txt"
144area = {}
145try:
146    f = open(whereset+zefile, 'r')
147    for line in f:
148        if "#" in line: pass
149        else:
150            name, wlat1, wlat2, wlon1, wlon2 = line.strip().split(';')
151            area[name.strip()] = [[float(wlon1.strip()),float(wlon2.strip())],\
152                                  [float(wlat1.strip()),float(wlat2.strip())]]
153    f.close()
154except IOError:
155    files_not_present = files_not_present + zefile + " "
156# A note to the user about missing files
157if files_not_present != "":
158    print "warning: files "+files_not_present+" not in "+whereset+" ; those presets will be missing"
159
160# TBD: should change vector color with colormaps
161#"gist_heat":    "white",\
162#"hot":          "white",\
163#"gray":         "red",\
164
165####################
166# useful functions #
167####################
168
169# a function to define subplot
170# ... user can change settings in set_multiplot.txt read above
171# -------------------------------
172def definesubplot(numplot, fig):
173    try: 
174        mpl.rcParams['font.size'] = font_t[numplot]
175    except: 
176        mpl.rcParams['font.size'] = 18
177    try: 
178        fig.subplots_adjust(wspace = wspace_t[numplot], hspace = hspace_t[numplot])
179        subv, subh = subv_t[numplot],subh_t[numplot]
180    except: 
181        print "!! WARNING !! no preset found from set_multiplot.txt, or this setting file was not found."
182        subv = 1 ; subh = numplot
183    return subv,subh
184
185# a function to calculate automatically bounds (or simply prescribe those)
186# -------------------------------
187def calculate_bounds(field,vmin=None,vmax=None):
188    # prescribed cases first
189    zevmin = vmin
190    zevmax = vmax
191    # computed cases
192    if zevmin is None or zevmax is None:
193       # select values
194       ind = np.where(field < 9e+35)
195       fieldcalc = field[ ind ] # field must be a numpy array
196       # calculate stdev and mean
197       dev = np.std(fieldcalc)*how_many_sigma
198       damean = ppcompute.mean(fieldcalc)
199       # fill min/max if needed
200       if vmin is None: zevmin = damean - dev
201       if vmax is None: zevmax = damean + dev
202       # special case: negative values with stddev while field is positive
203       if zevmin < 0. and ppcompute.min(fieldcalc) > 0.: zevmin = 0.
204    # check that bounds are not too tight given the field
205    amin = ppcompute.min(field)
206    amax = ppcompute.max(field)
207    cmin = 100.*np.abs((amin - zevmin)/amin)
208    cmax = 100.*np.abs((amax - zevmax)/amax)
209    if cmin > 150. or cmax > 150.:
210        print "!! WARNING !! Bounds are a bit too tight. Might need to reconsider those."
211        print "!! WARNING !! --> actual",amin,amax,"adopted",zevmin,zevmax
212    return zevmin, zevmax   
213    #### treat vmin = vmax for continuity
214    #if vmin == vmax:  zevmin = damean - dev ; zevmax = damean + dev
215
216# a function to solve the problem with blank bounds !
217# -------------------------------
218def bounds(what_I_plot,zevmin,zevmax,miss=9e+35):
219    small_enough = 1.e-7
220    if zevmin < 0: what_I_plot[ what_I_plot < zevmin*(1.-small_enough) ] = zevmin*(1.-small_enough)
221    else:          what_I_plot[ what_I_plot < zevmin*(1.+small_enough) ] = zevmin*(1.+small_enough)
222    what_I_plot[ what_I_plot > miss  ] = -miss
223    what_I_plot[ what_I_plot > zevmax ] = zevmax*(1.-small_enough)
224    return what_I_plot
225
226# a generic function to show (GUI) or save a plot (PNG,EPS,PDF,...)
227# -------------------------------
228def save(mode="gui",filename="plot",folder="./",includedate=True,res=150,custom=False):
229    # a few settings
230    possiblesave = ['eps','ps','svg','png','jpg','pdf'] 
231    # now the main instructions
232    if mode == "gui": 
233        mpl.show()
234    elif mode in possiblesave:
235        ## name of plot
236        name = folder+'/'+filename
237        if includedate:
238            for ttt in timelib.gmtime():
239                name = name + "_" + str(ttt)
240        name = name +"."+mode
241        ## save file
242        print "**** Saving file in "+mode+" format... Please wait."
243        if not custom:
244            # ... regular plots
245            mpl.savefig(name,dpi=res,pad_inches=pad_inches_value,bbox_inches='tight')
246        else:
247            # ... mapping mode, adapted space for labels etc...
248            mpl.savefig(name,dpi=res)
249    else:
250        print "!! ERROR !! File format not supported. Supported: ",possiblesave
251
252##################################
253# a generic class to make a plot #
254##################################
255class plot():
256
257    # print out a help string when help is invoked on the object
258    # -------------------------------
259    def __repr__(self):
260        whatprint = 'plot object. \"help(plot)\" for more information\n'
261        return whatprint
262
263    # default settings
264    # -- user can define settings by two methods.
265    # -- 1. yeah = plot2d(title="foo")
266    # -- 2. yeah = pp() ; yeah.title = "foo"
267    # -------------------------------
268    def __init__(self,\
269                 var=None,\
270                 field=None,\
271                 absc=None,\
272                 xlabel="",\
273                 ylabel="",\
274                 div=20,\
275                 logx=False,\
276                 logy=False,\
277                 swap=False,\
278                 swaplab=True,\
279                 invert=False,\
280                 xcoeff=1.,\
281                 ycoeff=1.,\
282                 title=""):
283        ## what could be defined by the user
284        self.var = var
285        self.field = field
286        self.absc = absc
287        self.xlabel = xlabel
288        self.ylabel = ylabel
289        self.title = title
290        self.div = div
291        self.logx = logx
292        self.logy = logy
293        self.swap = swap
294        self.swaplab = swaplab # NB: swaplab only used if swap=True
295        self.invert = invert
296        self.xcoeff = xcoeff
297        self.ycoeff = ycoeff
298        ## other useful arguments
299        ## ... not used here in ppplot but need to be attached to plot object
300        self.axisbg = "white"
301        self.superpose = False
302
303    # check
304    # -------------------------------
305    def check(self):
306        if self.field is None: print "!! ERROR !! Please define a field to be plotted" ; exit()
307
308    # define_from_var
309    # ... this uses settings in set_var.txt
310    # -------------------------------
311    def define_from_var(self):
312        if self.var is not None:
313         if self.var.upper() in vl.keys():
314          self.title = vl[self.var.upper()]
315
316    # make
317    # this is generic to all plots
318    # -------------------------------
319    def make(self):
320        self.check()
321        mpl.xlabel(self.xlabel)
322        mpl.ylabel(self.ylabel)
323        if self.swap:
324         if self.swaplab:
325           mpl.xlabel(self.ylabel)
326           mpl.ylabel(self.xlabel)
327        mpl.title(self.title)
328        # if masked array, set masked values to filled values (e.g. np.nan) for plotting purposes
329        if type(self.field).__name__ in 'MaskedArray':
330            self.field[self.field.mask] = self.field.fill_value
331
332################################
333# a subclass to make a 1D plot #
334################################
335class plot1d(plot):
336
337    # print out a help string when help is invoked on the object
338    # -------------------------------
339    def __repr__(self):
340        whatprint = 'plot1d object. \"help(plot1d)\" for more information\n'
341        return whatprint
342
343    # default settings
344    # -- user can define settings by two methods.
345    # -- 1. yeah = plot1d(title="foo")
346    # -- 2. yeah = pp() ; yeah.title = "foo"
347    # -------------------------------
348    def __init__(self,\
349                 lstyle='-',\
350                 color='b',\
351                 marker='x',\
352                 label=None):
353        ## get initialization from parent class
354        plot.__init__(self)
355        ## what could be defined by the user
356        self.lstyle = lstyle
357        self.color = color
358        self.marker = marker
359        self.label = label
360
361    # define_from_var
362    # ... this uses settings in set_var.txt
363    # -------------------------------
364    def define_from_var(self):
365        # get what is done in the parent class
366        plot.define_from_var(self)
367        # add specific stuff
368        if self.var is not None:
369         if self.var.upper() in vl.keys():
370          self.ylabel = vl[self.var.upper()]
371          self.title = ""
372
373    # make
374    # -------------------------------
375    def make(self):
376        # get what is done in the parent class
377        plot.make(self)
378        # add specific stuff
379        mpl.grid(color='grey')
380        if self.lstyle == "": self.lstyle = " " # to allow for no line at all with ""
381        # swapping if requested
382        if self.swap:  x = self.field ; y = self.absc
383        else:          x = self.absc ; y = self.field
384        # coefficients on axis
385        x=x*self.xcoeff ; y=y*self.ycoeff
386        # check axis
387        if x.size != y.size:
388            print "!! ERROR !! x and y sizes don't match on 1D plot.", x.size, y.size
389            exit()
390        # make the 1D plot
391        # either request linestyle or let matplotlib decide
392        if self.lstyle is not None and self.color is not None:
393            mpl.plot(x,y,self.color+self.lstyle,marker=self.marker,label=self.label)
394        else:
395            mpl.plot(x,y,marker=self.marker,label=self.label)
396        # make log axes and/or invert ordinate
397        # ... this must be after plot so that axis bounds are well-defined
398        # ... also inverting must be after making the thing logarithmic
399        if self.logx: mpl.semilogx()
400        if self.logy: mpl.semilogy()
401        if self.invert: ax = mpl.gca() ; ax.set_ylim(ax.get_ylim()[::-1])
402        # add a label for line(s)
403        if self.label is not None:
404            if self.label != "":
405                mpl.legend(loc="best",fancybox=True)
406        ## TBD: set with .div the number of ticks
407        ## TBD: be able to control plot limits
408        #ticks = self.div + 1
409        #ax = mpl.gca()
410        #ax.get_xaxis().set_ticks(np.linspace(ppcompute.min(x),ppcompute.max(x),ticks/2+1))
411
412################################
413# a subclass to make a 2D plot #
414################################
415class plot2d(plot):
416
417    # print out a help string when help is invoked on the object
418    # -------------------------------
419    def __repr__(self):
420        whatprint = 'plot2d object. \"help(plot2d)\" for more information\n'
421        return whatprint
422
423    # default settings
424    # -- user can define settings by two methods.
425    # -- 1. yeah = plot2d(title="foo")
426    # -- 2. yeah = pp() ; yeah.title = "foo"
427    # -------------------------------
428    def __init__(self,\
429                 ordi=None,\
430                 mapmode=False,\
431                 proj="cyl",\
432                 back=None,\
433                 colorb="jet",\
434                 trans=1.0,\
435                 addvecx=None,\
436                 addvecy=None,\
437                 addcontour=None,\
438                 fmt="%.2e",\
439                 blon=None,\
440                 blat=None,\
441                 area=None,\
442                 vmin=None,\
443                 vmax=None,\
444                 colorvec="black"):
445        ## get initialization from parent class
446        plot.__init__(self)
447        ## what could be defined by the user
448        self.ordi = ordi
449        self.mapmode = mapmode
450        self.proj = proj
451        self.back = back
452        self.colorb = colorb
453        self.trans = trans
454        self.addvecx = addvecx
455        self.addvecy = addvecy
456        self.colorvec = colorvec
457        self.addcontour = addcontour
458        self.fmt = fmt
459        self.blon = blon ; self.blat = blat
460        self.area = area
461        self.vmin = vmin ; self.vmax = vmax
462
463    # define_from_var
464    # ... this uses settings in set_var.txt
465    # -------------------------------
466    def define_from_var(self):
467        # get what is done in the parent class
468        plot.define_from_var(self)
469        # add specific stuff
470        if self.var is not None:
471         if self.var.upper() in vl.keys():
472          self.colorb = vc[self.var.upper()]
473          self.fmt = vf[self.var.upper()]
474
475    # make
476    # -------------------------------
477    def make(self):
478        # get what is done in the parent class...
479        plot.make(self)
480        # ... then add specific stuff
481        ############################################################################################
482        ### PRE-SETTINGS
483        ############################################################################################
484        # transposing if necessary
485        shape = self.field.shape
486        if shape[0] != shape[1]:
487         if len(self.absc) == shape[0] and len(self.ordi) == shape[1]:
488            print "!! WARNING !! Transposing axes"
489            self.field = np.transpose(self.field)
490        # bound field
491        zevmin, zevmax = calculate_bounds(self.field,vmin=self.vmin,vmax=self.vmax)
492        what_I_plot = bounds(self.field,zevmin,zevmax)
493        # define contour field levels. define color palette
494        ticks = self.div + 1
495        zelevels = np.linspace(zevmin,zevmax,ticks)
496        palette = get_cmap(name=self.colorb)
497        # do the same thing for possible contourline entries
498        if self.addcontour is not None:
499            # if masked array, set masked values to filled values (e.g. np.nan) for plotting purposes
500            if type(self.addcontour).__name__ in 'MaskedArray':
501               self.addcontour[self.addcontour.mask] = self.addcontour.fill_value
502            zevminc, zevmaxc = calculate_bounds(self.addcontour)
503            what_I_contour = bounds(self.addcontour,zevminc,zevmaxc)
504            ticks = self.div + 1
505            zelevelsc = np.linspace(zevminc,zevmaxc,ticks)
506        ############################################################################################
507        ### MAIN PLOT
508        ### NB: contour lines are done before contour shades otherwise colorar error
509        ############################################################################################
510        if not self.mapmode:
511            ## A SIMPLE 2D PLOT
512            ###################
513            # swapping if requested
514            if self.swap:  x = self.ordi ; y = self.absc
515            else:          x = self.absc ; y = self.ordi
516            # coefficients on axis
517            x=x*self.xcoeff ; y=y*self.ycoeff
518            # make shaded and line contours
519            if self.addcontour is not None: 
520                mpl.contour(x, y, what_I_contour, \
521                            zelevelsc, colors = ccol, linewidths = cline)
522            mpl.contourf(x, y, \
523                         self.field, \
524                         zelevels, cmap=palette)
525            # make log axes and/or invert ordinate
526            if self.logx: mpl.semilogx()
527            if self.logy: mpl.semilogy()
528            if self.invert: ax = mpl.gca() ; ax.set_ylim(ax.get_ylim()[::-1])
529        else:
530            ## A 2D MAP USING PROJECTIONS (basemap)
531            #######################################
532            mpl.xlabel("") ; mpl.ylabel("")
533            # additional security in case self.proj is None here
534            # ... we set cylindrical projection (the simplest one)
535            if self.proj is None: self.proj = "cyl"
536            # get lon and lat in 2D version.
537            # (but first ensure we do have 2D coordinates)
538            if self.absc.ndim == 1:     [self.absc,self.ordi] = np.meshgrid(self.absc,self.ordi)
539            elif self.absc.ndim > 2:    print "!! ERROR !! lon and lat arrays must be 1D or 2D"
540            # get lat lon intervals and associated settings
541            wlon = [np.min(self.absc),np.max(self.absc)]
542            wlat = [np.min(self.ordi),np.max(self.ordi)]
543            # -- area presets are in set_area.txt
544            if self.area is not None:
545             if self.area in area.keys():
546                wlon, wlat = area[self.area]
547            # -- settings for meridians and parallels
548            steplon = abs(wlon[1]-wlon[0])/6.
549            steplat = abs(wlat[1]-wlat[0])/3.
550            mertab = np.r_[wlon[0]:wlon[1]:steplon] ; merlab = [0,0,0,1]
551            partab = np.r_[wlat[0]:wlat[1]:steplat] ; parlab = [1,0,0,0]
552            format = '%.1f'
553            # -- center of domain and bounding lats
554            lon_0 = 0.5*(wlon[0]+wlon[1])
555            lat_0 = 0.5*(wlat[0]+wlat[1])
556            # some tests, bug fixes, and good-looking settings
557            # ... cyl is good for global and regional
558            if self.proj == "cyl":
559                format = '%.0f'
560            # ... global projections
561            elif self.proj in ["ortho","moll","robin"]:
562                wlat[0] = None ; wlat[1] = None ; wlon[0] = None ; wlon[1] = None
563                steplon = 30. ; steplat = 30.
564                if self.proj in ["robin","moll"]: steplon = 60.
565                mertab = np.r_[-360.:360.:steplon]
566                partab = np.r_[-90.:90.:steplat]
567                if self.proj == "ortho": 
568                    merlab = [0,0,0,0] ; parlab = [0,0,0,0]
569                    # in ortho projection, blon and blat can be used to set map center
570                    if self.blon is not None: lon_0 = self.blon
571                    if self.blat is not None: lat_0 = self.blat
572                elif self.proj == "moll":
573                    merlab = [0,0,0,0]
574                format = '%.0f'
575            # ... regional projections
576            elif self.proj in ["lcc","laea","merc"]:
577                if self.proj in ["lcc","laea"] and wlat[0] == -wlat[1]: 
578                    print "!! ERROR !! with Lambert lat1 must be different than lat2" ; exit()
579                if wlat[0] < -80. and wlat[1] > 80.:
580                    print "!! ERROR !! set an area (not global)" ; exit()
581                format = '%.0f'
582            elif self.proj in ["npstere","spstere"]:
583                # in polar projections, blat gives the bounding lat
584                # if not set, set something reasonable
585                if self.blat is None:   self.blat = 60.
586                # help the user who forgets self.blat would better be negative in spstere
587                # (this actually serves for the default setting just above)
588                if self.proj == "spstere" and self.blat > 0: self.blat = -self.blat
589            # ... unsupported projections
590            else:
591                print "!! ERROR !! unsupported projection. supported: "+\
592                      "cyl, npstere, spstere, ortho, moll, robin, lcc, laea, merc"
593            # finally define projection
594            m = Basemap(projection=self.proj,\
595                        lat_0=lat_0,lon_0=lon_0,\
596                        boundinglat=self.blat,\
597                        llcrnrlat=wlat[0],urcrnrlat=wlat[1],\
598                        llcrnrlon=wlon[0],urcrnrlon=wlon[1])
599            # draw meridians and parallels
600            ft = int(mpl.rcParams['font.size']*3./4.)
601            m.drawmeridians(mertab,labels=merlab,color='grey',linewidth=0.75,fontsize=ft,fmt=format)
602            m.drawparallels(partab,labels=parlab,color='grey',linewidth=0.75,fontsize=ft,fmt=format)
603            # define background (see set_back.txt)
604            if self.back is not None:
605              if self.back in back.keys():
606                 print "**** info: loading a background, please wait.",self.back
607                 if back not in ["coast","sea"]:   m.warpimage(back[self.back],scale=0.75)
608                 elif back == "coast":             m.drawcoastlines()
609                 elif back == "sea":               m.drawlsmask(land_color='white',ocean_color='aqua')
610              else:
611                 print "!! ERROR !! requested background not defined. change name or fill in set_back.txt" ; exit()
612            # define x and y given the projection
613            x, y = m(self.absc, self.ordi)
614            # contour field. first line contour then shaded contour.
615            if self.addcontour is not None: 
616                m.contour(x, y, what_I_contour, \
617                            zelevelsc, colors = ccol, linewidths = cline)
618            m.contourf(x, y, what_I_plot, zelevels, cmap = palette, alpha = self.trans)
619        ############################################################################################
620        ### COLORBAR
621        ############################################################################################
622        if self.trans > 0.:
623            ## draw colorbar. settings are different with projections. or if not mapmode.
624            if not self.mapmode: orientation=zeorientation ; frac = 0.075 ; pad = 0.03
625            elif self.proj in ['moll']: orientation="horizontal" ; frac = 0.075 ; pad = 0.03
626            elif self.proj in ['cyl']: orientation="vertical" ; frac = 0.023 ; pad = 0.03
627            else: orientation = zeorientation ; frac = zefrac ; pad = 0.03
628            zelevpal = np.linspace(zevmin,zevmax,num=min([ticks/2+1,21]))
629            zecb = mpl.colorbar(fraction=frac,pad=pad,\
630                                format=self.fmt,orientation=orientation,\
631                                ticks=zelevpal,\
632                                extend='neither',spacing='proportional') 
633            if zeorientation == "horizontal": zecb.ax.set_xlabel(self.title) ; self.title = ""
634        ############################################################################################
635        ### VECTORS. must be after the colorbar. we could also leave possibility for streamlines.
636        ############################################################################################
637        ### not expecting NaN in self.addvecx and self.addvecy. masked arrays is just enough.
638        stride = 3
639        if self.addvecx is not None and self.addvecy is not None and self.mapmode:
640                ## for metwinds only ???
641                [vecx,vecy] = m.rotate_vector(self.addvecx,self.addvecy,self.absc,self.ordi) 
642                # reference vector is scaled
643                zescale = ppcompute.mean(np.sqrt(self.addvecx*self.addvecx+self.addvecy*self.addvecy))
644                # make vector field
645                q = m.quiver( x[::stride,::stride],y[::stride,::stride],\
646                              vecx[::stride,::stride],vecy[::stride,::stride],\
647                              angles='xy',color=self.colorvec,pivot='middle',\
648                              scale=zescale*reducevec,width=widthvec )
649                # make vector key. default is on upper left corner.
650                keyh = 1.025 ; keyv = 1.05
651                #keyh = -0.03 ; keyv = 1.08
652                p = mpl.quiverkey(q,keyh,keyv,\
653                                  zescale,str(int(zescale)),\
654                                  color='black',labelpos='S',labelsep = 0.07)
Note: See TracBrowser for help on using the repository browser.