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

Last change on this file since 969 was 964, checked in by aslmd, 12 years ago

UTIL PYTHON planetoplot_v2. added attributes showcb and res.

File size: 30.3 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                 showcb=True,\
491                 colorvec="black"):
492        ## get initialization from parent class
493        plot.__init__(self)
494        ## what could be defined by the user
495        self.ordi = ordi
496        self.mapmode = mapmode
497        self.proj = proj
498        self.back = back
499        self.colorb = colorb
500        self.trans = trans
501        self.addvecx = addvecx
502        self.addvecy = addvecy
503        self.colorvec = colorvec
504        self.addcontour = addcontour
505        self.blon = blon ; self.blat = blat
506        self.area = area
507        self.vmin = vmin ; self.vmax = vmax
508        self.showcb = showcb
509
510    # define_from_var
511    # ... this uses settings in set_var.txt
512    # -------------------------------
513    def define_from_var(self):
514        # get what is done in the parent class
515        plot.define_from_var(self)
516        # add specific stuff
517        if self.var is not None:
518         if self.var.upper() in vl.keys():
519          self.colorb = vc[self.var.upper()]
520          self.fmt = vf[self.var.upper()]
521
522    # make
523    # -------------------------------
524    def make(self):
525        # get what is done in the parent class...
526        plot.make(self)
527        if self.fmt is None: self.fmt = "%.2e"
528        # ... then add specific stuff
529        ############################################################################################
530        ### PRE-SETTINGS
531        ############################################################################################
532        # transposing if necessary
533        shape = self.field.shape
534        if shape[0] != shape[1]:
535         if len(self.absc) == shape[0] and len(self.ordi) == shape[1]:
536            print "!! WARNING !! Transposing axes"
537            self.field = np.transpose(self.field)
538        # set dummy xy axis if not defined
539        if self.absc is None: 
540            self.absc = np.array(range(self.field.shape[0]))
541            self.mapmode = False
542            print "!! WARNING !! dummy coordinates on x axis"
543        if self.ordi is None: 
544            self.ordi = np.array(range(self.field.shape[1]))
545            self.mapmode = False
546            print "!! WARNING !! dummy coordinates on y axis"
547        # bound field
548        zevmin, zevmax = calculate_bounds(self.field,vmin=self.vmin,vmax=self.vmax)
549        what_I_plot = bounds(self.field,zevmin,zevmax)
550        # define contour field levels. define color palette
551        ticks = self.div + 1
552        zelevels = np.linspace(zevmin,zevmax,ticks)
553        palette = get_cmap(name=self.colorb)
554        # do the same thing for possible contourline entries
555        if self.addcontour is not None:
556            # if masked array, set masked values to filled values (e.g. np.nan) for plotting purposes
557            if type(self.addcontour).__name__ in 'MaskedArray':
558               self.addcontour[self.addcontour.mask] = self.addcontour.fill_value
559            zevminc, zevmaxc = calculate_bounds(self.addcontour)
560            what_I_contour = bounds(self.addcontour,zevminc,zevmaxc)
561            ticks = self.div + 1
562            zelevelsc = np.linspace(zevminc,zevmaxc,ticks)
563        ############################################################################################
564        ### MAIN PLOT
565        ### NB: contour lines are done before contour shades otherwise colorar error
566        ############################################################################################
567        if not self.mapmode:
568            ## A SIMPLE 2D PLOT
569            ###################
570            # swapping if requested
571            if self.swap:  x = self.ordi ; y = self.absc
572            else:          x = self.absc ; y = self.ordi
573            # coefficients on axis
574            x=x*self.xcoeff ; y=y*self.ycoeff
575            # make shaded and line contours
576            if self.addcontour is not None: 
577                objC = mpl.contour(x, y, what_I_contour, \
578                            zelevelsc, colors = ccol, linewidths = cline)
579                #mpl.clabel(objC, inline=1, fontsize=10)
580            mpl.contourf(x, y, \
581                         self.field, \
582                         zelevels, cmap=palette)
583            # make log axes and/or invert ordinate
584            if self.logx: mpl.semilogx()
585            if self.logy: mpl.semilogy()
586            if self.invert: ax = mpl.gca() ; ax.set_ylim(ax.get_ylim()[::-1])
587        else:
588            ## A 2D MAP USING PROJECTIONS (basemap)
589            #######################################
590            mpl.xlabel("") ; mpl.ylabel("")
591            # additional security in case self.proj is None here
592            # ... we set cylindrical projection (the simplest one)
593            if self.proj is None: self.proj = "cyl"
594            # get lon and lat in 2D version.
595            # (but first ensure we do have 2D coordinates)
596            if self.absc.ndim == 1:     [self.absc,self.ordi] = np.meshgrid(self.absc,self.ordi)
597            elif self.absc.ndim > 2:    print "!! ERROR !! lon and lat arrays must be 1D or 2D"
598            # get lat lon intervals and associated settings
599            wlon = [np.min(self.absc),np.max(self.absc)]
600            wlat = [np.min(self.ordi),np.max(self.ordi)]
601            # -- area presets are in set_area.txt
602            if self.area is not None:
603             if self.area in area.keys():
604                wlon, wlat = area[self.area]
605            # -- settings for meridians and parallels
606            steplon = int(abs(wlon[1]-wlon[0])/6.)
607            steplat = int(abs(wlat[1]-wlat[0])/3.)
608            #mertab = np.r_[wlon[0]:wlon[1]:steplon] ; merlab = [0,0,0,1]
609            #partab = np.r_[wlat[0]:wlat[1]:steplat] ; parlab = [1,0,0,0]
610            mertab = np.r_[-360.:360.:steplon] ; merlab = [0,0,0,1]
611            partab = np.r_[-90.:90.:steplat] ; parlab = [1,0,0,0]
612            format = '%.1f'
613            # -- center of domain and bounding lats
614            lon_0 = 0.5*(wlon[0]+wlon[1])
615            lat_0 = 0.5*(wlat[0]+wlat[1])
616            # some tests, bug fixes, and good-looking settings
617            # ... cyl is good for global and regional
618            if self.proj == "cyl":
619                format = '%.0f'
620            # ... global projections
621            elif self.proj in ["ortho","moll","robin"]:
622                wlat[0] = None ; wlat[1] = None ; wlon[0] = None ; wlon[1] = None
623                steplon = 30. ; steplat = 30.
624                if self.proj in ["robin","moll"]: steplon = 60.
625                mertab = np.r_[-360.:360.:steplon]
626                partab = np.r_[-90.:90.:steplat]
627                if self.proj == "ortho": 
628                    merlab = [0,0,0,0] ; parlab = [0,0,0,0]
629                    # in ortho projection, blon and blat can be used to set map center
630                    if self.blon is not None: lon_0 = self.blon
631                    if self.blat is not None: lat_0 = self.blat
632                elif self.proj == "moll":
633                    merlab = [0,0,0,0]
634                format = '%.0f'
635            # ... regional projections
636            elif self.proj in ["lcc","laea","merc"]:
637                if self.proj in ["lcc","laea"] and wlat[0] == -wlat[1]: 
638                    print "!! ERROR !! with Lambert lat1 must be different than lat2" ; exit()
639                if wlat[0] < -80. and wlat[1] > 80.:
640                    print "!! ERROR !! set an area (not global)" ; exit()
641                format = '%.0f'
642            elif self.proj in ["npstere","spstere"]:
643                # in polar projections, blat gives the bounding lat
644                # if not set, set something reasonable
645                if self.blat is None:   self.blat = 60.
646                # help the user who forgets self.blat would better be negative in spstere
647                # (this actually serves for the default setting just above)
648                if self.proj == "spstere" and self.blat > 0: self.blat = -self.blat
649                # labels
650                mertab = np.r_[-360.:360.:15.]
651                partab = np.r_[-90.:90.:5.]
652            # ... unsupported projections
653            else:
654                print "!! ERROR !! unsupported projection. supported: "+\
655                      "cyl, npstere, spstere, ortho, moll, robin, lcc, laea, merc"
656            # finally define projection
657            m = Basemap(projection=self.proj,\
658                        lat_0=lat_0,lon_0=lon_0,\
659                        boundinglat=self.blat,\
660                        llcrnrlat=wlat[0],urcrnrlat=wlat[1],\
661                        llcrnrlon=wlon[0],urcrnrlon=wlon[1])
662            # draw meridians and parallels
663            ft = int(mpl.rcParams['font.size']*3./4.)
664            zelatmax = 85.
665            m.drawmeridians(mertab,labels=merlab,color='grey',linewidth=0.75,fontsize=ft,fmt=format,latmax=zelatmax)
666            m.drawparallels(partab,labels=parlab,color='grey',linewidth=0.75,fontsize=ft,fmt=format,latmax=zelatmax)
667            # define background (see set_back.txt)
668            if self.back is not None:
669              if self.back in back.keys():
670                 print "**** info: loading a background, please wait.",self.back
671                 if self.back not in ["coast","sea"]:   m.warpimage(back[self.back],scale=0.75)
672                 elif self.back == "coast":             m.drawcoastlines()
673                 elif self.back == "sea":               m.drawlsmask(land_color='white',ocean_color='aqua')
674              else:
675                 print "!! ERROR !! requested background not defined. change name or fill in set_back.txt" ; exit()
676            # define x and y given the projection
677            x, y = m(self.absc, self.ordi)
678            # contour field. first line contour then shaded contour.
679            if self.addcontour is not None: 
680                objC2 = m.contour(x, y, what_I_contour, \
681                            zelevelsc, colors = ccol, linewidths = cline)
682                #mpl.clabel(objC2, inline=1, fontsize=10)
683            m.contourf(x, y, what_I_plot, zelevels, cmap = palette, alpha = self.trans)
684        ############################################################################################
685        ### COLORBAR
686        ############################################################################################
687        if self.trans > 0. and self.showcb:
688            ## draw colorbar. settings are different with projections. or if not mapmode.
689            if not self.mapmode: orientation=zeorientation ; frac = 0.075 ; pad = 0.03 ; lu = 0.5
690            elif self.proj in ['moll']: orientation="horizontal" ; frac = 0.08 ; pad = 0.03 ; lu = 1.0
691            elif self.proj in ['cyl']: orientation="vertical" ; frac = 0.023 ; pad = 0.03 ; lu = 0.5
692            else: orientation = zeorientation ; frac = zefrac ; pad = 0.03 ; lu = 0.5
693            zelevpal = np.linspace(zevmin,zevmax,num=min([ticks/2+1,21]))
694            zecb = mpl.colorbar(fraction=frac,pad=pad,\
695                                format=self.fmt,orientation=orientation,\
696                                ticks=zelevpal,\
697                                extend='neither',spacing='proportional')
698            if zeorientation == "horizontal": zecb.ax.set_xlabel(self.title) ; self.title = ""
699            # colorbar title --> units
700            if self.units not in ["dimless",""]:
701                zecb.ax.set_title("["+self.units+"]",fontsize=3.*mpl.rcParams['font.size']/4.,x=lu,y=1.025)
702
703        ############################################################################################
704        ### VECTORS. must be after the colorbar. we could also leave possibility for streamlines.
705        ############################################################################################
706        ### not expecting NaN in self.addvecx and self.addvecy. masked arrays is just enough.
707        stride = 3
708        #stride = 1
709        if self.addvecx is not None and self.addvecy is not None and self.mapmode:
710                ### for metwinds only ???
711                [vecx,vecy] = m.rotate_vector(self.addvecx,self.addvecy,self.absc,self.ordi) 
712                #vecx,vecy = self.addvecx,self.addvecy
713                # reference vector is scaled
714                zescale = ppcompute.mean(np.sqrt(self.addvecx*self.addvecx+self.addvecy*self.addvecy))
715                #zescale = 25.
716                # make vector field
717                q = m.quiver( x[::stride,::stride],y[::stride,::stride],\
718                              vecx[::stride,::stride],vecy[::stride,::stride],\
719                              angles='xy',color=self.colorvec,pivot='middle',\
720                              scale=zescale*reducevec,width=widthvec )
721                # make vector key.
722                #keyh = 1.025 ; keyv = 1.05 # upper right corner over colorbar
723                keyh = 0.98 ; keyv = 1.06
724                keyh = 0.98 ; keyv = 1.07
725                #keyh = -0.03 ; keyv = 1.08 # upper left corner
726                p = mpl.quiverkey(q,keyh,keyv,\
727                                  zescale,str(int(zescale)),\
728                                  color='black',labelpos='S',labelsep = 0.07)
729        ############################################################################################
730        ### TEXT. ANYWHERE. add_text.txt should be present with lines x ; y ; text ; color
731        ############################################################################################
732        try:
733            f = open("add_text.txt", 'r')
734            for line in f:
735              if "#" in line: pass
736              else:
737                  userx, usery, usert, userc = line.strip().split(';')
738                  userc = userc.strip()
739                  usert = usert.strip()
740                  userx = float(userx.strip())
741                  usery = float(usery.strip())
742                  if self.mapmode: userx,usery = m(userx,usery)
743                  mpl.text(userx,usery,usert,\
744                           color = userc,\
745                           horizontalalignment='center',\
746                           verticalalignment='center')
747            f.close()
748        except IOError:
749            pass
Note: See TracBrowser for help on using the repository browser.