source: trunk/python/asaplotbase.py @ 2699

Last change on this file since 2699 was 2699, checked in by Kana Sugimoto, 11 years ago

New Development: No

JIRA Issue: No (bug fixes)

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs: unit tests of sdplot

Put in Release Notes: No

Module(s): asapplotter and sdplot

Description:

Fixed a bug which caused failure of plots by user defined linestyles.
Made sure data is plotted on mpl plotter (not on ASAP plotter) by
plotpointing and plotazel.


  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 29.9 KB
RevLine 
[705]1"""
2ASAP plotting class based on matplotlib.
3"""
4
5import sys
6from re import match
7import matplotlib
8
9from matplotlib.figure import Figure, Text
[1147]10from matplotlib.font_manager import FontProperties as FP
[1739]11from numpy import sqrt
[705]12from matplotlib import rc, rcParams
[1259]13from matplotlib.ticker import OldScalarFormatter
[2538]14from matplotlib import _pylab_helpers
[1147]15
[1826]16from asap.parameters import rcParams as asaprcParams
[1861]17from asap.logging import asaplog
[1826]18
[1425]19# API change in mpl >= 0.98
20try:
21    from matplotlib.transforms import blended_transform_factory
22except ImportError:
[1560]23    from matplotlib.transforms import blend_xy_sep_transform as blended_transform_factory
[1425]24
[2169]25mvers = matplotlib.__version__.split(".")
26if int(mvers[0]) == 0 and int(mvers[1]) < 99:
[1819]27    #print "Warning: matplotlib version < 0.87. This might cause errors. Please upgrade."
[1826]28    asaplog.push( "matplotlib version < 0.99. This might cause errors. Please upgrade." )
[1861]29    asaplog.post( 'WARN' )
[1019]30
[705]31class asaplotbase:
32    """
33    ASAP plotting base class based on matplotlib.
34    """
35
[1563]36    def __init__(self, rows=1, cols=0, title='', size=None, buffering=False):
[1019]37        """
38        Create a new instance of the ASAPlot plotting class.
[705]39
[1019]40        If rows < 1 then a separate call to set_panels() is required to define
41        the panel layout; refer to the doctext for set_panels().
42        """
[705]43        self.is_dead = False
[1019]44        self.figure = Figure(figsize=size, facecolor='#ddddee')
[705]45        self.canvas = None
46
[1019]47        self.set_title(title)
48        self.subplots = []
49        if rows > 0:
50            self.set_panels(rows, cols)
[705]51
[710]52        # Set matplotlib default colour sequence.
53        self.colormap = "green red black cyan magenta orange blue purple yellow pink".split()
[1019]54
[710]55        c = asaprcParams['plotter.colours']
56        if isinstance(c,str) and len(c) > 0:
57            self.colormap = c.split()
[2699]58        # line styles need to be set as a list of numbers to use set_dashes
59        self.lsalias = {"line":  [1,0],
60                        "dashdot": [4,2,1,2],
61                        "dashed" : [4,2,4,2],
62                        "dotted" : [1,2],
[710]63                        "dashdotdot": [4,2,1,2,1,2],
64                        "dashdashdot": [4,2,4,2,1,2]
65                        }
66
67        styles = "line dashed dotted dashdot".split()
68        c = asaprcParams['plotter.linestyles']
69        if isinstance(c,str) and len(c) > 0:
70            styles = c.split()
71        s = []
72        for ls in styles:
73            if self.lsalias.has_key(ls):
74                s.append(self.lsalias.get(ls))
75            else:
76                s.append('-')
77        self.linestyles = s
78
[705]79        self.color = 0;
[710]80        self.linestyle = 0;
[1019]81        self.attributes = {}
82        self.loc = 0
[705]83
[1019]84        self.buffering = buffering
[705]85
[2451]86        self.events = {'button_press':None,
87                       'button_release':None,
88                       'motion_notify':None}
89
[705]90    def clear(self):
[1019]91        """
[2693]92        Delete all lines from the current subplot.
93        Line numbering will restart from 0.
[1019]94        """
[705]95
[2697]96        #for i in range(len(self.lines)):
97        #   self.delete(i)
[1019]98        self.axes.clear()
99        self.color = 0
[2699]100        self.linestyle = 0
[1019]101        self.lines = []
[2697]102        self.subplots[self.i]['lines'] = self.lines
[705]103
[710]104    def palette(self, color, colormap=None, linestyle=0, linestyles=None):
[705]105        if colormap:
[710]106            if isinstance(colormap,list):
107                self.colormap = colormap
108            elif isinstance(colormap,str):
109                self.colormap = colormap.split()
[705]110        if 0 <= color < len(self.colormap):
111            self.color = color
[710]112        if linestyles:
113            self.linestyles = []
114            if isinstance(linestyles,list):
115                styles = linestyles
116            elif isinstance(linestyles,str):
117                styles = linestyles.split()
118            for ls in styles:
119                if self.lsalias.has_key(ls):
120                    self.linestyles.append(self.lsalias.get(ls))
121                else:
122                    self.linestyles.append(self.lsalias.get('line'))
123        if 0 <= linestyle < len(self.linestyles):
124            self.linestyle = linestyle
[705]125
126    def delete(self, numbers=None):
[1019]127        """
128        Delete the 0-relative line number, default is to delete the last.
129        The remaining lines are NOT renumbered.
130        """
[705]131
[1019]132        if numbers is None: numbers = [len(self.lines)-1]
[705]133
[1019]134        if not hasattr(numbers, '__iter__'):
135            numbers = [numbers]
[705]136
[1019]137        for number in numbers:
138            if 0 <= number < len(self.lines):
139                if self.lines[number] is not None:
140                    for line in self.lines[number]:
141                        line.set_linestyle('None')
142                        self.lines[number] = None
143        self.show()
[705]144
145    def get_line(self):
[1019]146        """
147        Get the current default line attributes.
148        """
149        return self.attributes
[705]150
151
[1086]152    def hist(self, x=None, y=None, fmt=None, add=None):
[1019]153        """
154        Plot a histogram.  N.B. the x values refer to the start of the
155        histogram bin.
[705]156
[1019]157        fmt is the line style as in plot().
158        """
[1739]159        from numpy import array
160        from numpy.ma import MaskedArray
[1019]161        if x is None:
162            if y is None: return
[1023]163            x = range(len(y))
[705]164
[1019]165        if len(x) != len(y):
166            return
167        l2 = 2*len(x)
[1023]168        x2 = range(l2)
[1086]169        y2 = range(12)
[1023]170        y2 = range(l2)
171        m2 = range(l2)
[1553]172        ymsk = None
173        ydat = None
174        if hasattr(y, "raw_mask"):
175            # numpy < 1.1
176            ymsk = y.raw_mask()
177            ydat = y.raw_data()
178        else:
179            ymsk = y.mask
180            ydat = y.data
[1023]181        for i in range(l2):
[1019]182            x2[i] = x[i/2]
[1086]183            m2[i] = ymsk[i/2]
[705]184
[1023]185        y2[0] = 0.0
[1019]186        for i in range(1,l2):
[1086]187            y2[i] = ydat[(i-1)/2]
[705]188
[1086]189        self.plot(x2, MaskedArray(y2,mask=m2,copy=0), fmt, add)
[705]190
191
192    def hold(self, hold=True):
[1019]193        """
194        Buffer graphics until subsequently released.
195        """
196        self.buffering = hold
[705]197
198
199    def legend(self, loc=None):
[1019]200        """
201        Add a legend to the plot.
[705]202
[1019]203        Any other value for loc else disables the legend:
204             1: upper right
205             2: upper left
206             3: lower left
207             4: lower right
208             5: right
209             6: center left
210             7: center right
211             8: lower center
212             9: upper center
213            10: center
[705]214
[1019]215        """
[1095]216        if isinstance(loc, int):
[1098]217            self.loc = None
218            if 0 <= loc <= 10: self.loc = loc
[1095]219        else:
220            self.loc = None
221        #self.show()
[705]222
223
[1086]224    def plot(self, x=None, y=None, fmt=None, add=None):
[1019]225        """
226        Plot the next line in the current frame using the current line
227        attributes.  The ASAPlot graphics window will be mapped and raised.
[705]228
[1019]229        The argument list works a bit like the matlab plot() function.
230        """
231        if x is None:
232            if y is None: return
233            x = range(len(y))
[705]234
[1019]235        elif y is None:
236            y = x
237            x = range(len(y))
[1086]238        if fmt is None:
239            line = self.axes.plot(x, y)
[1019]240        else:
[1086]241            line = self.axes.plot(x, y, fmt)
[1980]242        # add a picker to lines for spectral value mode.
243        # matplotlib.axes.plot returns a list of line object (1 element)
244        line[0].set_picker(5.0)
[705]245
[1019]246        # Add to an existing line?
[1086]247        i = None
[1019]248        if add is None or len(self.lines) < add < 0:
249            # Don't add.
250            self.lines.append(line)
251            i = len(self.lines) - 1
252        else:
253            if add == 0: add = len(self.lines)
254            i = add - 1
255            self.lines[i].extend(line)
[705]256
[1019]257        # Set/reset attributes for the line.
258        gotcolour = False
259        for k, v in self.attributes.iteritems():
260            if k == 'color': gotcolour = True
261            for segment in self.lines[i]:
262                getattr(segment, "set_%s"%k)(v)
[705]263
[1019]264        if not gotcolour and len(self.colormap):
265            for segment in self.lines[i]:
266                getattr(segment, "set_color")(self.colormap[self.color])
[710]267                if len(self.colormap)  == 1:
268                    getattr(segment, "set_dashes")(self.linestyles[self.linestyle])
[1086]269
[1019]270            self.color += 1
271            if self.color >= len(self.colormap):
272                self.color = 0
[705]273
[710]274            if len(self.colormap) == 1:
275                self.linestyle += 1
[1019]276            if self.linestyle >= len(self.linestyles):
277                self.linestyle = 0
[710]278
[1019]279        self.show()
[705]280
281
282    def position(self):
[1019]283        """
284        Use the mouse to get a position from a graph.
285        """
[705]286
[1019]287        def position_disable(event):
288            self.register('button_press', None)
289            print '%.4f, %.4f' % (event.xdata, event.ydata)
[705]290
[1019]291        print 'Press any mouse button...'
292        self.register('button_press', position_disable)
[705]293
294
[1546]295    def get_region(self):
296        pos = []
[1568]297        print "Please select the bottom/left point"
[1546]298        pos.append(self.figure.ginput(n=1, show_clicks=False)[0])
[1568]299        print "Please select the top/right point"
[1546]300        pos.append(self.figure.ginput(n=1, show_clicks=False)[0])
301        return pos
302
303    def get_point(self):
[1568]304        print "Please select the point"
[1553]305        pt = self.figure.ginput(n=1, show_clicks=False)
306        if pt:
307            return pt[0]
308        else:
309            return None
[1546]310
[705]311    def region(self):
[1019]312        """
313        Use the mouse to get a rectangular region from a plot.
[705]314
[1019]315        The return value is [x0, y0, x1, y1] in world coordinates.
316        """
[705]317
[1019]318        def region_start(event):
[1819]319            self.rect = {'x': event.x, 'y': event.y,
[1019]320                         'world': [event.xdata, event.ydata,
321                                   event.xdata, event.ydata]}
322            self.register('button_press', None)
323            self.register('motion_notify', region_draw)
324            self.register('button_release', region_disable)
[705]325
[1019]326        def region_draw(event):
[1819]327            self.figmgr.toolbar.draw_rubberband(event, event.x, event.y,
328                                                self.rect['x'], self.rect['y'])
[1826]329
[1019]330        def region_disable(event):
331            self.register('motion_notify', None)
332            self.register('button_release', None)
[705]333
[1019]334            self.rect['world'][2:4] = [event.xdata, event.ydata]
335            print '(%.2f, %.2f)  (%.2f, %.2f)' % (self.rect['world'][0],
336                self.rect['world'][1], self.rect['world'][2],
337                self.rect['world'][3])
[1819]338            self.figmgr.toolbar.release(event)
[705]339
[1019]340        self.register('button_press', region_start)
[705]341
[1019]342        # This has to be modified to block and return the result (currently
343        # printed by region_disable) when that becomes possible in matplotlib.
[705]344
[1019]345        return [0.0, 0.0, 0.0, 0.0]
[705]346
347
348    def register(self, type=None, func=None):
[1019]349        """
350        Register, reregister, or deregister events of type 'button_press',
351        'button_release', or 'motion_notify'.
[705]352
[1019]353        The specified callback function should have the following signature:
[705]354
[1019]355            def func(event)
[705]356
[1019]357        where event is an MplEvent instance containing the following data:
[705]358
[1019]359            name                # Event name.
360            canvas              # FigureCanvas instance generating the event.
361            x      = None       # x position - pixels from left of canvas.
362            y      = None       # y position - pixels from bottom of canvas.
363            button = None       # Button pressed: None, 1, 2, 3.
364            key    = None       # Key pressed: None, chr(range(255)), shift,
365                                  win, or control
366            inaxes = None       # Axes instance if cursor within axes.
367            xdata  = None       # x world coordinate.
368            ydata  = None       # y world coordinate.
[705]369
[1019]370        For example:
[705]371
[1019]372            def mouse_move(event):
373                print event.xdata, event.ydata
[705]374
[1019]375            a = asaplot()
376            a.register('motion_notify', mouse_move)
[705]377
[1019]378        If func is None, the event is deregistered.
[705]379
[1019]380        Note that in TkAgg keyboard button presses don't generate an event.
381        """
[705]382
[1019]383        if not self.events.has_key(type): return
[705]384
[1019]385        if func is None:
386            if self.events[type] is not None:
387                # It's not clear that this does anything.
388                self.canvas.mpl_disconnect(self.events[type])
389                self.events[type] = None
[705]390
[1819]391                # It seems to be necessary to return events to the toolbar. <-- Not ture. 2010.Jul.14.kana.
392                #if type == 'motion_notify':
393                #    self.canvas.mpl_connect(type + '_event',
394                #        self.figmgr.toolbar.mouse_move)
395                #elif type == 'button_press':
396                #    self.canvas.mpl_connect(type + '_event',
397                #        self.figmgr.toolbar.press)
398                #elif type == 'button_release':
399                #    self.canvas.mpl_connect(type + '_event',
400                #        self.figmgr.toolbar.release)
[705]401
[1019]402        else:
403            self.events[type] = self.canvas.mpl_connect(type + '_event', func)
[705]404
405
406    def release(self):
[1019]407        """
408        Release buffered graphics.
409        """
410        self.buffering = False
411        self.show()
[705]412
413
[1095]414    def save(self, fname=None, orientation=None, dpi=None, papertype=None):
[1019]415        """
416        Save the plot to a file.
[705]417
[1019]418        fname is the name of the output file.  The image format is determined
419        from the file suffix; 'png', 'ps', and 'eps' are recognized.  If no
420        file name is specified 'yyyymmdd_hhmmss.png' is created in the current
421        directory.
422        """
[1095]423        from asap import rcParams
424        if papertype is None:
425            papertype = rcParams['plotter.papertype']
[1019]426        if fname is None:
427            from datetime import datetime
428            dstr = datetime.now().strftime('%Y%m%d_%H%M%S')
429            fname = 'asap'+dstr+'.png'
[705]430
[1870]431        d = ['png','.ps','eps', 'svg']
[705]432
[1019]433        from os.path import expandvars
434        fname = expandvars(fname)
[705]435
[1019]436        if fname[-3:].lower() in d:
437            try:
[705]438                if fname[-3:].lower() == ".ps":
[1020]439                    from matplotlib import __version__ as mv
[1479]440                    w = self.figure.get_figwidth()
441                    h = self.figure.get_figheight()
[1019]442
[705]443                    if orientation is None:
[1147]444                        # oriented
[705]445                        if w > h:
446                            orientation = 'landscape'
447                        else:
448                            orientation = 'portrait'
[1095]449                    from matplotlib.backends.backend_ps import papersize
450                    pw,ph = papersize[papertype.lower()]
[1025]451                    ds = None
452                    if orientation == 'landscape':
[1095]453                        ds = min(ph/w, pw/h)
[1025]454                    else:
[1095]455                        ds = min(pw/w, ph/h)
[1025]456                    ow = ds * w
457                    oh = ds * h
[1479]458                    self.figure.set_size_inches((ow, oh))
[1095]459                    self.figure.savefig(fname, orientation=orientation,
460                                        papertype=papertype.lower())
[1479]461                    self.figure.set_size_inches((w, h))
[705]462                    print 'Written file %s' % (fname)
[1019]463                else:
[705]464                    if dpi is None:
465                        dpi =150
[1025]466                    self.figure.savefig(fname,dpi=dpi)
[705]467                    print 'Written file %s' % (fname)
[1019]468            except IOError, msg:
[1819]469                #print 'Failed to save %s: Error msg was\n\n%s' % (fname, err)
[1861]470                asaplog.post()
[1819]471                asaplog.push('Failed to save %s: Error msg was\n\n%s' % (fname, str(msg)))
[1861]472                asaplog.post( 'ERROR' )
[1019]473                return
474        else:
[1819]475            #print "Invalid image type. Valid types are:"
476            #print "'ps', 'eps', 'png'"
477            asaplog.push( "Invalid image type. Valid types are:" )
[1870]478            asaplog.push( "'ps', 'eps', 'png', 'svg'" )
[1861]479            asaplog.post('WARN')
[705]480
481
482    def set_axes(self, what=None, *args, **kwargs):
[1019]483        """
484        Set attributes for the axes by calling the relevant Axes.set_*()
485        method.  Colour translation is done as described in the doctext
486        for palette().
487        """
[705]488
[1019]489        if what is None: return
490        if what[-6:] == 'colour': what = what[:-6] + 'color'
[705]491
[1153]492        key = "colour"
493        if kwargs.has_key(key):
494            val = kwargs.pop(key)
495            kwargs["color"] = val
[705]496
[1153]497        getattr(self.axes, "set_%s"%what)(*args, **kwargs)
[705]498
[1153]499        self.show(hardrefresh=False)
[705]500
[1019]501
[705]502    def set_figure(self, what=None, *args, **kwargs):
[1019]503        """
504        Set attributes for the figure by calling the relevant Figure.set_*()
505        method.  Colour translation is done as described in the doctext
506        for palette().
507        """
[705]508
[1019]509        if what is None: return
510        if what[-6:] == 'colour': what = what[:-6] + 'color'
511        #if what[-5:] == 'color' and len(args):
512        #    args = (get_colour(args[0]),)
[705]513
[1019]514        newargs = {}
515        for k, v in kwargs.iteritems():
516            k = k.lower()
517            if k == 'colour': k = 'color'
518            newargs[k] = v
[705]519
[1019]520        getattr(self.figure, "set_%s"%what)(*args, **newargs)
[1153]521        self.show(hardrefresh=False)
[705]522
523
524    def set_limits(self, xlim=None, ylim=None):
[1019]525        """
526        Set x-, and y-limits for each subplot.
[705]527
[1019]528        xlim = [xmin, xmax] as in axes.set_xlim().
529        ylim = [ymin, ymax] as in axes.set_ylim().
530        """
531        for s in self.subplots:
532            self.axes  = s['axes']
533            self.lines = s['lines']
[705]534            oldxlim =  list(self.axes.get_xlim())
535            oldylim =  list(self.axes.get_ylim())
536            if xlim is not None:
537                for i in range(len(xlim)):
538                    if xlim[i] is not None:
539                        oldxlim[i] = xlim[i]
[1019]540            if ylim is not None:
[705]541                for i in range(len(ylim)):
542                    if ylim[i] is not None:
543                        oldylim[i] = ylim[i]
544            self.axes.set_xlim(oldxlim)
545            self.axes.set_ylim(oldylim)
546        return
547
548
549    def set_line(self, number=None, **kwargs):
[1019]550        """
551        Set attributes for the specified line, or else the next line(s)
552        to be plotted.
[705]553
[1019]554        number is the 0-relative number of a line that has already been
555        plotted.  If no such line exists, attributes are recorded and used
556        for the next line(s) to be plotted.
[705]557
[1019]558        Keyword arguments specify Line2D attributes, e.g. color='r'.  Do
[705]559
[1019]560            import matplotlib
561            help(matplotlib.lines)
[705]562
[1019]563        The set_* methods of class Line2D define the attribute names and
[2451]564        values.  For non-US usage, 'colour' is recognized as synonymous with
565        'color'.
[705]566
[1019]567        Set the value to None to delete an attribute.
[705]568
[1019]569        Colour translation is done as described in the doctext for palette().
570        """
[705]571
[1019]572        redraw = False
573        for k, v in kwargs.iteritems():
574            k = k.lower()
575            if k == 'colour': k = 'color'
[705]576
[1019]577            if 0 <= number < len(self.lines):
578                if self.lines[number] is not None:
579                    for line in self.lines[number]:
580                        getattr(line, "set_%s"%k)(v)
581                    redraw = True
582            else:
583                if v is None:
584                    del self.attributes[k]
585                else:
586                    self.attributes[k] = v
[705]587
[1153]588        if redraw: self.show(hardrefresh=False)
[705]589
590
[1819]591    #def set_panels(self, rows=1, cols=0, n=-1, nplots=-1, ganged=True):
[2037]592    def set_panels(self, rows=1, cols=0, n=-1, nplots=-1, margin=None,ganged=True):
[1019]593        """
594        Set the panel layout.
[705]595
[1019]596        rows and cols, if cols != 0, specify the number of rows and columns in
597        a regular layout.   (Indexing of these panels in matplotlib is row-
598        major, i.e. column varies fastest.)
[705]599
[1019]600        cols == 0 is interpreted as a retangular layout that accomodates
601        'rows' panels, e.g. rows == 6, cols == 0 is equivalent to
602        rows == 2, cols == 3.
[705]603
[1019]604        0 <= n < rows*cols is interpreted as the 0-relative panel number in
605        the configuration specified by rows and cols to be added to the
606        current figure as its next 0-relative panel number (i).  This allows
607        non-regular panel layouts to be constructed via multiple calls.  Any
608        other value of n clears the plot and produces a rectangular array of
609        empty panels.  The number of these may be limited by nplots.
610        """
611        if n < 0 and len(self.subplots):
612            self.figure.clear()
613            self.set_title()
[705]614
[2037]615        if margin:
616            lef, bot, rig, top, wsp, hsp = margin
[1819]617            self.figure.subplots_adjust(
618                left=lef,bottom=bot,right=rig,top=top,wspace=wsp,hspace=hsp)
619            del lef,bot,rig,top,wsp,hsp
620
[1019]621        if rows < 1: rows = 1
[705]622
[1019]623        if cols <= 0:
624            i = int(sqrt(rows))
625            if i*i < rows: i += 1
626            cols = i
[705]627
[1019]628            if i*(i-1) >= rows: i -= 1
629            rows = i
[705]630
[1019]631        if 0 <= n < rows*cols:
632            i = len(self.subplots)
[1819]633
[1019]634            self.subplots.append({})
[705]635
[1019]636            self.subplots[i]['axes']  = self.figure.add_subplot(rows,
637                                            cols, n+1)
638            self.subplots[i]['lines'] = []
[705]639
[1019]640            if i == 0: self.subplot(0)
[705]641
[1019]642            self.rows = 0
643            self.cols = 0
[705]644
[1019]645        else:
646            self.subplots = []
[705]647
[1019]648            if nplots < 1 or rows*cols < nplots:
649                nplots = rows*cols
[1025]650            if ganged:
651                hsp,wsp = None,None
652                if rows > 1: hsp = 0.0001
653                if cols > 1: wsp = 0.0001
654                self.figure.subplots_adjust(wspace=wsp,hspace=hsp)
[1019]655            for i in range(nplots):
656                self.subplots.append({})
[1153]657                self.subplots[i]['lines'] = []
658                if not ganged:
659                    self.subplots[i]['axes'] = self.figure.add_subplot(rows,
[1019]660                                                cols, i+1)
[1560]661                    if asaprcParams['plotter.axesformatting'] != 'mpl':
[1513]662                        self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter())
[1153]663                else:
664                    if i == 0:
665                        self.subplots[i]['axes'] = self.figure.add_subplot(rows,
666                                                cols, i+1)
[1560]667                        if asaprcParams['plotter.axesformatting'] != 'mpl':
[1826]668
[1513]669                            self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter())
[1153]670                    else:
671                        self.subplots[i]['axes'] = self.figure.add_subplot(rows,
672                                                cols, i+1,
673                                                sharex=self.subplots[0]['axes'],
674                                                sharey=self.subplots[0]['axes'])
[1259]675
[705]676                    # Suppress tick labelling for interior subplots.
677                    if i <= (rows-1)*cols - 1:
678                        if i+cols < nplots:
679                            # Suppress x-labels for frames width
680                            # adjacent frames
[1153]681                            for tick in self.subplots[i]['axes'].xaxis.majorTicks:
682                                tick.label1On = False
[1926]683                            #self.subplots[i]['axes'].xaxis.label.set_visible(False)
[705]684                    if i%cols:
685                        # Suppress y-labels for frames not in the left column.
686                        for tick in self.subplots[i]['axes'].yaxis.majorTicks:
687                            tick.label1On = False
[1926]688                        #self.subplots[i]['axes'].yaxis.label.set_visible(False)
[1025]689                    # disable the first tick of [1:ncol-1] of the last row
[1153]690                    #if i+1 < nplots:
691                    #    self.subplots[i]['axes'].xaxis.majorTicks[0].label1On = False
[1926]692                # set axes label state for interior subplots.
693                if i%cols:
694                    self.subplots[i]['axes'].yaxis.label.set_visible(False)
695                if (i <= (rows-1)*cols - 1) and (i+cols < nplots):
696                    self.subplots[i]['axes'].xaxis.label.set_visible(False)
697            self.rows = rows
698            self.cols = cols
[1019]699            self.subplot(0)
[2037]700        del rows,cols,n,nplots,margin,ganged,i
[705]701
[1926]702
[1153]703    def tidy(self):
704        # this needs to be exceuted after the first "refresh"
705        nplots = len(self.subplots)
706        if nplots == 1: return
707        for i in xrange(nplots):
708            ax = self.subplots[i]['axes']
709            if i%self.cols:
710                ax.xaxis.majorTicks[0].label1On = False
711            else:
712                if i != 0:
713                    ax.yaxis.majorTicks[-1].label1On = False
[1926]714            ## set axes label state for interior subplots.
715            #innerax=False
716            #if i%self.cols:
717            #    ax.yaxis.label.set_visible(innerax)
718            #if (i <= (self.rows-1)*self.cols - 1) and (i+self.cols < nplots):
719            #    ax.xaxis.label.set_visible(innerax)
720           
[1153]721
[705]722    def set_title(self, title=None):
[1019]723        """
724        Set the title of the plot window.  Use the previous title if title is
725        omitted.
726        """
727        if title is not None:
728            self.title = title
[705]729
[1019]730        self.figure.text(0.5, 0.95, self.title, horizontalalignment='center')
[705]731
732
[1153]733    def show(self, hardrefresh=True):
[1019]734        """
735        Show graphics dependent on the current buffering state.
736        """
[1153]737        if not hardrefresh: return
[1019]738        if not self.buffering:
739            if self.loc is not None:
[1086]740                for sp in self.subplots:
[1019]741                    lines  = []
742                    labels = []
743                    i = 0
[1086]744                    for line in sp['lines']:
[1019]745                        i += 1
746                        if line is not None:
747                            lines.append(line[0])
748                            lbl = line[0].get_label()
749                            if lbl == '':
750                                lbl = str(i)
751                            labels.append(lbl)
[705]752
[1019]753                    if len(lines):
[1147]754                        fp = FP(size=rcParams['legend.fontsize'])
[2068]755                        #fsz = fp.get_size_in_points() - len(lines)
756                        fsz = fp.get_size_in_points() - max(len(lines),self.cols)
757                        #fp.set_size(max(fsz,6))
758                        fp.set_size(max(fsz,8))
[1086]759                        sp['axes'].legend(tuple(lines), tuple(labels),
[1147]760                                          self.loc, prop=fp)
[1946]761                    #else:
762                    #    sp['axes'].legend((' '))
[705]763
[1086]764            from matplotlib.artist import setp
[1560]765            fpx = FP(size=rcParams['xtick.labelsize'])
766            xts = fpx.get_size_in_points()- (self.cols)/2
767            fpy = FP(size=rcParams['ytick.labelsize'])
768            yts = fpy.get_size_in_points() - (self.rows)/2
769            fpa = FP(size=rcParams['axes.labelsize'])
770            fpat = FP(size=rcParams['axes.titlesize'])
771            axsize =  fpa.get_size_in_points()
[1819]772            tsize =  fpat.get_size_in_points()-(self.cols)/2
[1086]773            for sp in self.subplots:
774                ax = sp['axes']
[1819]775                ax.title.set_size(tsize)
[1086]776                setp(ax.get_xticklabels(), fontsize=xts)
777                setp(ax.get_yticklabels(), fontsize=yts)
778                off = 0
[1819]779                if self.cols > 1: off = self.cols
[1560]780                ax.xaxis.label.set_size(axsize-off)
[1819]781                off = 0
782                if self.rows > 1: off = self.rows
[1560]783                ax.yaxis.label.set_size(axsize-off)
[705]784
785    def subplot(self, i=None, inc=None):
[1019]786        """
787        Set the subplot to the 0-relative panel number as defined by one or
788        more invokations of set_panels().
789        """
790        l = len(self.subplots)
791        if l:
792            if i is not None:
793                self.i = i
[705]794
[1019]795            if inc is not None:
796                self.i += inc
[705]797
[1019]798            self.i %= l
799            self.axes  = self.subplots[self.i]['axes']
800            self.lines = self.subplots[self.i]['lines']
[705]801
802    def text(self, *args, **kwargs):
[1019]803        """
804        Add text to the figure.
805        """
806        self.figure.text(*args, **kwargs)
807        self.show()
[1147]808
809    def vline_with_label(self, x, y, label,
810                         location='bottom', rotate=0.0, **kwargs):
811        """
812        Plot a vertical line with label.
813        It takes "world" values fo x and y.
814        """
815        ax = self.axes
816        # need this to suppress autoscaling during this function
817        self.axes.set_autoscale_on(False)
818        ymin = 0.0
819        ymax = 1.0
820        valign = 'center'
821        if location.lower() == 'top':
822            y = max(0.0, y)
823        elif location.lower() == 'bottom':
824            y = min(0.0, y)
825        lbloffset = 0.06
826        # a rough estimate for the bb of the text
827        if rotate > 0.0: lbloffset = 0.03*len(label)
828        peakoffset = 0.01
[1535]829        xy = None
830        xy0 = None
831        # matplotlib api change 0.98 is using transform now
832        if hasattr(ax.transData, "inverse_xy_tup"):
833            # get relative coords
834            xy0 = ax.transData.xy_tup((x,y))
835            xy = ax.transAxes.inverse_xy_tup(xy0)
836        else:
837            xy0 = ax.transData.transform((x,y))
838            # get relative coords
839            xy = ax.transAxes.inverted().transform(xy0)
[1147]840        if location.lower() == 'top':
841            ymax = 1.0-lbloffset
842            ymin = xy[1]+peakoffset
843            valign = 'bottom'
844            ylbl = ymax+0.01
845        elif location.lower() == 'bottom':
846            ymin = lbloffset
847            ymax = xy[1]-peakoffset
848            valign = 'top'
849            ylbl = ymin-0.01
[1425]850        trans = blended_transform_factory(ax.transData, ax.transAxes)
[1147]851        l = ax.axvline(x, ymin, ymax, color='black', **kwargs)
852        t = ax.text(x, ylbl ,label, verticalalignment=valign,
853                                    horizontalalignment='center',
854                    rotation=rotate,transform = trans)
855        self.axes.set_autoscale_on(True)
[2538]856
857    def _alive(self):
858        # Return True if the GUI alives.
859        if (not self.is_dead) and \
860               self.figmgr and hasattr(self.figmgr, "num"):
861            figid = self.figmgr.num
862            # Make sure figid=0 is what asapplotter expects.
863            # It might be already destroied/overridden by matplotlib
864            # commands or other methods using asaplot.
865            return _pylab_helpers.Gcf.has_fignum(figid) and \
866                   (self.figmgr == _pylab_helpers.Gcf.get_fig_manager(figid))
867        return False
Note: See TracBrowser for help on using the repository browser.