desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return true if the object should try to do antialiased rendering'
def get_antialiased(self):
return self._antialiased
'Return the capstyle as a string in (\'butt\', \'round\', \'projecting\')'
def get_capstyle(self):
return self._capstyle
'Return the clip rectangle as a :class:`~matplotlib.transforms.Bbox` instance'
def get_clip_rectangle(self):
return self._cliprect
'Return the clip path in the form (path, transform), where path is a :class:`~matplotlib.path.Path` instance, and transform is an affine transform to apply to the path before clipping.'
def get_clip_path(self):
if (self._clippath is not None): return self._clippath.get_transformed_path_and_affine() return (None, None)
'Return the dash information as an offset dashlist tuple. The dash list is a even size list that gives the ink on, ink off in pixels. See p107 of to PostScript `BLUEBOOK <http://www-cdf.fnal.gov/offline/PostScript/BLUEBOOK.PDF>`_ for more info. Default value is None'
def get_dashes(self):
return self._dashes
'Return the line join style as one of (\'miter\', \'round\', \'bevel\')'
def get_joinstyle(self):
return self._joinstyle
'Return the linestyle: one of (\'solid\', \'dashed\', \'dashdot\', \'dotted\').'
def get_linestyle(self, style):
return self._linestyle
'Return the line width in points as a scalar'
def get_linewidth(self):
return self._linewidth
'returns a tuple of three floats from 0-1. color can be a matlab format string, a html hex color string, or a rgb tuple'
def get_rgb(self):
return self._rgb
'returns a url if one is set, None otherwise'
def get_url(self):
return self._url
'returns the snap setting which may be: * True: snap vertices to the nearest pixel center * False: leave vertices as-is * None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center'
def get_snap(self):
return self._snap
'Set the alpha value used for blending - not supported on all backends'
def set_alpha(self, alpha):
self._alpha = alpha
'True if object should be drawn with antialiased rendering'
def set_antialiased(self, b):
if b: self._antialiased = 1 else: self._antialiased = 0
'Set the capstyle as a string in (\'butt\', \'round\', \'projecting\')'
def set_capstyle(self, cs):
if (cs in ('butt', 'round', 'projecting')): self._capstyle = cs else: raise ValueError(('Unrecognized cap style. Found %s' % cs))
'Set the clip rectangle with sequence (left, bottom, width, height)'
def set_clip_rectangle(self, rectangle):
self._cliprect = rectangle
'Set the clip path and transformation. Path should be a :class:`~matplotlib.transforms.TransformedPath` instance.'
def set_clip_path(self, path):
assert ((path is None) or isinstance(path, transforms.TransformedPath)) self._clippath = path
'Set the dash style for the gc. *dash_offset* is the offset (usually 0). *dash_list* specifies the on-off sequence as points. ``(None, None)`` specifies a solid line'
def set_dashes(self, dash_offset, dash_list):
self._dashes = (dash_offset, dash_list)
'Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. The :class:`GraphicsContextBase` converts colors to rgb internally. If you know the color is rgb already, you can set ``isRGB=True`` to avoid the performace hit of the conversion'
def set_foreground(self, fg, isRGB=False):
if isRGB: self._rgb = fg else: self._rgb = colors.colorConverter.to_rgba(fg)
'Set the foreground color to be a gray level with *frac*'
def set_graylevel(self, frac):
self._rgb = (frac, frac, frac)
'Set the join style to be one of (\'miter\', \'round\', \'bevel\')'
def set_joinstyle(self, js):
if (js in ('miter', 'round', 'bevel')): self._joinstyle = js else: raise ValueError(('Unrecognized join style. Found %s' % js))
'Set the linewidth in points'
def set_linewidth(self, w):
self._linewidth = w
'Set the linestyle to be one of (\'solid\', \'dashed\', \'dashdot\', \'dotted\').'
def set_linestyle(self, style):
try: (offset, dashes) = self.dashd[style] except: raise ValueError(('Unrecognized linestyle: %s' % style)) self._linestyle = style self.set_dashes(offset, dashes)
'Sets the url for links in compatible backends'
def set_url(self, url):
self._url = url
'Sets the snap setting which may be: * True: snap vertices to the nearest pixel center * False: leave vertices as-is * None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center'
def set_snap(self, snap):
self._snap = snap
'Sets the hatch style for filling'
def set_hatch(self, hatch):
self._hatch = hatch
'Gets the current hatch style'
def get_hatch(self):
return self._hatch
'*x*, *y* in figure coords, 0,0 = bottom, left'
def __init__(self, name, canvas, x, y, guiEvent=None):
Event.__init__(self, name, canvas, guiEvent=guiEvent) self.x = x self.y = y if ((x is None) or (y is None)): self.inaxes = None self._update_enter_leave() return axes_list = [a for a in self.canvas.figure.get_axes() if a.in_axes(self)] if (len(axes_list) == 0): self.inaxes = None self._update_enter_leave() return elif (len(axes_list) > 1): axCmp = (lambda _x, _y: cmp(_x.zorder, _y.zorder)) axes_list.sort(axCmp) self.inaxes = axes_list[(-1)] else: self.inaxes = axes_list[0] try: (xdata, ydata) = self.inaxes.transData.inverted().transform_point((x, y)) except ValueError: self.xdata = None self.ydata = None else: self.xdata = xdata self.ydata = ydata self._update_enter_leave()
'process the figure/axes enter leave events'
def _update_enter_leave(self):
if (LocationEvent.lastevent is not None): last = LocationEvent.lastevent if (last.inaxes != self.inaxes): if (last.inaxes is not None): last.canvas.callbacks.process('axes_leave_event', last) if (self.inaxes is not None): self.canvas.callbacks.process('axes_enter_event', self) elif (self.inaxes is not None): self.canvas.callbacks.process('axes_enter_event', self) LocationEvent.lastevent = self
'x, y in figure coords, 0,0 = bottom, left button pressed None, 1, 2, 3, \'up\', \'down\''
def __init__(self, name, canvas, x, y, button=None, key=None, step=0, guiEvent=None):
LocationEvent.__init__(self, name, canvas, x, y, guiEvent=guiEvent) self.button = button self.key = key self.step = step
'Mouse event processor which removes the top artist under the cursor. Connect this to the \'mouse_press_event\' using:: canvas.mpl_connect(\'mouse_press_event\',canvas.onRemove)'
def onRemove(self, ev):
def sort_artists(artists): L = [(h.zorder, h) for h in artists] L.sort() return [h for (zorder, h) in L] under = sort_artists(self.figure.hitlist(ev)) h = None if under: h = under[(-1)] while h: print 'Removing', h if h.remove(): self.draw_idle() break parent = None for p in under: if (h in p.get_children()): parent = p break h = parent
'Mouse event processor which highlights the artists under the cursor. Connect this to the \'motion_notify_event\' using:: canvas.mpl_connect(\'motion_notify_event\',canvas.onHilite)'
def onHilite(self, ev):
if (not hasattr(self, '_active')): self._active = dict() under = self.figure.hitlist(ev) enter = [a for a in under if (a not in self._active)] leave = [a for a in self._active if (a not in under)] print 'within:', ' '.join([str(x) for x in under]) for a in leave: if hasattr(a, 'get_color'): a.set_color(self._active[a]) elif hasattr(a, 'get_edgecolor'): a.set_edgecolor(self._active[a][0]) a.set_facecolor(self._active[a][1]) del self._active[a] for a in enter: if hasattr(a, 'get_color'): self._active[a] = a.get_color() elif hasattr(a, 'get_edgecolor'): self._active[a] = (a.get_edgecolor(), a.get_facecolor()) else: self._active[a] = None for a in enter: if hasattr(a, 'get_color'): a.set_color('red') elif hasattr(a, 'get_edgecolor'): a.set_edgecolor('red') a.set_facecolor('lightblue') else: self._active[a] = None self.draw_idle()
'blit the canvas in bbox (default entire canvas)'
def blit(self, bbox=None):
pass
'set the canvas size in pixels'
def resize(self, w, h):
pass
'This method will be call all functions connected to the \'draw_event\' with a :class:`DrawEvent`'
def draw_event(self, renderer):
s = 'draw_event' event = DrawEvent(s, self, renderer) self.callbacks.process(s, event)
'This method will be call all functions connected to the \'resize_event\' with a :class:`ResizeEvent`'
def resize_event(self):
s = 'resize_event' event = ResizeEvent(s, self) self.callbacks.process(s, event)
'This method will be call all functions connected to the \'key_press_event\' with a :class:`KeyEvent`'
def key_press_event(self, key, guiEvent=None):
self._key = key s = 'key_press_event' event = KeyEvent(s, self, key, self._lastx, self._lasty, guiEvent=guiEvent) self.callbacks.process(s, event)
'This method will be call all functions connected to the \'key_release_event\' with a :class:`KeyEvent`'
def key_release_event(self, key, guiEvent=None):
s = 'key_release_event' event = KeyEvent(s, self, key, self._lastx, self._lasty, guiEvent=guiEvent) self.callbacks.process(s, event) self._key = None
'This method will be called by artists who are picked and will fire off :class:`PickEvent` callbacks registered listeners'
def pick_event(self, mouseevent, artist, **kwargs):
s = 'pick_event' event = PickEvent(s, self, mouseevent, artist, **kwargs) self.callbacks.process(s, event)
'Backend derived classes should call this function on any scroll wheel event. x,y are the canvas coords: 0,0 is lower, left. button and key are as defined in MouseEvent. This method will be call all functions connected to the \'scroll_event\' with a :class:`MouseEvent` instance.'
def scroll_event(self, x, y, step, guiEvent=None):
if (step >= 0): self._button = 'up' else: self._button = 'down' s = 'scroll_event' mouseevent = MouseEvent(s, self, x, y, self._button, self._key, step=step, guiEvent=guiEvent) self.callbacks.process(s, mouseevent)
'Backend derived classes should call this function on any mouse button press. x,y are the canvas coords: 0,0 is lower, left. button and key are as defined in :class:`MouseEvent`. This method will be call all functions connected to the \'button_press_event\' with a :class:`MouseEvent` instance.'
def button_press_event(self, x, y, button, guiEvent=None):
self._button = button s = 'button_press_event' mouseevent = MouseEvent(s, self, x, y, button, self._key, guiEvent=guiEvent) self.callbacks.process(s, mouseevent)
'Backend derived classes should call this function on any mouse button release. *x* the canvas coordinates where 0=left *y* the canvas coordinates where 0=bottom *guiEvent* the native UI event that generated the mpl event This method will be call all functions connected to the \'button_release_event\' with a :class:`MouseEvent` instance.'
def button_release_event(self, x, y, button, guiEvent=None):
s = 'button_release_event' event = MouseEvent(s, self, x, y, button, self._key, guiEvent=guiEvent) self.callbacks.process(s, event) self._button = None
'Backend derived classes should call this function on any motion-notify-event. *x* the canvas coordinates where 0=left *y* the canvas coordinates where 0=bottom *guiEvent* the native UI event that generated the mpl event This method will be call all functions connected to the \'motion_notify_event\' with a :class:`MouseEvent` instance.'
def motion_notify_event(self, x, y, guiEvent=None):
(self._lastx, self._lasty) = (x, y) s = 'motion_notify_event' event = MouseEvent(s, self, x, y, self._button, self._key, guiEvent=guiEvent) self.callbacks.process(s, event)
'Backend derived classes should call this function when leaving canvas *guiEvent* the native UI event that generated the mpl event'
def leave_notify_event(self, guiEvent=None):
self.callbacks.process('figure_leave_event', LocationEvent.lastevent) LocationEvent.lastevent = None
'Backend derived classes should call this function when entering canvas *guiEvent* the native UI event that generated the mpl event'
def enter_notify_event(self, guiEvent=None):
event = Event('figure_enter_event', self, guiEvent) self.callbacks.process('figure_enter_event', event)
'call when GUI is idle'
def idle_event(self, guiEvent=None):
s = 'idle_event' event = IdleEvent(s, self, guiEvent=guiEvent) self.callbacks.process(s, event)
'Render the :class:`~matplotlib.figure.Figure`'
def draw(self, *args, **kwargs):
pass
':meth:`draw` only if idle; defaults to draw but backends can overrride'
def draw_idle(self, *args, **kwargs):
self.draw(*args, **kwargs)
'Draw a cursor in the event.axes if inaxes is not None. Use native GUI drawing for efficiency if possible'
def draw_cursor(self, event):
pass
'return the figure width and height in points or pixels (depending on the backend), truncated to integers'
def get_width_height(self):
return (int(self.figure.bbox.width), int(self.figure.bbox.height))
'Render the figure to hardcopy. Set the figure patch face and edge colors. This is useful because some of the GUIs have a gray figure face color background and you\'ll probably want to override this on hardcopy. Arguments are: *filename* can also be a file object on image backends *orientation* only currently applies to PostScript printing. *dpi* the dots per inch to save the figure in; if None, use savefig.dpi *facecolor* the facecolor of the figure *edgecolor* the edgecolor of the figure *orientation* \' landscape\' | \'portrait\' (not supported on all backends) *format* when set, forcibly set the file format to save to'
def print_figure(self, filename, dpi=None, facecolor='w', edgecolor='w', orientation='portrait', format=None, **kwargs):
if (format is None): if cbook.is_string_like(filename): format = os.path.splitext(filename)[1][1:] if ((format is None) or (format == '')): format = self.get_default_filetype() if cbook.is_string_like(filename): filename = ((filename.rstrip('.') + '.') + format) format = format.lower() method_name = ('print_%s' % format) if ((format not in self.filetypes) or (not hasattr(self, method_name))): formats = self.filetypes.keys() formats.sort() raise ValueError(('Format "%s" is not supported.\nSupported formats: %s.' % (format, ', '.join(formats)))) if (dpi is None): dpi = rcParams['savefig.dpi'] origDPI = self.figure.dpi origfacecolor = self.figure.get_facecolor() origedgecolor = self.figure.get_edgecolor() self.figure.dpi = dpi self.figure.set_facecolor(facecolor) self.figure.set_edgecolor(edgecolor) try: result = getattr(self, method_name)(filename, dpi=dpi, facecolor=facecolor, edgecolor=edgecolor, orientation=orientation, **kwargs) finally: self.figure.dpi = origDPI self.figure.set_facecolor(origfacecolor) self.figure.set_edgecolor(origedgecolor) self.figure.set_canvas(self) return result
'Set the title text of the window containing the figure. Note that this has no effect if there is no window (eg, a PS backend).'
def set_window_title(self, title):
if hasattr(self, 'manager'): self.manager.set_window_title(title)
'instantiate an instance of FigureCanvasClass This is used for backend switching, eg, to instantiate a FigureCanvasPS from a FigureCanvasGTK. Note, deep copying is not done, so any changes to one of the instances (eg, setting figure size or line props), will be reflected in the other'
def switch_backends(self, FigureCanvasClass):
newCanvas = FigureCanvasClass(self.figure) return newCanvas
'Connect event with string *s* to *func*. The signature of *func* is:: def func(event) where event is a :class:`matplotlib.backend_bases.Event`. The following events are recognized - \'button_press_event\' - \'button_release_event\' - \'draw_event\' - \'key_press_event\' - \'key_release_event\' - \'motion_notify_event\' - \'pick_event\' - \'resize_event\' - \'scroll_event\' For the location events (button and key press/release), if the mouse is over the axes, the variable ``event.inaxes`` will be set to the :class:`~matplotlib.axes.Axes` the event occurs is over, and additionally, the variables ``event.xdata`` and ``event.ydata`` will be defined. This is the mouse location in data coords. See :class:`~matplotlib.backend_bases.KeyEvent` and :class:`~matplotlib.backend_bases.MouseEvent` for more info. Return value is a connection id that can be used with :meth:`~matplotlib.backend_bases.Event.mpl_disconnect`. Example usage:: def on_press(event): print \'you pressed\', event.button, event.xdata, event.ydata cid = canvas.mpl_connect(\'button_press_event\', on_press)'
def mpl_connect(self, s, func):
return self.callbacks.connect(s, func)
'disconnect callback id cid Example usage:: cid = canvas.mpl_connect(\'button_press_event\', on_press) #...later canvas.mpl_disconnect(cid)'
def mpl_disconnect(self, cid):
return self.callbacks.disconnect(cid)
'Flush the GUI events for the figure. Implemented only for backends with GUIs.'
def flush_events(self):
raise NotImplementedError
'Start an event loop. This is used to start a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This should not be confused with the main GUI event loop, which is always running and has nothing to do with this. This is implemented only for backends with GUIs.'
def start_event_loop(self, timeout):
raise NotImplementedError
'Stop an event loop. This is used to stop a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This is implemented only for backends with GUIs.'
def stop_event_loop(self):
raise NotImplementedError
'Start an event loop. This is used to start a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This should not be confused with the main GUI event loop, which is always running and has nothing to do with this. This function provides default event loop functionality based on time.sleep that is meant to be used until event loop functions for each of the GUI backends can be written. As such, it throws a deprecated warning. Call signature:: start_event_loop_default(self,timeout=0) This call blocks until a callback function triggers stop_event_loop() or *timeout* is reached. If *timeout* is <=0, never timeout.'
def start_event_loop_default(self, timeout=0):
str = 'Using default event loop until function specific' str += ' to this GUI is implemented' warnings.warn(str, DeprecationWarning) if (timeout <= 0): timeout = np.inf timestep = 0.01 counter = 0 self._looping = True while (self._looping and ((counter * timestep) < timeout)): self.flush_events() time.sleep(timestep) counter += 1
'Stop an event loop. This is used to stop a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. Call signature:: stop_event_loop_default(self)'
def stop_event_loop_default(self):
self._looping = False
'For gui backends: resize window in pixels'
def resize(self, w, h):
pass
'Display message in a popup -- GUI only'
def show_popup(self, msg):
pass
'Set the title text of the window containing the figure. Note that this has no effect if there is no window (eg, a PS backend).'
def set_window_title(self, title):
pass
'display a message on toolbar or in status bar'
def set_message(self, s):
pass
'move back up the view lim stack'
def back(self, *args):
self._views.back() self._positions.back() self.set_history_buttons() self._update_view()
'draw a rectangle rubberband to indicate zoom limits'
def draw_rubberband(self, event, x0, y0, x1, y1):
pass
'move forward in the view lim stack'
def forward(self, *args):
self._views.forward() self._positions.forward() self.set_history_buttons() self._update_view()
'restore the original view'
def home(self, *args):
self._views.home() self._positions.home() self.set_history_buttons() self._update_view()
'This is where you actually build the GUI widgets (called by __init__). The icons ``home.xpm``, ``back.xpm``, ``forward.xpm``, ``hand.xpm``, ``zoom_to_rect.xpm`` and ``filesave.xpm`` are standard across backends (there are ppm versions in CVS also). You just need to set the callbacks home : self.home back : self.back forward : self.forward hand : self.pan zoom_to_rect : self.zoom filesave : self.save_figure You only need to define the last one - the others are in the base class implementation.'
def _init_toolbar(self):
raise NotImplementedError
'Activate the pan/zoom tool. pan with left button, zoom with right'
def pan(self, *args):
if (self._active == 'PAN'): self._active = None else: self._active = 'PAN' if (self._idPress is not None): self._idPress = self.canvas.mpl_disconnect(self._idPress) self.mode = '' if (self._idRelease is not None): self._idRelease = self.canvas.mpl_disconnect(self._idRelease) self.mode = '' if self._active: self._idPress = self.canvas.mpl_connect('button_press_event', self.press_pan) self._idRelease = self.canvas.mpl_connect('button_release_event', self.release_pan) self.mode = 'pan/zoom mode' self.canvas.widgetlock(self) else: self.canvas.widgetlock.release(self) for a in self.canvas.figure.get_axes(): a.set_navigate_mode(self._active) self.set_message(self.mode)
'this will be called whenver a mouse button is pressed'
def press(self, event):
pass
'the press mouse button in pan/zoom mode callback'
def press_pan(self, event):
if (event.button == 1): self._button_pressed = 1 elif (event.button == 3): self._button_pressed = 3 else: self._button_pressed = None return (x, y) = (event.x, event.y) if self._views.empty(): self.push_current() self._xypress = [] for (i, a) in enumerate(self.canvas.figure.get_axes()): if ((x is not None) and (y is not None) and a.in_axes(event) and a.get_navigate()): a.start_pan(x, y, event.button) self._xypress.append((a, i)) self.canvas.mpl_disconnect(self._idDrag) self._idDrag = self.canvas.mpl_connect('motion_notify_event', self.drag_pan) self.press(event)
'the press mouse button in zoom to rect mode callback'
def press_zoom(self, event):
if (event.button == 1): self._button_pressed = 1 elif (event.button == 3): self._button_pressed = 3 else: self._button_pressed = None return (x, y) = (event.x, event.y) if self._views.empty(): self.push_current() self._xypress = [] for (i, a) in enumerate(self.canvas.figure.get_axes()): if ((x is not None) and (y is not None) and a.in_axes(event) and a.get_navigate() and a.can_zoom()): self._xypress.append((x, y, a, i, a.viewLim.frozen(), a.transData.frozen())) self.press(event)
'push the current view limits and position onto the stack'
def push_current(self):
lims = [] pos = [] for a in self.canvas.figure.get_axes(): (xmin, xmax) = a.get_xlim() (ymin, ymax) = a.get_ylim() lims.append((xmin, xmax, ymin, ymax)) pos.append((a.get_position(True).frozen(), a.get_position().frozen())) self._views.push(lims) self._positions.push(pos) self.set_history_buttons()
'this will be called whenever mouse button is released'
def release(self, event):
pass
'the release mouse button callback in pan/zoom mode'
def release_pan(self, event):
self.canvas.mpl_disconnect(self._idDrag) self._idDrag = self.canvas.mpl_connect('motion_notify_event', self.mouse_move) for (a, ind) in self._xypress: a.end_pan() if (not self._xypress): return self._xypress = [] self._button_pressed = None self.push_current() self.release(event) self.draw()
'the drag callback in pan/zoom mode'
def drag_pan(self, event):
for (a, ind) in self._xypress: a.drag_pan(self._button_pressed, event.key, event.x, event.y) self.dynamic_update()
'the release mouse button callback in zoom to rect mode'
def release_zoom(self, event):
if (not self._xypress): return last_a = [] for cur_xypress in self._xypress: (x, y) = (event.x, event.y) (lastx, lasty, a, ind, lim, trans) = cur_xypress if ((abs((x - lastx)) < 5) or (abs((y - lasty)) < 5)): self._xypress = None self.release(event) self.draw() return (x0, y0, x1, y1) = lim.extents inverse = a.transData.inverted() (lastx, lasty) = inverse.transform_point((lastx, lasty)) (x, y) = inverse.transform_point((x, y)) (Xmin, Xmax) = a.get_xlim() (Ymin, Ymax) = a.get_ylim() (twinx, twiny) = (False, False) if last_a: for la in last_a: if a.get_shared_x_axes().joined(a, la): twinx = True if a.get_shared_y_axes().joined(a, la): twiny = True last_a.append(a) if twinx: (x0, x1) = (Xmin, Xmax) elif (Xmin < Xmax): if (x < lastx): (x0, x1) = (x, lastx) else: (x0, x1) = (lastx, x) if (x0 < Xmin): x0 = Xmin if (x1 > Xmax): x1 = Xmax else: if (x > lastx): (x0, x1) = (x, lastx) else: (x0, x1) = (lastx, x) if (x0 > Xmin): x0 = Xmin if (x1 < Xmax): x1 = Xmax if twiny: (y0, y1) = (Ymin, Ymax) elif (Ymin < Ymax): if (y < lasty): (y0, y1) = (y, lasty) else: (y0, y1) = (lasty, y) if (y0 < Ymin): y0 = Ymin if (y1 > Ymax): y1 = Ymax else: if (y > lasty): (y0, y1) = (y, lasty) else: (y0, y1) = (lasty, y) if (y0 > Ymin): y0 = Ymin if (y1 < Ymax): y1 = Ymax if (self._button_pressed == 1): a.set_xlim((x0, x1)) a.set_ylim((y0, y1)) elif (self._button_pressed == 3): if (a.get_xscale() == 'log'): alpha = (np.log((Xmax / Xmin)) / np.log((x1 / x0))) rx1 = (pow((Xmin / x0), alpha) * Xmin) rx2 = (pow((Xmax / x0), alpha) * Xmin) else: alpha = ((Xmax - Xmin) / (x1 - x0)) rx1 = ((alpha * (Xmin - x0)) + Xmin) rx2 = ((alpha * (Xmax - x0)) + Xmin) if (a.get_yscale() == 'log'): alpha = (np.log((Ymax / Ymin)) / np.log((y1 / y0))) ry1 = (pow((Ymin / y0), alpha) * Ymin) ry2 = (pow((Ymax / y0), alpha) * Ymin) else: alpha = ((Ymax - Ymin) / (y1 - y0)) ry1 = ((alpha * (Ymin - y0)) + Ymin) ry2 = ((alpha * (Ymax - y0)) + Ymin) a.set_xlim((rx1, rx2)) a.set_ylim((ry1, ry2)) self.draw() self._xypress = None self._button_pressed = None self.push_current() self.release(event)
'redraw the canvases, update the locators'
def draw(self):
for a in self.canvas.figure.get_axes(): xaxis = getattr(a, 'xaxis', None) yaxis = getattr(a, 'yaxis', None) locators = [] if (xaxis is not None): locators.append(xaxis.get_major_locator()) locators.append(xaxis.get_minor_locator()) if (yaxis is not None): locators.append(yaxis.get_major_locator()) locators.append(yaxis.get_minor_locator()) for loc in locators: loc.refresh() self.canvas.draw()
'update the viewlim and position from the view and position stack for each axes'
def _update_view(self):
lims = self._views() if (lims is None): return pos = self._positions() if (pos is None): return for (i, a) in enumerate(self.canvas.figure.get_axes()): (xmin, xmax, ymin, ymax) = lims[i] a.set_xlim((xmin, xmax)) a.set_ylim((ymin, ymax)) a.set_position(pos[i][0], 'original') a.set_position(pos[i][1], 'active') self.draw()
'save the current figure'
def save_figure(self, *args):
raise NotImplementedError
'Set the current cursor to one of the :class:`Cursors` enums values'
def set_cursor(self, cursor):
pass
'reset the axes stack'
def update(self):
self._views.clear() self._positions.clear() self.set_history_buttons()
'activate zoom to rect mode'
def zoom(self, *args):
if (self._active == 'ZOOM'): self._active = None else: self._active = 'ZOOM' if (self._idPress is not None): self._idPress = self.canvas.mpl_disconnect(self._idPress) self.mode = '' if (self._idRelease is not None): self._idRelease = self.canvas.mpl_disconnect(self._idRelease) self.mode = '' if self._active: self._idPress = self.canvas.mpl_connect('button_press_event', self.press_zoom) self._idRelease = self.canvas.mpl_connect('button_release_event', self.release_zoom) self.mode = 'Zoom to rect mode' self.canvas.widgetlock(self) else: self.canvas.widgetlock.release(self) for a in self.canvas.figure.get_axes(): a.set_navigate_mode(self._active) self.set_message(self.mode)
'enable or disable back/forward button'
def set_history_buttons(self):
pass
'Calculate any free parameters based on the current cmap and norm, and do all the drawing.'
def draw_all(self):
self._process_values() self._find_range() (X, Y) = self._mesh() C = self._values[:, np.newaxis] self._config_axes(X, Y) if self.filled: self._add_solids(X, Y, C) self._set_label()
'Make an axes patch and outline.'
def _config_axes(self, X, Y):
ax = self.ax ax.set_frame_on(False) ax.set_navigate(False) xy = self._outline(X, Y) ax.update_datalim(xy) ax.set_xlim(*ax.dataLim.intervalx) ax.set_ylim(*ax.dataLim.intervaly) self.outline = lines.Line2D(xy[:, 0], xy[:, 1], color=mpl.rcParams['axes.edgecolor'], linewidth=mpl.rcParams['axes.linewidth']) ax.add_artist(self.outline) self.outline.set_clip_box(None) self.outline.set_clip_path(None) c = mpl.rcParams['axes.facecolor'] self.patch = patches.Polygon(xy, edgecolor=c, facecolor=c, linewidth=0.01, zorder=(-1)) ax.add_artist(self.patch) (ticks, ticklabels, offset_string) = self._ticker() if (self.orientation == 'vertical'): ax.set_xticks([]) ax.yaxis.set_label_position('right') ax.yaxis.set_ticks_position('right') ax.set_yticks(ticks) ax.set_yticklabels(ticklabels) ax.yaxis.get_major_formatter().set_offset_string(offset_string) else: ax.set_yticks([]) ax.xaxis.set_label_position('bottom') ax.set_xticks(ticks) ax.set_xticklabels(ticklabels) ax.xaxis.get_major_formatter().set_offset_string(offset_string)
'Label the long axis of the colorbar'
def set_label(self, label, **kw):
self._label = label self._labelkw = kw self._set_label()
'Return *x*, *y* arrays of colorbar bounding polygon, taking orientation into account.'
def _outline(self, X, Y):
N = X.shape[0] ii = [0, 1, (N - 2), (N - 1), ((2 * N) - 1), ((2 * N) - 2), (N + 1), N, 0] x = np.take(np.ravel(np.transpose(X)), ii) y = np.take(np.ravel(np.transpose(Y)), ii) x = x.reshape((len(x), 1)) y = y.reshape((len(y), 1)) if (self.orientation == 'horizontal'): return np.hstack((y, x)) return np.hstack((x, y))
'Return the separator line segments; helper for _add_solids.'
def _edges(self, X, Y):
N = X.shape[0] if (self.orientation == 'vertical'): return [zip(X[i], Y[i]) for i in range(1, (N - 1))] else: return [zip(Y[i], X[i]) for i in range(1, (N - 1))]
'Draw the colors using :meth:`~matplotlib.axes.Axes.pcolor`; optionally add separators.'
def _add_solids(self, X, Y, C):
if (self.orientation == 'vertical'): args = (X, Y, C) else: args = (np.transpose(Y), np.transpose(X), np.transpose(C)) kw = {'cmap': self.cmap, 'norm': self.norm, 'shading': 'flat', 'alpha': self.alpha} _hold = self.ax.ishold() self.ax.hold(True) col = self.ax.pcolor(*args, **kw) self.ax.hold(_hold) self.solids = col if self.drawedges: self.dividers = collections.LineCollection(self._edges(X, Y), colors=(mpl.rcParams['axes.edgecolor'],), linewidths=((0.5 * mpl.rcParams['axes.linewidth']),)) self.ax.add_collection(self.dividers)
'Draw lines on the colorbar.'
def add_lines(self, levels, colors, linewidths):
N = len(levels) (dummy, y) = self._locate(levels) if (len(y) != N): raise ValueError('levels are outside colorbar range') x = np.array([0.0, 1.0]) (X, Y) = np.meshgrid(x, y) if (self.orientation == 'vertical'): xy = [zip(X[i], Y[i]) for i in range(N)] else: xy = [zip(Y[i], X[i]) for i in range(N)] col = collections.LineCollection(xy, linewidths=linewidths) self.lines = col col.set_color(colors) self.ax.add_collection(col)
'Return two sequences: ticks (colorbar data locations) and ticklabels (strings).'
def _ticker(self):
locator = self.locator formatter = self.formatter if (locator is None): if (self.boundaries is None): if isinstance(self.norm, colors.NoNorm): nv = len(self._values) base = (1 + int((nv / 10))) locator = ticker.IndexLocator(base=base, offset=0) elif isinstance(self.norm, colors.BoundaryNorm): b = self.norm.boundaries locator = ticker.FixedLocator(b, nbins=10) elif isinstance(self.norm, colors.LogNorm): locator = ticker.LogLocator() else: locator = ticker.MaxNLocator() else: b = self._boundaries[self._inside] locator = ticker.FixedLocator(b, nbins=10) if isinstance(self.norm, colors.NoNorm): intv = (self._values[0], self._values[(-1)]) else: intv = (self.vmin, self.vmax) locator.create_dummy_axis() formatter.create_dummy_axis() locator.set_view_interval(*intv) locator.set_data_interval(*intv) formatter.set_view_interval(*intv) formatter.set_data_interval(*intv) b = np.array(locator()) (b, ticks) = self._locate(b) formatter.set_locs(b) ticklabels = [formatter(t, i) for (i, t) in enumerate(b)] offset_string = formatter.get_offset() return (ticks, ticklabels, offset_string)
'Set the :attr:`_boundaries` and :attr:`_values` attributes based on the input boundaries and values. Input boundaries can be *self.boundaries* or the argument *b*.'
def _process_values(self, b=None):
if (b is None): b = self.boundaries if (b is not None): self._boundaries = np.asarray(b, dtype=float) if (self.values is None): self._values = (0.5 * (self._boundaries[:(-1)] + self._boundaries[1:])) if isinstance(self.norm, colors.NoNorm): self._values = (self._values + 1e-05).astype(np.int16) return self._values = np.array(self.values) return if (self.values is not None): self._values = np.array(self.values) if (self.boundaries is None): b = np.zeros((len(self.values) + 1), 'd') b[1:(-1)] = (0.5 * (self._values[:(-1)] - self._values[1:])) b[0] = ((2.0 * b[1]) - b[2]) b[(-1)] = ((2.0 * b[(-2)]) - b[(-3)]) self._boundaries = b return self._boundaries = np.array(self.boundaries) return if isinstance(self.norm, colors.NoNorm): b = ((self._uniform_y((self.cmap.N + 1)) * self.cmap.N) - 0.5) v = np.zeros(((len(b) - 1),), dtype=np.int16) v[self._inside] = np.arange(self.cmap.N, dtype=np.int16) if (self.extend in ('both', 'min')): v[0] = (-1) if (self.extend in ('both', 'max')): v[(-1)] = self.cmap.N self._boundaries = b self._values = v return elif isinstance(self.norm, colors.BoundaryNorm): b = list(self.norm.boundaries) if (self.extend in ('both', 'min')): b = ([(b[0] - 1)] + b) if (self.extend in ('both', 'max')): b = (b + [(b[(-1)] + 1)]) b = np.array(b) v = np.zeros(((len(b) - 1),), dtype=float) bi = self.norm.boundaries v[self._inside] = (0.5 * (bi[:(-1)] + bi[1:])) if (self.extend in ('both', 'min')): v[0] = (b[0] - 1) if (self.extend in ('both', 'max')): v[(-1)] = (b[(-1)] + 1) self._boundaries = b self._values = v return else: if (not self.norm.scaled()): self.norm.vmin = 0 self.norm.vmax = 1 b = self.norm.inverse(self._uniform_y((self.cmap.N + 1))) if (self.extend in ('both', 'min')): b[0] = (b[0] - 1) if (self.extend in ('both', 'max')): b[(-1)] = (b[(-1)] + 1) self._process_values(b)
'Set :attr:`vmin` and :attr:`vmax` attributes to the first and last boundary excluding extended end boundaries.'
def _find_range(self):
b = self._boundaries[self._inside] self.vmin = b[0] self.vmax = b[(-1)]
'number of boundaries **before** extension of ends'
def _central_N(self):
nb = len(self._boundaries) if (self.extend == 'both'): nb -= 2 elif (self.extend in ('min', 'max')): nb -= 1 return nb
'Based on the colormap and extend variable, return the number of boundaries.'
def _extended_N(self):
N = (self.cmap.N + 1) if (self.extend == 'both'): N += 2 elif (self.extend in ('min', 'max')): N += 1 return N
'Return colorbar data coordinates for *N* uniformly spaced boundaries, plus ends if required.'
def _uniform_y(self, N):
if (self.extend == 'neither'): y = np.linspace(0, 1, N) else: if (self.extend == 'both'): y = np.zeros((N + 2), 'd') y[0] = (-0.05) y[(-1)] = 1.05 elif (self.extend == 'min'): y = np.zeros((N + 1), 'd') y[0] = (-0.05) else: y = np.zeros((N + 1), 'd') y[(-1)] = 1.05 y[self._inside] = np.linspace(0, 1, N) return y
'Return colorbar data coordinates for the boundaries of a proportional colorbar.'
def _proportional_y(self):
if isinstance(self.norm, colors.BoundaryNorm): b = self._boundaries[self._inside] y = (self._boundaries - self._boundaries[0]) y = (y / (self._boundaries[(-1)] - self._boundaries[0])) else: y = self.norm(self._boundaries.copy()) if (self.extend in ('both', 'min')): y[0] = (-0.05) if (self.extend in ('both', 'max')): y[(-1)] = 1.05 yi = y[self._inside] norm = colors.Normalize(yi[0], yi[(-1)]) y[self._inside] = norm(yi) return y
'Return X,Y, the coordinate arrays for the colorbar pcolormesh. These are suitable for a vertical colorbar; swapping and transposition for a horizontal colorbar are done outside this function.'
def _mesh(self):
x = np.array([0.0, 1.0]) if (self.spacing == 'uniform'): y = self._uniform_y(self._central_N()) else: y = self._proportional_y() self._y = y (X, Y) = np.meshgrid(x, y) if (self.extend in ('min', 'both')): X[0, :] = 0.5 if (self.extend in ('max', 'both')): X[(-1), :] = 0.5 return (X, Y)
'Given a possible set of color data values, return the ones within range, together with their corresponding colorbar data coordinates.'
def _locate(self, x):
if isinstance(self.norm, (colors.NoNorm, colors.BoundaryNorm)): b = self._boundaries xn = x xout = x else: b = self.norm(self._boundaries, clip=False).filled() xn = self.norm(x, clip=False).filled() in_cond = ((xn > (-0.001)) & (xn < 1.001)) xn = np.compress(in_cond, xn) xout = np.compress(in_cond, x) y = self._y N = len(b) ii = np.minimum(np.searchsorted(b, xn), (N - 1)) i0 = np.maximum((ii - 1), 0) db = (np.take(b, ii) - np.take(b, i0)) db = np.where((i0 == ii), 1.0, db) dy = (np.take(y, ii) - np.take(y, i0)) z = (np.take(y, i0) + (((xn - np.take(b, i0)) * dy) / db)) return (xout, z)