source: trunk/python/asaplotbase.py@ 1898

Last change on this file since 1898 was 1870, checked in by Malte Marquarding, 14 years ago

Added svg support

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