[705] | 1 | """
|
---|
| 2 | ASAP plotting class based on matplotlib.
|
---|
| 3 | """
|
---|
| 4 |
|
---|
| 5 | import sys
|
---|
| 6 | from re import match
|
---|
| 7 |
|
---|
| 8 | import matplotlib
|
---|
| 9 |
|
---|
| 10 | from matplotlib.figure import Figure, Text
|
---|
| 11 | from matplotlib.font_manager import FontProperties
|
---|
| 12 | from matplotlib.numerix import sqrt
|
---|
| 13 | from matplotlib import rc, rcParams
|
---|
[710] | 14 | from asap import rcParams as asaprcParams
|
---|
[705] | 15 |
|
---|
[1019] | 16 | from matplotlib.ticker import ScalarFormatter
|
---|
| 17 | from matplotlib.ticker import NullLocator
|
---|
| 18 |
|
---|
| 19 | class MyFormatter(ScalarFormatter):
|
---|
| 20 | def __call__(self, x, pos=None):
|
---|
| 21 | last = len(self.locs)-2
|
---|
| 22 | if pos==last:
|
---|
| 23 | print "Diabling tick no " , pos, last
|
---|
| 24 | return '' # pos=-1 is the last tick
|
---|
| 25 | else: return ScalarFormatter.__call__(self, x, pos)
|
---|
| 26 |
|
---|
[705] | 27 | class asaplotbase:
|
---|
| 28 | """
|
---|
| 29 | ASAP plotting base class based on matplotlib.
|
---|
| 30 | """
|
---|
| 31 |
|
---|
| 32 | def __init__(self, rows=1, cols=0, title='', size=(8,6), buffering=False):
|
---|
[1019] | 33 | """
|
---|
| 34 | Create a new instance of the ASAPlot plotting class.
|
---|
[705] | 35 |
|
---|
[1019] | 36 | If rows < 1 then a separate call to set_panels() is required to define
|
---|
| 37 | the panel layout; refer to the doctext for set_panels().
|
---|
| 38 | """
|
---|
[705] | 39 | self.is_dead = False
|
---|
[1019] | 40 | self.figure = Figure(figsize=size, facecolor='#ddddee')
|
---|
[705] | 41 | self.canvas = None
|
---|
| 42 |
|
---|
[1019] | 43 | self.set_title(title)
|
---|
| 44 | self.subplots = []
|
---|
| 45 | if rows > 0:
|
---|
| 46 | self.set_panels(rows, cols)
|
---|
[705] | 47 |
|
---|
[710] | 48 | # Set matplotlib default colour sequence.
|
---|
| 49 | self.colormap = "green red black cyan magenta orange blue purple yellow pink".split()
|
---|
[1019] | 50 |
|
---|
[710] | 51 | c = asaprcParams['plotter.colours']
|
---|
| 52 | if isinstance(c,str) and len(c) > 0:
|
---|
| 53 | self.colormap = c.split()
|
---|
| 54 |
|
---|
| 55 | self.lsalias = {"line": [1,0],
|
---|
| 56 | "dashdot": [4,2,1,2],
|
---|
| 57 | "dashed" : [4,2,4,2],
|
---|
| 58 | "dotted" : [1,2],
|
---|
| 59 | "dashdotdot": [4,2,1,2,1,2],
|
---|
| 60 | "dashdashdot": [4,2,4,2,1,2]
|
---|
| 61 | }
|
---|
| 62 |
|
---|
| 63 | styles = "line dashed dotted dashdot".split()
|
---|
| 64 | c = asaprcParams['plotter.linestyles']
|
---|
| 65 | if isinstance(c,str) and len(c) > 0:
|
---|
| 66 | styles = c.split()
|
---|
| 67 | s = []
|
---|
| 68 | for ls in styles:
|
---|
| 69 | if self.lsalias.has_key(ls):
|
---|
| 70 | s.append(self.lsalias.get(ls))
|
---|
| 71 | else:
|
---|
| 72 | s.append('-')
|
---|
| 73 | self.linestyles = s
|
---|
| 74 |
|
---|
[705] | 75 | self.color = 0;
|
---|
[710] | 76 | self.linestyle = 0;
|
---|
[1019] | 77 | self.attributes = {}
|
---|
| 78 | self.loc = 0
|
---|
[705] | 79 |
|
---|
[1019] | 80 | self.buffering = buffering
|
---|
[705] | 81 |
|
---|
| 82 | def clear(self):
|
---|
[1019] | 83 | """
|
---|
| 84 | Delete all lines from the plot. Line numbering will restart from 1.
|
---|
| 85 | """
|
---|
[705] | 86 |
|
---|
[1019] | 87 | for i in range(len(self.lines)):
|
---|
| 88 | self.delete(i)
|
---|
| 89 | self.axes.clear()
|
---|
| 90 | self.color = 0
|
---|
| 91 | self.lines = []
|
---|
[705] | 92 |
|
---|
[710] | 93 | def palette(self, color, colormap=None, linestyle=0, linestyles=None):
|
---|
[705] | 94 | if colormap:
|
---|
[710] | 95 | if isinstance(colormap,list):
|
---|
| 96 | self.colormap = colormap
|
---|
| 97 | elif isinstance(colormap,str):
|
---|
| 98 | self.colormap = colormap.split()
|
---|
[705] | 99 | if 0 <= color < len(self.colormap):
|
---|
| 100 | self.color = color
|
---|
[710] | 101 | if linestyles:
|
---|
| 102 | self.linestyles = []
|
---|
| 103 | if isinstance(linestyles,list):
|
---|
| 104 | styles = linestyles
|
---|
| 105 | elif isinstance(linestyles,str):
|
---|
| 106 | styles = linestyles.split()
|
---|
| 107 | for ls in styles:
|
---|
| 108 | if self.lsalias.has_key(ls):
|
---|
| 109 | self.linestyles.append(self.lsalias.get(ls))
|
---|
| 110 | else:
|
---|
| 111 | self.linestyles.append(self.lsalias.get('line'))
|
---|
| 112 | if 0 <= linestyle < len(self.linestyles):
|
---|
| 113 | self.linestyle = linestyle
|
---|
[705] | 114 |
|
---|
| 115 | def delete(self, numbers=None):
|
---|
[1019] | 116 | """
|
---|
| 117 | Delete the 0-relative line number, default is to delete the last.
|
---|
| 118 | The remaining lines are NOT renumbered.
|
---|
| 119 | """
|
---|
[705] | 120 |
|
---|
[1019] | 121 | if numbers is None: numbers = [len(self.lines)-1]
|
---|
[705] | 122 |
|
---|
[1019] | 123 | if not hasattr(numbers, '__iter__'):
|
---|
| 124 | numbers = [numbers]
|
---|
[705] | 125 |
|
---|
[1019] | 126 | for number in numbers:
|
---|
| 127 | if 0 <= number < len(self.lines):
|
---|
| 128 | if self.lines[number] is not None:
|
---|
| 129 | for line in self.lines[number]:
|
---|
| 130 | line.set_linestyle('None')
|
---|
| 131 | self.lines[number] = None
|
---|
| 132 | self.show()
|
---|
[705] | 133 |
|
---|
| 134 | def get_line(self):
|
---|
[1019] | 135 | """
|
---|
| 136 | Get the current default line attributes.
|
---|
| 137 | """
|
---|
| 138 | return self.attributes
|
---|
[705] | 139 |
|
---|
| 140 |
|
---|
| 141 | def hist(self, x=None, y=None, fmt=None):
|
---|
[1019] | 142 | """
|
---|
| 143 | Plot a histogram. N.B. the x values refer to the start of the
|
---|
| 144 | histogram bin.
|
---|
[705] | 145 |
|
---|
[1019] | 146 | fmt is the line style as in plot().
|
---|
| 147 | """
|
---|
[705] | 148 |
|
---|
[1019] | 149 | if x is None:
|
---|
| 150 | if y is None: return
|
---|
| 151 | x = range(0,len(y))
|
---|
[705] | 152 |
|
---|
[1019] | 153 | if len(x) != len(y):
|
---|
| 154 | return
|
---|
[705] | 155 |
|
---|
[1019] | 156 | l2 = 2*len(x)
|
---|
| 157 | x2 = range(0,l2)
|
---|
| 158 | y2 = range(0,l2)
|
---|
[705] | 159 |
|
---|
[1019] | 160 | for i in range(0,l2):
|
---|
| 161 | x2[i] = x[i/2]
|
---|
[705] | 162 |
|
---|
[1019] | 163 | y2[0] = 0
|
---|
| 164 | for i in range(1,l2):
|
---|
| 165 | y2[i] = y[(i-1)/2]
|
---|
[705] | 166 |
|
---|
[1019] | 167 | self.plot(x2, y2, fmt)
|
---|
[705] | 168 |
|
---|
| 169 |
|
---|
| 170 | def hold(self, hold=True):
|
---|
[1019] | 171 | """
|
---|
| 172 | Buffer graphics until subsequently released.
|
---|
| 173 | """
|
---|
| 174 | self.buffering = hold
|
---|
[705] | 175 |
|
---|
| 176 |
|
---|
| 177 | def legend(self, loc=None):
|
---|
[1019] | 178 | """
|
---|
| 179 | Add a legend to the plot.
|
---|
[705] | 180 |
|
---|
[1019] | 181 | Any other value for loc else disables the legend:
|
---|
| 182 | 1: upper right
|
---|
| 183 | 2: upper left
|
---|
| 184 | 3: lower left
|
---|
| 185 | 4: lower right
|
---|
| 186 | 5: right
|
---|
| 187 | 6: center left
|
---|
| 188 | 7: center right
|
---|
| 189 | 8: lower center
|
---|
| 190 | 9: upper center
|
---|
| 191 | 10: center
|
---|
[705] | 192 |
|
---|
[1019] | 193 | """
|
---|
[705] | 194 | if isinstance(loc,int):
|
---|
| 195 | if 0 > loc > 10: loc = 0
|
---|
| 196 | self.loc = loc
|
---|
[1019] | 197 | self.show()
|
---|
[705] | 198 |
|
---|
| 199 |
|
---|
| 200 | def plot(self, x=None, y=None, mask=None, fmt=None, add=None):
|
---|
[1019] | 201 | """
|
---|
| 202 | Plot the next line in the current frame using the current line
|
---|
| 203 | attributes. The ASAPlot graphics window will be mapped and raised.
|
---|
[705] | 204 |
|
---|
[1019] | 205 | The argument list works a bit like the matlab plot() function.
|
---|
| 206 | """
|
---|
[705] | 207 |
|
---|
[1019] | 208 | if x is None:
|
---|
| 209 | if y is None: return
|
---|
| 210 | x = range(len(y))
|
---|
[705] | 211 |
|
---|
[1019] | 212 | elif y is None:
|
---|
| 213 | y = x
|
---|
| 214 | x = range(len(y))
|
---|
[705] | 215 |
|
---|
[1019] | 216 | if mask is None:
|
---|
| 217 | if fmt is None:
|
---|
| 218 | line = self.axes.plot(x, y)
|
---|
| 219 | else:
|
---|
| 220 | line = self.axes.plot(x, y, fmt)
|
---|
| 221 | else:
|
---|
| 222 | segments = []
|
---|
[705] | 223 |
|
---|
[1019] | 224 | mask = list(mask)
|
---|
| 225 | i = 0
|
---|
| 226 | while mask[i:].count(1):
|
---|
| 227 | i += mask[i:].index(1)
|
---|
| 228 | if mask[i:].count(0):
|
---|
| 229 | j = i + mask[i:].index(0)
|
---|
| 230 | else:
|
---|
| 231 | j = len(mask)
|
---|
[705] | 232 |
|
---|
[1019] | 233 | segments.append(x[i:j])
|
---|
| 234 | segments.append(y[i:j])
|
---|
[705] | 235 |
|
---|
[1019] | 236 | i = j
|
---|
[705] | 237 |
|
---|
[1019] | 238 | line = self.axes.plot(*segments)
|
---|
| 239 | # Add to an existing line?
|
---|
| 240 | if add is None or len(self.lines) < add < 0:
|
---|
| 241 | # Don't add.
|
---|
| 242 | self.lines.append(line)
|
---|
| 243 | i = len(self.lines) - 1
|
---|
| 244 | else:
|
---|
| 245 | if add == 0: add = len(self.lines)
|
---|
| 246 | i = add - 1
|
---|
| 247 | self.lines[i].extend(line)
|
---|
[705] | 248 |
|
---|
[1019] | 249 | # Set/reset attributes for the line.
|
---|
| 250 | gotcolour = False
|
---|
| 251 | for k, v in self.attributes.iteritems():
|
---|
| 252 | if k == 'color': gotcolour = True
|
---|
| 253 | for segment in self.lines[i]:
|
---|
| 254 | getattr(segment, "set_%s"%k)(v)
|
---|
[705] | 255 |
|
---|
[1019] | 256 | if not gotcolour and len(self.colormap):
|
---|
| 257 | for segment in self.lines[i]:
|
---|
| 258 | getattr(segment, "set_color")(self.colormap[self.color])
|
---|
[710] | 259 | if len(self.colormap) == 1:
|
---|
| 260 | getattr(segment, "set_dashes")(self.linestyles[self.linestyle])
|
---|
[1019] | 261 | self.color += 1
|
---|
| 262 | if self.color >= len(self.colormap):
|
---|
| 263 | self.color = 0
|
---|
[705] | 264 |
|
---|
[710] | 265 | if len(self.colormap) == 1:
|
---|
| 266 | self.linestyle += 1
|
---|
[1019] | 267 | if self.linestyle >= len(self.linestyles):
|
---|
| 268 | self.linestyle = 0
|
---|
[710] | 269 |
|
---|
[1019] | 270 | self.show()
|
---|
[705] | 271 |
|
---|
| 272 |
|
---|
| 273 | def position(self):
|
---|
[1019] | 274 | """
|
---|
| 275 | Use the mouse to get a position from a graph.
|
---|
| 276 | """
|
---|
[705] | 277 |
|
---|
[1019] | 278 | def position_disable(event):
|
---|
| 279 | self.register('button_press', None)
|
---|
| 280 | print '%.4f, %.4f' % (event.xdata, event.ydata)
|
---|
[705] | 281 |
|
---|
[1019] | 282 | print 'Press any mouse button...'
|
---|
| 283 | self.register('button_press', position_disable)
|
---|
[705] | 284 |
|
---|
| 285 |
|
---|
| 286 | def region(self):
|
---|
[1019] | 287 | """
|
---|
| 288 | Use the mouse to get a rectangular region from a plot.
|
---|
[705] | 289 |
|
---|
[1019] | 290 | The return value is [x0, y0, x1, y1] in world coordinates.
|
---|
| 291 | """
|
---|
[705] | 292 |
|
---|
[1019] | 293 | def region_start(event):
|
---|
| 294 | height = self.canvas.figure.bbox.height()
|
---|
| 295 | self.rect = {'fig': None, 'height': height,
|
---|
| 296 | 'x': event.x, 'y': height - event.y,
|
---|
| 297 | 'world': [event.xdata, event.ydata,
|
---|
| 298 | event.xdata, event.ydata]}
|
---|
| 299 | self.register('button_press', None)
|
---|
| 300 | self.register('motion_notify', region_draw)
|
---|
| 301 | self.register('button_release', region_disable)
|
---|
[705] | 302 |
|
---|
[1019] | 303 | def region_draw(event):
|
---|
| 304 | self.canvas._tkcanvas.delete(self.rect['fig'])
|
---|
| 305 | self.rect['fig'] = self.canvas._tkcanvas.create_rectangle(
|
---|
| 306 | self.rect['x'], self.rect['y'],
|
---|
| 307 | event.x, self.rect['height'] - event.y)
|
---|
[705] | 308 |
|
---|
[1019] | 309 | def region_disable(event):
|
---|
| 310 | self.register('motion_notify', None)
|
---|
| 311 | self.register('button_release', None)
|
---|
[705] | 312 |
|
---|
[1019] | 313 | self.canvas._tkcanvas.delete(self.rect['fig'])
|
---|
[705] | 314 |
|
---|
[1019] | 315 | self.rect['world'][2:4] = [event.xdata, event.ydata]
|
---|
| 316 | print '(%.2f, %.2f) (%.2f, %.2f)' % (self.rect['world'][0],
|
---|
| 317 | self.rect['world'][1], self.rect['world'][2],
|
---|
| 318 | self.rect['world'][3])
|
---|
[705] | 319 |
|
---|
[1019] | 320 | self.register('button_press', region_start)
|
---|
[705] | 321 |
|
---|
[1019] | 322 | # This has to be modified to block and return the result (currently
|
---|
| 323 | # printed by region_disable) when that becomes possible in matplotlib.
|
---|
[705] | 324 |
|
---|
[1019] | 325 | return [0.0, 0.0, 0.0, 0.0]
|
---|
[705] | 326 |
|
---|
| 327 |
|
---|
| 328 | def register(self, type=None, func=None):
|
---|
[1019] | 329 | """
|
---|
| 330 | Register, reregister, or deregister events of type 'button_press',
|
---|
| 331 | 'button_release', or 'motion_notify'.
|
---|
[705] | 332 |
|
---|
[1019] | 333 | The specified callback function should have the following signature:
|
---|
[705] | 334 |
|
---|
[1019] | 335 | def func(event)
|
---|
[705] | 336 |
|
---|
[1019] | 337 | where event is an MplEvent instance containing the following data:
|
---|
[705] | 338 |
|
---|
[1019] | 339 | name # Event name.
|
---|
| 340 | canvas # FigureCanvas instance generating the event.
|
---|
| 341 | x = None # x position - pixels from left of canvas.
|
---|
| 342 | y = None # y position - pixels from bottom of canvas.
|
---|
| 343 | button = None # Button pressed: None, 1, 2, 3.
|
---|
| 344 | key = None # Key pressed: None, chr(range(255)), shift,
|
---|
| 345 | win, or control
|
---|
| 346 | inaxes = None # Axes instance if cursor within axes.
|
---|
| 347 | xdata = None # x world coordinate.
|
---|
| 348 | ydata = None # y world coordinate.
|
---|
[705] | 349 |
|
---|
[1019] | 350 | For example:
|
---|
[705] | 351 |
|
---|
[1019] | 352 | def mouse_move(event):
|
---|
| 353 | print event.xdata, event.ydata
|
---|
[705] | 354 |
|
---|
[1019] | 355 | a = asaplot()
|
---|
| 356 | a.register('motion_notify', mouse_move)
|
---|
[705] | 357 |
|
---|
[1019] | 358 | If func is None, the event is deregistered.
|
---|
[705] | 359 |
|
---|
[1019] | 360 | Note that in TkAgg keyboard button presses don't generate an event.
|
---|
| 361 | """
|
---|
[705] | 362 |
|
---|
[1019] | 363 | if not self.events.has_key(type): return
|
---|
[705] | 364 |
|
---|
[1019] | 365 | if func is None:
|
---|
| 366 | if self.events[type] is not None:
|
---|
| 367 | # It's not clear that this does anything.
|
---|
| 368 | self.canvas.mpl_disconnect(self.events[type])
|
---|
| 369 | self.events[type] = None
|
---|
[705] | 370 |
|
---|
[1019] | 371 | # It seems to be necessary to return events to the toolbar.
|
---|
| 372 | if type == 'motion_notify':
|
---|
| 373 | self.canvas.mpl_connect(type + '_event',
|
---|
| 374 | self.figmgr.toolbar.mouse_move)
|
---|
| 375 | elif type == 'button_press':
|
---|
| 376 | self.canvas.mpl_connect(type + '_event',
|
---|
| 377 | self.figmgr.toolbar.press)
|
---|
| 378 | elif type == 'button_release':
|
---|
| 379 | self.canvas.mpl_connect(type + '_event',
|
---|
| 380 | self.figmgr.toolbar.release)
|
---|
[705] | 381 |
|
---|
[1019] | 382 | else:
|
---|
| 383 | self.events[type] = self.canvas.mpl_connect(type + '_event', func)
|
---|
[705] | 384 |
|
---|
| 385 |
|
---|
| 386 | def release(self):
|
---|
[1019] | 387 | """
|
---|
| 388 | Release buffered graphics.
|
---|
| 389 | """
|
---|
| 390 | self.buffering = False
|
---|
| 391 | self.show()
|
---|
[705] | 392 |
|
---|
| 393 |
|
---|
| 394 | def save(self, fname=None, orientation=None, dpi=None):
|
---|
[1019] | 395 | """
|
---|
| 396 | Save the plot to a file.
|
---|
[705] | 397 |
|
---|
[1019] | 398 | fname is the name of the output file. The image format is determined
|
---|
| 399 | from the file suffix; 'png', 'ps', and 'eps' are recognized. If no
|
---|
| 400 | file name is specified 'yyyymmdd_hhmmss.png' is created in the current
|
---|
| 401 | directory.
|
---|
| 402 | """
|
---|
| 403 | if fname is None:
|
---|
| 404 | from datetime import datetime
|
---|
| 405 | dstr = datetime.now().strftime('%Y%m%d_%H%M%S')
|
---|
| 406 | fname = 'asap'+dstr+'.png'
|
---|
[705] | 407 |
|
---|
[1019] | 408 | d = ['png','.ps','eps']
|
---|
[705] | 409 |
|
---|
[1019] | 410 | from os.path import expandvars
|
---|
| 411 | fname = expandvars(fname)
|
---|
[705] | 412 |
|
---|
[1019] | 413 | if fname[-3:].lower() in d:
|
---|
| 414 | try:
|
---|
[705] | 415 | if fname[-3:].lower() == ".ps":
|
---|
[1020] | 416 | from matplotlib import __version__ as mv
|
---|
[705] | 417 | w = self.figure.figwidth.get()
|
---|
[1019] | 418 | h = self.figure.figheight.get()
|
---|
| 419 |
|
---|
[705] | 420 | if orientation is None:
|
---|
| 421 | # auto oriented
|
---|
| 422 | if w > h:
|
---|
| 423 | orientation = 'landscape'
|
---|
| 424 | else:
|
---|
| 425 | orientation = 'portrait'
|
---|
[1020] | 426 | # hack to circument ps bug in eraly versions of mpl
|
---|
| 427 | if int(mv.split(".")[1]) < 86:
|
---|
| 428 | a4w = 8.25
|
---|
| 429 | a4h = 11.25
|
---|
| 430 | ds = None
|
---|
| 431 | if orientation == 'landscape':
|
---|
| 432 | ds = min(a4h/w,a4w/h)
|
---|
| 433 | else:
|
---|
| 434 | ds = min(a4w/w,a4h/h)
|
---|
| 435 | ow = ds * w
|
---|
| 436 | oh = ds * h
|
---|
| 437 | self.figure.set_figsize_inches((ow,oh))
|
---|
[705] | 438 | self.canvas.print_figure(fname,orientation=orientation)
|
---|
| 439 | print 'Written file %s' % (fname)
|
---|
[1019] | 440 | else:
|
---|
[705] | 441 | if dpi is None:
|
---|
| 442 | dpi =150
|
---|
| 443 | self.canvas.print_figure(fname,dpi=dpi)
|
---|
| 444 | print 'Written file %s' % (fname)
|
---|
[1019] | 445 | except IOError, msg:
|
---|
| 446 | print 'Failed to save %s: Error msg was\n\n%s' % (fname, err)
|
---|
| 447 | return
|
---|
| 448 | else:
|
---|
| 449 | print "Invalid image type. Valid types are:"
|
---|
| 450 | print "'ps', 'eps', 'png'"
|
---|
[705] | 451 |
|
---|
| 452 |
|
---|
| 453 | def set_axes(self, what=None, *args, **kwargs):
|
---|
[1019] | 454 | """
|
---|
| 455 | Set attributes for the axes by calling the relevant Axes.set_*()
|
---|
| 456 | method. Colour translation is done as described in the doctext
|
---|
| 457 | for palette().
|
---|
| 458 | """
|
---|
[705] | 459 |
|
---|
[1019] | 460 | if what is None: return
|
---|
| 461 | if what[-6:] == 'colour': what = what[:-6] + 'color'
|
---|
[705] | 462 |
|
---|
[1019] | 463 | newargs = {}
|
---|
[705] | 464 |
|
---|
[1019] | 465 | for k, v in kwargs.iteritems():
|
---|
| 466 | k = k.lower()
|
---|
| 467 | if k == 'colour': k = 'color'
|
---|
| 468 | newargs[k] = v
|
---|
[705] | 469 |
|
---|
[1019] | 470 | getattr(self.axes, "set_%s"%what)(*args, **newargs)
|
---|
| 471 | s = self.axes.title.get_size()
|
---|
| 472 | tsize = s-(self.cols+self.rows)/2-1
|
---|
| 473 | self.axes.title.set_size(tsize)
|
---|
| 474 | if self.cols > 1:
|
---|
| 475 | xfsize = self.axes.xaxis.label.get_size()-(self.cols+1)/2
|
---|
| 476 | self.axes.xaxis.label.set_size(xfsize)
|
---|
| 477 | if self.rows > 1:
|
---|
| 478 | yfsize = self.axes.yaxis.label.get_size()-(self.rows+1)/2
|
---|
| 479 | self.axes.yaxis.label.set_size(yfsize)
|
---|
[705] | 480 |
|
---|
[1019] | 481 | self.show()
|
---|
| 482 |
|
---|
| 483 |
|
---|
[705] | 484 | def set_figure(self, what=None, *args, **kwargs):
|
---|
[1019] | 485 | """
|
---|
| 486 | Set attributes for the figure by calling the relevant Figure.set_*()
|
---|
| 487 | method. Colour translation is done as described in the doctext
|
---|
| 488 | for palette().
|
---|
| 489 | """
|
---|
[705] | 490 |
|
---|
[1019] | 491 | if what is None: return
|
---|
| 492 | if what[-6:] == 'colour': what = what[:-6] + 'color'
|
---|
| 493 | #if what[-5:] == 'color' and len(args):
|
---|
| 494 | # args = (get_colour(args[0]),)
|
---|
[705] | 495 |
|
---|
[1019] | 496 | newargs = {}
|
---|
| 497 | for k, v in kwargs.iteritems():
|
---|
| 498 | k = k.lower()
|
---|
| 499 | if k == 'colour': k = 'color'
|
---|
| 500 | newargs[k] = v
|
---|
[705] | 501 |
|
---|
[1019] | 502 | getattr(self.figure, "set_%s"%what)(*args, **newargs)
|
---|
| 503 | self.show()
|
---|
[705] | 504 |
|
---|
| 505 |
|
---|
| 506 | def set_limits(self, xlim=None, ylim=None):
|
---|
[1019] | 507 | """
|
---|
| 508 | Set x-, and y-limits for each subplot.
|
---|
[705] | 509 |
|
---|
[1019] | 510 | xlim = [xmin, xmax] as in axes.set_xlim().
|
---|
| 511 | ylim = [ymin, ymax] as in axes.set_ylim().
|
---|
| 512 | """
|
---|
| 513 | for s in self.subplots:
|
---|
| 514 | self.axes = s['axes']
|
---|
| 515 | self.lines = s['lines']
|
---|
[705] | 516 | oldxlim = list(self.axes.get_xlim())
|
---|
| 517 | oldylim = list(self.axes.get_ylim())
|
---|
| 518 | if xlim is not None:
|
---|
| 519 | for i in range(len(xlim)):
|
---|
| 520 | if xlim[i] is not None:
|
---|
| 521 | oldxlim[i] = xlim[i]
|
---|
[1019] | 522 | if ylim is not None:
|
---|
[705] | 523 | for i in range(len(ylim)):
|
---|
| 524 | if ylim[i] is not None:
|
---|
| 525 | oldylim[i] = ylim[i]
|
---|
| 526 | self.axes.set_xlim(oldxlim)
|
---|
| 527 | self.axes.set_ylim(oldylim)
|
---|
| 528 | return
|
---|
| 529 |
|
---|
| 530 |
|
---|
| 531 | def set_line(self, number=None, **kwargs):
|
---|
[1019] | 532 | """
|
---|
| 533 | Set attributes for the specified line, or else the next line(s)
|
---|
| 534 | to be plotted.
|
---|
[705] | 535 |
|
---|
[1019] | 536 | number is the 0-relative number of a line that has already been
|
---|
| 537 | plotted. If no such line exists, attributes are recorded and used
|
---|
| 538 | for the next line(s) to be plotted.
|
---|
[705] | 539 |
|
---|
[1019] | 540 | Keyword arguments specify Line2D attributes, e.g. color='r'. Do
|
---|
[705] | 541 |
|
---|
[1019] | 542 | import matplotlib
|
---|
| 543 | help(matplotlib.lines)
|
---|
[705] | 544 |
|
---|
[1019] | 545 | The set_* methods of class Line2D define the attribute names and
|
---|
| 546 | values. For non-US usage, "colour" is recognized as synonymous with
|
---|
| 547 | "color".
|
---|
[705] | 548 |
|
---|
[1019] | 549 | Set the value to None to delete an attribute.
|
---|
[705] | 550 |
|
---|
[1019] | 551 | Colour translation is done as described in the doctext for palette().
|
---|
| 552 | """
|
---|
[705] | 553 |
|
---|
[1019] | 554 | redraw = False
|
---|
| 555 | for k, v in kwargs.iteritems():
|
---|
| 556 | k = k.lower()
|
---|
| 557 | if k == 'colour': k = 'color'
|
---|
[705] | 558 |
|
---|
[1019] | 559 | if 0 <= number < len(self.lines):
|
---|
| 560 | if self.lines[number] is not None:
|
---|
| 561 | for line in self.lines[number]:
|
---|
| 562 | getattr(line, "set_%s"%k)(v)
|
---|
| 563 | redraw = True
|
---|
| 564 | else:
|
---|
| 565 | if v is None:
|
---|
| 566 | del self.attributes[k]
|
---|
| 567 | else:
|
---|
| 568 | self.attributes[k] = v
|
---|
[705] | 569 |
|
---|
[1019] | 570 | if redraw: self.show()
|
---|
[705] | 571 |
|
---|
| 572 |
|
---|
| 573 | def set_panels(self, rows=1, cols=0, n=-1, nplots=-1, ganged=True):
|
---|
[1019] | 574 | """
|
---|
| 575 | Set the panel layout.
|
---|
[705] | 576 |
|
---|
[1019] | 577 | rows and cols, if cols != 0, specify the number of rows and columns in
|
---|
| 578 | a regular layout. (Indexing of these panels in matplotlib is row-
|
---|
| 579 | major, i.e. column varies fastest.)
|
---|
[705] | 580 |
|
---|
[1019] | 581 | cols == 0 is interpreted as a retangular layout that accomodates
|
---|
| 582 | 'rows' panels, e.g. rows == 6, cols == 0 is equivalent to
|
---|
| 583 | rows == 2, cols == 3.
|
---|
[705] | 584 |
|
---|
[1019] | 585 | 0 <= n < rows*cols is interpreted as the 0-relative panel number in
|
---|
| 586 | the configuration specified by rows and cols to be added to the
|
---|
| 587 | current figure as its next 0-relative panel number (i). This allows
|
---|
| 588 | non-regular panel layouts to be constructed via multiple calls. Any
|
---|
| 589 | other value of n clears the plot and produces a rectangular array of
|
---|
| 590 | empty panels. The number of these may be limited by nplots.
|
---|
| 591 | """
|
---|
| 592 | if n < 0 and len(self.subplots):
|
---|
| 593 | self.figure.clear()
|
---|
| 594 | self.set_title()
|
---|
[705] | 595 |
|
---|
[1019] | 596 | if rows < 1: rows = 1
|
---|
[705] | 597 |
|
---|
[1019] | 598 | if cols <= 0:
|
---|
| 599 | i = int(sqrt(rows))
|
---|
| 600 | if i*i < rows: i += 1
|
---|
| 601 | cols = i
|
---|
[705] | 602 |
|
---|
[1019] | 603 | if i*(i-1) >= rows: i -= 1
|
---|
| 604 | rows = i
|
---|
[705] | 605 |
|
---|
[1019] | 606 | if 0 <= n < rows*cols:
|
---|
| 607 | i = len(self.subplots)
|
---|
| 608 | self.subplots.append({})
|
---|
[705] | 609 |
|
---|
[1019] | 610 | self.subplots[i]['axes'] = self.figure.add_subplot(rows,
|
---|
| 611 | cols, n+1)
|
---|
| 612 | self.subplots[i]['lines'] = []
|
---|
[705] | 613 |
|
---|
[1019] | 614 | if i == 0: self.subplot(0)
|
---|
[705] | 615 |
|
---|
[1019] | 616 | self.rows = 0
|
---|
| 617 | self.cols = 0
|
---|
[705] | 618 |
|
---|
[1019] | 619 | else:
|
---|
| 620 | self.subplots = []
|
---|
[705] | 621 |
|
---|
[1019] | 622 | if nplots < 1 or rows*cols < nplots:
|
---|
| 623 | nplots = rows*cols
|
---|
[705] | 624 |
|
---|
[1019] | 625 | for i in range(nplots):
|
---|
| 626 | self.subplots.append({})
|
---|
[705] | 627 |
|
---|
[1019] | 628 | self.subplots[i]['axes'] = self.figure.add_subplot(rows,
|
---|
| 629 | cols, i+1)
|
---|
| 630 | self.subplots[i]['lines'] = []
|
---|
| 631 |
|
---|
[705] | 632 | if ganged:
|
---|
| 633 | if rows > 1 or cols > 1:
|
---|
| 634 | # Squeeze the plots together.
|
---|
| 635 | pos = self.subplots[i]['axes'].get_position()
|
---|
| 636 | if cols > 1: pos[2] *= 1.2
|
---|
| 637 | if rows > 1: pos[3] *= 1.2
|
---|
| 638 | self.subplots[i]['axes'].set_position(pos)
|
---|
| 639 |
|
---|
| 640 | # Suppress tick labelling for interior subplots.
|
---|
| 641 | if i <= (rows-1)*cols - 1:
|
---|
| 642 | if i+cols < nplots:
|
---|
| 643 | # Suppress x-labels for frames width
|
---|
| 644 | # adjacent frames
|
---|
[1019] | 645 | self.subplots[i]['axes'].xaxis.set_major_locator(NullLocator())
|
---|
| 646 | self.subplots[i]['axes'].xaxis.label.set_visible(False)
|
---|
[705] | 647 | if i%cols:
|
---|
| 648 | # Suppress y-labels for frames not in the left column.
|
---|
| 649 | for tick in self.subplots[i]['axes'].yaxis.majorTicks:
|
---|
| 650 | tick.label1On = False
|
---|
| 651 | self.subplots[i]['axes'].yaxis.label.set_visible(False)
|
---|
[1019] | 652 | if (i+1)%cols:
|
---|
| 653 | self.subplots[i]['axes'].xaxis.set_major_formatter(MyFormatter())
|
---|
| 654 | self.rows = rows
|
---|
| 655 | self.cols = cols
|
---|
[705] | 656 |
|
---|
[1019] | 657 | self.subplot(0)
|
---|
[705] | 658 |
|
---|
| 659 | def set_title(self, title=None):
|
---|
[1019] | 660 | """
|
---|
| 661 | Set the title of the plot window. Use the previous title if title is
|
---|
| 662 | omitted.
|
---|
| 663 | """
|
---|
| 664 | if title is not None:
|
---|
| 665 | self.title = title
|
---|
[705] | 666 |
|
---|
[1019] | 667 | self.figure.text(0.5, 0.95, self.title, horizontalalignment='center')
|
---|
[705] | 668 |
|
---|
| 669 |
|
---|
| 670 | def show(self):
|
---|
[1019] | 671 | """
|
---|
| 672 | Show graphics dependent on the current buffering state.
|
---|
| 673 | """
|
---|
| 674 | if not self.buffering:
|
---|
| 675 | if self.loc is not None:
|
---|
| 676 | for j in range(len(self.subplots)):
|
---|
| 677 | lines = []
|
---|
| 678 | labels = []
|
---|
| 679 | i = 0
|
---|
| 680 | for line in self.subplots[j]['lines']:
|
---|
| 681 | i += 1
|
---|
| 682 | if line is not None:
|
---|
| 683 | lines.append(line[0])
|
---|
| 684 | lbl = line[0].get_label()
|
---|
| 685 | if lbl == '':
|
---|
| 686 | lbl = str(i)
|
---|
| 687 | labels.append(lbl)
|
---|
[705] | 688 |
|
---|
[1019] | 689 | if len(lines):
|
---|
| 690 | self.subplots[j]['axes'].legend(tuple(lines),
|
---|
| 691 | tuple(labels),
|
---|
| 692 | self.loc)
|
---|
| 693 | else:
|
---|
| 694 | self.subplots[j]['axes'].legend((' '))
|
---|
[705] | 695 |
|
---|
| 696 |
|
---|
| 697 | def subplot(self, i=None, inc=None):
|
---|
[1019] | 698 | """
|
---|
| 699 | Set the subplot to the 0-relative panel number as defined by one or
|
---|
| 700 | more invokations of set_panels().
|
---|
| 701 | """
|
---|
| 702 | l = len(self.subplots)
|
---|
| 703 | if l:
|
---|
| 704 | if i is not None:
|
---|
| 705 | self.i = i
|
---|
[705] | 706 |
|
---|
[1019] | 707 | if inc is not None:
|
---|
| 708 | self.i += inc
|
---|
[705] | 709 |
|
---|
[1019] | 710 | self.i %= l
|
---|
| 711 | self.axes = self.subplots[self.i]['axes']
|
---|
| 712 | self.lines = self.subplots[self.i]['lines']
|
---|
[705] | 713 |
|
---|
| 714 |
|
---|
| 715 | def text(self, *args, **kwargs):
|
---|
[1019] | 716 | """
|
---|
| 717 | Add text to the figure.
|
---|
| 718 | """
|
---|
| 719 | self.figure.text(*args, **kwargs)
|
---|
| 720 | self.show()
|
---|