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

Last change on this file since 963 was 960, checked in by aslmd, 12 years ago

UTIL PYTHON planetoplot_v2. MAJOR: created an easy way to load a variable from a netcdf file, see easy_get_field.py [note: now to avoid confusion with .f attributes containing field, .f() method is named .func()] ; MINOR: generic units keyword, quiet mode, dummy xy axis when not given in ppplot, bug fixes for one-value 0D requests.

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