desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'alias for get_style'
def get_fontstyle(self):
return self.get_style()
'alias for get_size'
def get_fontsize(self):
return self.get_size()
'alias for get_weight'
def get_fontweight(self):
return self.get_weight()
'Get the font stretch as a string or number'
def get_stretch(self):
return self._fontproperties.get_stretch()
'alias for get_stretch'
def get_fontstretch(self):
return self.get_stretch()
'alias for get_horizontalalignment'
def get_ha(self):
return self.get_horizontalalignment()
'Return the horizontal alignment as string. Will be one of \'left\', \'center\' or \'right\'.'
def get_horizontalalignment(self):
return self._horizontalalignment
'Return the position of the text as a tuple (*x*, *y*)'
def get_position(self):
x = float(self.convert_xunits(self._x)) y = float(self.convert_yunits(self._y)) return (x, y)
'Return a hashable tuple of properties. Not intended to be human readable, but useful for backends who want to cache derived information about text (eg layouts) and need to know if the text has changed.'
def get_prop_tup(self):
(x, y) = self.get_position() return (x, y, self._text, self._color, self._verticalalignment, self._horizontalalignment, hash(self._fontproperties), self._rotation, self.figure.dpi, id(self._renderer))
'Get the text as string'
def get_text(self):
return self._text
'alias for :meth:`getverticalalignment`'
def get_va(self):
return self.get_verticalalignment()
'Return the vertical alignment as string. Will be one of \'top\', \'center\', \'bottom\' or \'baseline\'.'
def get_verticalalignment(self):
return self._verticalalignment
'Return a :class:`~matplotlib.transforms.Bbox` object bounding the text, in display units. In addition to being used internally, this is useful for specifying clickable regions in a png file on a web page. *renderer* defaults to the _renderer attribute of the text object. This is not assigned until the first execution of :meth:`draw`, so you must use this kwarg if you want to call :meth:`get_window_extent` prior to the first :meth:`draw`. For getting web page regions, it is simpler to call the method after saving the figure. *dpi* defaults to self.figure.dpi; the renderer dpi is irrelevant. For the web application, if figure.dpi is not the value used when saving the figure, then the value that was used must be specified as the *dpi* argument.'
def get_window_extent(self, renderer=None, dpi=None):
if (not self.get_visible()): return Bbox.unit() if (dpi is not None): dpi_orig = self.figure.dpi self.figure.dpi = dpi if (self._text == ''): (tx, ty) = self._get_xy_display() return Bbox.from_bounds(tx, ty, 0, 0) if (renderer is not None): self._renderer = renderer if (self._renderer is None): raise RuntimeError('Cannot get window extent w/o renderer') (bbox, info) = self._get_layout(self._renderer) (x, y) = self.get_position() (x, y) = self.get_transform().transform_point((x, y)) bbox = bbox.translated(x, y) if (dpi is not None): self.figure.dpi = dpi_orig return bbox
'Set the background color of the text by updating the bbox. .. seealso:: :meth:`set_bbox` ACCEPTS: any matplotlib color'
def set_backgroundcolor(self, color):
if (self._bbox is None): self._bbox = dict(facecolor=color, edgecolor=color) else: self._bbox.update(dict(facecolor=color))
'Set the foreground color of the text ACCEPTS: any matplotlib color'
def set_color(self, color):
try: hash(color) except TypeError: color = tuple(color) self._color = color
'alias for set_horizontalalignment'
def set_ha(self, align):
self.set_horizontalalignment(align)
'Set the horizontal alignment to one of ACCEPTS: [ \'center\' | \'right\' | \'left\' ]'
def set_horizontalalignment(self, align):
legal = ('center', 'right', 'left') if (align not in legal): raise ValueError(('Horizontal alignment must be one of %s' % str(legal))) self._horizontalalignment = align
'alias for set_verticalalignment'
def set_ma(self, align):
self.set_multialignment(align)
'Set the alignment for multiple lines layout. The layout of the bounding box of all the lines is determined bu the horizontalalignment and verticalalignment properties, but the multiline text within that box can be ACCEPTS: [\'left\' | \'right\' | \'center\' ]'
def set_multialignment(self, align):
legal = ('center', 'right', 'left') if (align not in legal): raise ValueError(('Horizontal alignment must be one of %s' % str(legal))) self._multialignment = align
'Set the line spacing as a multiple of the font size. Default is 1.2. ACCEPTS: float (multiple of font size)'
def set_linespacing(self, spacing):
self._linespacing = spacing
'Set the font family. May be either a single string, or a list of strings in decreasing priority. Each string may be either a real font name or a generic font class name. If the latter, the specific font names will be looked up in the :file:`matplotlibrc` file. ACCEPTS: [ FONTNAME | \'serif\' | \'sans-serif\' | \'cursive\' | \'fantasy\' | \'monospace\' ]'
def set_family(self, fontname):
self._fontproperties.set_family(fontname)
'Set the font variant, either \'normal\' or \'small-caps\'. ACCEPTS: [ \'normal\' | \'small-caps\' ]'
def set_variant(self, variant):
self._fontproperties.set_variant(variant)
'alias for set_variant'
def set_fontvariant(self, variant):
return self.set_variant(variant)
'alias for set_family'
def set_name(self, fontname):
return self.set_family(fontname)
'alias for set_family'
def set_fontname(self, fontname):
self.set_family(fontname)
'Set the font style. ACCEPTS: [ \'normal\' | \'italic\' | \'oblique\']'
def set_style(self, fontstyle):
self._fontproperties.set_style(fontstyle)
'alias for set_style'
def set_fontstyle(self, fontstyle):
return self.set_style(fontstyle)
'Set the font size. May be either a size string, relative to the default font size, or an absolute font size in points. ACCEPTS: [ size in points | \'xx-small\' | \'x-small\' | \'small\' | \'medium\' | \'large\' | \'x-large\' | \'xx-large\' ]'
def set_size(self, fontsize):
self._fontproperties.set_size(fontsize)
'alias for set_size'
def set_fontsize(self, fontsize):
return self.set_size(fontsize)
'Set the font weight. ACCEPTS: [ a numeric value in range 0-1000 | \'ultralight\' | \'light\' | \'normal\' | \'regular\' | \'book\' | \'medium\' | \'roman\' | \'semibold\' | \'demibold\' | \'demi\' | \'bold\' | \'heavy\' | \'extra bold\' | \'black\' ]'
def set_weight(self, weight):
self._fontproperties.set_weight(weight)
'alias for set_weight'
def set_fontweight(self, weight):
return self.set_weight(weight)
'Set the font stretch (horizontal condensation or expansion). ACCEPTS: [ a numeric value in range 0-1000 | \'ultra-condensed\' | \'extra-condensed\' | \'condensed\' | \'semi-condensed\' | \'normal\' | \'semi-expanded\' | \'expanded\' | \'extra-expanded\' | \'ultra-expanded\' ]'
def set_stretch(self, stretch):
self._fontproperties.set_stretch(stretch)
'alias for set_stretch'
def set_fontstretch(self, stretch):
return self.set_stretch(stretch)
'Set the (*x*, *y*) position of the text ACCEPTS: (x,y)'
def set_position(self, xy):
self.set_x(xy[0]) self.set_y(xy[1])
'Set the *x* position of the text ACCEPTS: float'
def set_x(self, x):
self._x = x
'Set the *y* position of the text ACCEPTS: float'
def set_y(self, y):
self._y = y
'Set the rotation of the text ACCEPTS: [ angle in degrees | \'vertical\' | \'horizontal\' ]'
def set_rotation(self, s):
self._rotation = s
'alias for set_verticalalignment'
def set_va(self, align):
self.set_verticalalignment(align)
'Set the vertical alignment ACCEPTS: [ \'center\' | \'top\' | \'bottom\' | \'baseline\' ]'
def set_verticalalignment(self, align):
legal = ('top', 'bottom', 'center', 'baseline') if (align not in legal): raise ValueError(('Vertical alignment must be one of %s' % str(legal))) self._verticalalignment = align
'Set the text string *s* It may contain newlines (``\n``) or math in LaTeX syntax. ACCEPTS: string or anything printable with \'%s\' conversion.'
def set_text(self, s):
self._text = ('%s' % (s,))
'Returns True if the given string *s* contains any mathtext.'
def is_math_text(self, s):
dollar_count = (s.count('$') - s.count('\\$')) even_dollars = ((dollar_count > 0) and ((dollar_count % 2) == 0)) if rcParams['text.usetex']: return (s, 'TeX') if even_dollars: return (s, True) else: return (s.replace('\\$', '$'), False)
'Set the font properties that control the text. *fp* must be a :class:`matplotlib.font_manager.FontProperties` object. ACCEPTS: a :class:`matplotlib.font_manager.FontProperties` instance'
def set_fontproperties(self, fp):
if is_string_like(fp): fp = FontProperties(fp) self._fontproperties = fp.copy()
'alias for set_fontproperties'
def set_font_properties(self, fp):
self.set_fontproperties(fp)
'Return the position of the text as a tuple (*x*, *y*)'
def get_position(self):
x = float(self.convert_xunits(self._dashx)) y = float(self.convert_yunits(self._dashy)) return (x, y)
'Return a hashable tuple of properties. Not intended to be human readable, but useful for backends who want to cache derived information about text (eg layouts) and need to know if the text has changed.'
def get_prop_tup(self):
props = [p for p in Text.get_prop_tup(self)] props.extend([self._x, self._y, self._dashlength, self._dashdirection, self._dashrotation, self._dashpad, self._dashpush]) return tuple(props)
'Draw the :class:`TextWithDash` object to the given *renderer*.'
def draw(self, renderer):
self.update_coords(renderer) Text.draw(self, renderer) if (self.get_dashlength() > 0.0): self.dashline.draw(renderer)
'Computes the actual *x*, *y* coordinates for text based on the input *x*, *y* and the *dashlength*. Since the rotation is with respect to the actual canvas\'s coordinates we need to map back and forth.'
def update_coords(self, renderer):
(dashx, dashy) = self.get_position() dashlength = self.get_dashlength() if (dashlength == 0.0): (self._x, self._y) = (dashx, dashy) return dashrotation = self.get_dashrotation() dashdirection = self.get_dashdirection() dashpad = self.get_dashpad() dashpush = self.get_dashpush() angle = get_rotation(dashrotation) theta = (np.pi * (((angle / 180.0) + dashdirection) - 1)) (cos_theta, sin_theta) = (np.cos(theta), np.sin(theta)) transform = self.get_transform() cxy = transform.transform_point((dashx, dashy)) cd = np.array([cos_theta, sin_theta]) c1 = (cxy + (dashpush * cd)) c2 = (cxy + ((dashpush + dashlength) * cd)) inverse = transform.inverted() (x1, y1) = inverse.transform_point(tuple(c1)) (x2, y2) = inverse.transform_point(tuple(c2)) self.dashline.set_data((x1, x2), (y1, y2)) we = Text.get_window_extent(self, renderer=renderer) (w, h) = (we.width, we.height) if (sin_theta == 0.0): dx = w dy = 0.0 elif (cos_theta == 0.0): dx = 0.0 dy = h else: tan_theta = (sin_theta / cos_theta) dx = w dy = (w * tan_theta) if ((dy > h) or (dy < (- h))): dy = h dx = (h / tan_theta) cwd = (np.array([dx, dy]) / 2) cwd *= (1 + (dashpad / np.sqrt(np.dot(cwd, cwd)))) cw = (c2 + (((dashdirection * 2) - 1) * cwd)) (newx, newy) = inverse.transform_point(tuple(cw)) (self._x, self._y) = (newx, newy) we = Text.get_window_extent(self, renderer=renderer) self._twd_window_extent = we.frozen() self._twd_window_extent.update_from_data_xy(np.array([c1]), False) Text.set_horizontalalignment(self, 'center') Text.set_verticalalignment(self, 'center')
'Return a :class:`~matplotlib.transforms.Bbox` object bounding the text, in display units. In addition to being used internally, this is useful for specifying clickable regions in a png file on a web page. *renderer* defaults to the _renderer attribute of the text object. This is not assigned until the first execution of :meth:`draw`, so you must use this kwarg if you want to call :meth:`get_window_extent` prior to the first :meth:`draw`. For getting web page regions, it is simpler to call the method after saving the figure.'
def get_window_extent(self, renderer=None):
self.update_coords(renderer) if (self.get_dashlength() == 0.0): return Text.get_window_extent(self, renderer=renderer) else: return self._twd_window_extent
'Get the length of the dash.'
def get_dashlength(self):
return self._dashlength
'Set the length of the dash. ACCEPTS: float (canvas units)'
def set_dashlength(self, dl):
self._dashlength = dl
'Get the direction dash. 1 is before the text and 0 is after.'
def get_dashdirection(self):
return self._dashdirection
'Set the direction of the dash following the text. 1 is before the text and 0 is after. The default is 0, which is what you\'d want for the typical case of ticks below and on the left of the figure. ACCEPTS: int (1 is before, 0 is after)'
def set_dashdirection(self, dd):
self._dashdirection = dd
'Get the rotation of the dash in degrees.'
def get_dashrotation(self):
if (self._dashrotation == None): return self.get_rotation() else: return self._dashrotation
'Set the rotation of the dash, in degrees ACCEPTS: float (degrees)'
def set_dashrotation(self, dr):
self._dashrotation = dr
'Get the extra spacing between the dash and the text, in canvas units.'
def get_dashpad(self):
return self._dashpad
'Set the "pad" of the TextWithDash, which is the extra spacing between the dash and the text, in canvas units. ACCEPTS: float (canvas units)'
def set_dashpad(self, dp):
self._dashpad = dp
'Get the extra spacing between the dash and the specified text position, in canvas units.'
def get_dashpush(self):
return self._dashpush
'Set the "push" of the TextWithDash, which is the extra spacing between the beginning of the dash and the specified position. ACCEPTS: float (canvas units)'
def set_dashpush(self, dp):
self._dashpush = dp
'Set the (*x*, *y*) position of the :class:`TextWithDash`. ACCEPTS: (x, y)'
def set_position(self, xy):
self.set_x(xy[0]) self.set_y(xy[1])
'Set the *x* position of the :class:`TextWithDash`. ACCEPTS: float'
def set_x(self, x):
self._dashx = float(x)
'Set the *y* position of the :class:`TextWithDash`. ACCEPTS: float'
def set_y(self, y):
self._dashy = float(y)
'Set the :class:`matplotlib.transforms.Transform` instance used by this artist. ACCEPTS: a :class:`matplotlib.transforms.Transform` instance'
def set_transform(self, t):
Text.set_transform(self, t) self.dashline.set_transform(t)
'return the figure instance the artist belongs to'
def get_figure(self):
return self.figure
'Set the figure instance the artist belong to. ACCEPTS: a :class:`matplotlib.figure.Figure` instance'
def set_figure(self, fig):
Text.set_figure(self, fig) self.dashline.set_figure(fig)
'Annotate the *x*, *y* point *xy* with text *s* at *x*, *y* location *xytext*. (If *xytext* = *None*, defaults to *xy*, and if *textcoords* = *None*, defaults to *xycoords*). *arrowprops*, if not *None*, is a dictionary of line properties (see :class:`matplotlib.lines.Line2D`) for the arrow that connects annotation to the point. If the dictionary has a key *arrowstyle*, a FancyArrowPatch instance is created with the given dictionary and is drawn. Otherwise, a YAArow patch instance is created and drawn. Valid keys for YAArow are Key Description width the width of the arrow in points frac the fraction of the arrow length occupied by the head headwidth the width of the base of the arrow head in points shrink oftentimes it is convenient to have the arrowtip and base a bit away from the text and point being annotated. If *d* is the distance between the text and annotated point, shrink will shorten the arrow so the tip and base are shink percent of the distance *d* away from the endpoints. ie, ``shrink=0.05 is 5%%`` ? any key for :class:`matplotlib.patches.polygon` Valid keys for FancyArrowPatch are Key Description arrowstyle the arrow style connectionstyle the connection style relpos default is (0.5, 0.5) patchA default is bounding box of the text patchB default is None shrinkA default is 2 points shrinkB default is 2 points mutation_scale default is text size (in points) mutation_aspect default is 1. ? any key for :class:`matplotlib.patches.PathPatch` *xycoords* and *textcoords* are strings that indicate the coordinates of *xy* and *xytext*. Property Description \'figure points\' points from the lower left corner of the figure \'figure pixels\' pixels from the lower left corner of the figure \'figure fraction\' 0,0 is lower left of figure and 1,1 is upper, right \'axes points\' points from lower left corner of axes \'axes pixels\' pixels from lower left corner of axes \'axes fraction\' 0,1 is lower left of axes and 1,1 is upper right \'data\' use the coordinate system of the object being annotated (default) \'offset points\' Specify an offset (in points) from the *xy* value \'polar\' you can specify *theta*, *r* for the annotation, even in cartesian plots. Note that if you are using a polar axes, you do not need to specify polar for the coordinate system since that is the native "data" coordinate system. If a \'points\' or \'pixels\' option is specified, values will be added to the bottom-left and if negative, values will be subtracted from the top-right. Eg:: # 10 points to the right of the left border of the axes and # 5 points below the top border xy=(10,-5), xycoords=\'axes points\' Additional kwargs are Text properties: %(Text)s'
def __init__(self, s, xy, xytext=None, xycoords='data', textcoords=None, arrowprops=None, **kwargs):
if (xytext is None): xytext = xy if (textcoords is None): textcoords = xycoords (x, y) = self.xytext = xytext Text.__init__(self, x, y, s, **kwargs) self.xy = xy self.xycoords = xycoords self.textcoords = textcoords self.arrowprops = arrowprops self.arrow = None if (arrowprops and arrowprops.has_key('arrowstyle')): self._arrow_relpos = arrowprops.pop('relpos', (0.5, 0.5)) self.arrow_patch = FancyArrowPatch((0, 0), (1, 1), **arrowprops) else: self.arrow_patch = None
'Draw the :class:`Annotation` object to the given *renderer*.'
def draw(self, renderer):
self.update_positions(renderer) self.update_bbox_position_size(renderer) if (self.arrow is not None): if ((self.arrow.figure is None) and (self.figure is not None)): self.arrow.figure = self.figure self.arrow.draw(renderer) if (self.arrow_patch is not None): if ((self.arrow_patch.figure is None) and (self.figure is not None)): self.arrow_patch.figure = self.figure self.arrow_patch.draw(renderer) Text.draw(self, renderer)
'reserve the lock for o'
def __call__(self, o):
if (not self.available(o)): raise ValueError('already locked') self._owner = o
'release the lock'
def release(self, o):
if (not self.available(o)): raise ValueError('you do not own this lock') self._owner = None
'drawing is available to o'
def available(self, o):
return ((not self.locked()) or self.isowner(o))
'o owns the lock'
def isowner(self, o):
return (self._owner is o)
'the lock is held'
def locked(self):
return (self._owner is not None)
'ax is the Axes instance the button will be placed into label is a string which is the button text image if not None, is an image to place in the button -- can be any legal arg to imshow (numpy array, matplotlib Image instance, or PIL image) color is the color of the button when not activated hovercolor is the color of the button when the mouse is over it'
def __init__(self, ax, label, image=None, color='0.85', hovercolor='0.95'):
if (image is not None): ax.imshow(image) self.label = ax.text(0.5, 0.5, label, verticalalignment='center', horizontalalignment='center', transform=ax.transAxes) self.cnt = 0 self.observers = {} self.ax = ax ax.figure.canvas.mpl_connect('button_press_event', self._click) ax.figure.canvas.mpl_connect('motion_notify_event', self._motion) ax.set_navigate(False) ax.set_axis_bgcolor(color) ax.set_xticks([]) ax.set_yticks([]) self.color = color self.hovercolor = hovercolor self._lastcolor = color
'When the button is clicked, call this func with event A connection id is returned which can be used to disconnect'
def on_clicked(self, func):
cid = self.cnt self.observers[cid] = func self.cnt += 1 return cid
'remove the observer with connection id cid'
def disconnect(self, cid):
try: del self.observers[cid] except KeyError: pass
'Create a slider from valmin to valmax in axes ax; valinit - the slider initial position label - the slider label valfmt - used to format the slider value closedmin and closedmax - indicate whether the slider interval is closed slidermin and slidermax - be used to contrain the value of this slider to the values of other sliders. additional kwargs are passed on to self.poly which is the matplotlib.patches.Rectangle which draws the slider. See the matplotlib.patches.Rectangle documentation for legal property names (eg facecolor, edgecolor, alpha, ...)'
def __init__(self, ax, label, valmin, valmax, valinit=0.5, valfmt='%1.2f', closedmin=True, closedmax=True, slidermin=None, slidermax=None, dragging=True, **kwargs):
self.ax = ax self.valmin = valmin self.valmax = valmax self.val = valinit self.valinit = valinit self.poly = ax.axvspan(valmin, valinit, 0, 1, **kwargs) self.vline = ax.axvline(valinit, 0, 1, color='r', lw=1) self.valfmt = valfmt ax.set_yticks([]) ax.set_xlim((valmin, valmax)) ax.set_xticks([]) ax.set_navigate(False) ax.figure.canvas.mpl_connect('button_press_event', self._update) if dragging: ax.figure.canvas.mpl_connect('motion_notify_event', self._update) self.label = ax.text((-0.02), 0.5, label, transform=ax.transAxes, verticalalignment='center', horizontalalignment='right') self.valtext = ax.text(1.02, 0.5, (valfmt % valinit), transform=ax.transAxes, verticalalignment='center', horizontalalignment='left') self.cnt = 0 self.observers = {} self.closedmin = closedmin self.closedmax = closedmax self.slidermin = slidermin self.slidermax = slidermax
'update the slider position'
def _update(self, event):
if (event.button != 1): return if (event.inaxes != self.ax): return val = event.xdata if ((not self.closedmin) and (val <= self.valmin)): return if ((not self.closedmax) and (val >= self.valmax)): return if (self.slidermin is not None): if (val <= self.slidermin.val): return if (self.slidermax is not None): if (val >= self.slidermax.val): return self.set_val(val)
'When the slider valud is changed, call this func with the new slider position A connection id is returned which can be used to disconnect'
def on_changed(self, func):
cid = self.cnt self.observers[cid] = func self.cnt += 1 return cid
'remove the observer with connection id cid'
def disconnect(self, cid):
try: del self.observers[cid] except KeyError: pass
'reset the slider to the initial value if needed'
def reset(self):
if (self.val != self.valinit): self.set_val(self.valinit)
'Add check buttons to axes.Axes instance ax labels is a len(buttons) list of labels as strings actives is a len(buttons) list of booleans indicating whether the button is active'
def __init__(self, ax, labels, actives):
ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) if (len(labels) > 1): dy = (1.0 / (len(labels) + 1)) ys = np.linspace((1 - dy), dy, len(labels)) else: dy = 0.25 ys = [0.5] cnt = 0 axcolor = ax.get_axis_bgcolor() self.labels = [] self.lines = [] self.rectangles = [] lineparams = {'color': 'k', 'linewidth': 1.25, 'transform': ax.transAxes, 'solid_capstyle': 'butt'} for (y, label) in zip(ys, labels): t = ax.text(0.25, y, label, transform=ax.transAxes, horizontalalignment='left', verticalalignment='center') (w, h) = ((dy / 2.0), (dy / 2.0)) (x, y) = (0.05, (y - (h / 2.0))) p = Rectangle(xy=(x, y), width=w, height=h, facecolor=axcolor, transform=ax.transAxes) l1 = Line2D([x, (x + w)], [(y + h), y], **lineparams) l2 = Line2D([x, (x + w)], [y, (y + h)], **lineparams) l1.set_visible(actives[cnt]) l2.set_visible(actives[cnt]) self.labels.append(t) self.rectangles.append(p) self.lines.append((l1, l2)) ax.add_patch(p) ax.add_line(l1) ax.add_line(l2) cnt += 1 ax.figure.canvas.mpl_connect('button_press_event', self._clicked) self.ax = ax self.cnt = 0 self.observers = {}
'When the button is clicked, call this func with button label A connection id is returned which can be used to disconnect'
def on_clicked(self, func):
cid = self.cnt self.observers[cid] = func self.cnt += 1 return cid
'remove the observer with connection id cid'
def disconnect(self, cid):
try: del self.observers[cid] except KeyError: pass
'Add radio buttons to axes.Axes instance ax labels is a len(buttons) list of labels as strings active is the index into labels for the button that is active activecolor is the color of the button when clicked'
def __init__(self, ax, labels, active=0, activecolor='blue'):
self.activecolor = activecolor ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) dy = (1.0 / (len(labels) + 1)) ys = np.linspace((1 - dy), dy, len(labels)) cnt = 0 axcolor = ax.get_axis_bgcolor() self.labels = [] self.circles = [] for (y, label) in zip(ys, labels): t = ax.text(0.25, y, label, transform=ax.transAxes, horizontalalignment='left', verticalalignment='center') if (cnt == active): facecolor = activecolor else: facecolor = axcolor p = Circle(xy=(0.15, y), radius=0.05, facecolor=facecolor, transform=ax.transAxes) self.labels.append(t) self.circles.append(p) ax.add_patch(p) cnt += 1 ax.figure.canvas.mpl_connect('button_press_event', self._clicked) self.ax = ax self.cnt = 0 self.observers = {}
'When the button is clicked, call this func with button label A connection id is returned which can be used to disconnect'
def on_clicked(self, func):
cid = self.cnt self.observers[cid] = func self.cnt += 1 return cid
'remove the observer with connection id cid'
def disconnect(self, cid):
try: del self.observers[cid] except KeyError: pass
'targetfig is the figure to adjust toolfig is the figure to embed the the subplot tool into. If None, a default pylab figure will be created. If you are using this from the GUI'
def __init__(self, targetfig, toolfig):
self.targetfig = targetfig toolfig.subplots_adjust(left=0.2, right=0.9) class toolbarfmt: def __init__(self, slider): self.slider = slider def __call__(self, x, y): fmt = ('%s=%s' % (self.slider.label.get_text(), self.slider.valfmt)) return (fmt % x) self.axleft = toolfig.add_subplot(711) self.axleft.set_title('Click on slider to adjust subplot param') self.axleft.set_navigate(False) self.sliderleft = Slider(self.axleft, 'left', 0, 1, targetfig.subplotpars.left, closedmax=False) self.sliderleft.on_changed(self.funcleft) self.axbottom = toolfig.add_subplot(712) self.axbottom.set_navigate(False) self.sliderbottom = Slider(self.axbottom, 'bottom', 0, 1, targetfig.subplotpars.bottom, closedmax=False) self.sliderbottom.on_changed(self.funcbottom) self.axright = toolfig.add_subplot(713) self.axright.set_navigate(False) self.sliderright = Slider(self.axright, 'right', 0, 1, targetfig.subplotpars.right, closedmin=False) self.sliderright.on_changed(self.funcright) self.axtop = toolfig.add_subplot(714) self.axtop.set_navigate(False) self.slidertop = Slider(self.axtop, 'top', 0, 1, targetfig.subplotpars.top, closedmin=False) self.slidertop.on_changed(self.functop) self.axwspace = toolfig.add_subplot(715) self.axwspace.set_navigate(False) self.sliderwspace = Slider(self.axwspace, 'wspace', 0, 1, targetfig.subplotpars.wspace, closedmax=False) self.sliderwspace.on_changed(self.funcwspace) self.axhspace = toolfig.add_subplot(716) self.axhspace.set_navigate(False) self.sliderhspace = Slider(self.axhspace, 'hspace', 0, 1, targetfig.subplotpars.hspace, closedmax=False) self.sliderhspace.on_changed(self.funchspace) self.sliderleft.slidermax = self.sliderright self.sliderright.slidermin = self.sliderleft self.sliderbottom.slidermax = self.slidertop self.slidertop.slidermin = self.sliderbottom bax = toolfig.add_axes([0.8, 0.05, 0.15, 0.075]) self.buttonreset = Button(bax, 'Reset') sliders = (self.sliderleft, self.sliderbottom, self.sliderright, self.slidertop, self.sliderwspace, self.sliderhspace) def func(event): thisdrawon = self.drawon self.drawon = False bs = [] for slider in sliders: bs.append(slider.drawon) slider.drawon = False for slider in sliders: slider.reset() for (slider, b) in zip(sliders, bs): slider.drawon = b self.drawon = thisdrawon if self.drawon: toolfig.canvas.draw() self.targetfig.canvas.draw() validate = toolfig.subplotpars.validate toolfig.subplotpars.validate = False self.buttonreset.on_clicked(func) toolfig.subplotpars.validate = validate
'Add a cursor to ax. If useblit=True, use the backend dependent blitting features for faster updates (GTKAgg only now). lineprops is a dictionary of line properties. See examples/widgets/cursor.py.'
def __init__(self, ax, useblit=False, **lineprops):
self.ax = ax self.canvas = ax.figure.canvas self.canvas.mpl_connect('motion_notify_event', self.onmove) self.canvas.mpl_connect('draw_event', self.clear) self.visible = True self.horizOn = True self.vertOn = True self.useblit = useblit self.lineh = ax.axhline(ax.get_ybound()[0], visible=False, **lineprops) self.linev = ax.axvline(ax.get_xbound()[0], visible=False, **lineprops) self.background = None self.needclear = False
'clear the cursor'
def clear(self, event):
if self.useblit: self.background = self.canvas.copy_from_bbox(self.ax.bbox) self.linev.set_visible(False) self.lineh.set_visible(False)
'on mouse motion draw the cursor if visible'
def onmove(self, event):
if (event.inaxes != self.ax): self.linev.set_visible(False) self.lineh.set_visible(False) if self.needclear: self.canvas.draw() self.needclear = False return self.needclear = True if (not self.visible): return self.linev.set_xdata((event.xdata, event.xdata)) self.lineh.set_ydata((event.ydata, event.ydata)) self.linev.set_visible((self.visible and self.vertOn)) self.lineh.set_visible((self.visible and self.horizOn)) self._update()
'clear the cursor'
def clear(self, event):
if self.useblit: self.background = self.canvas.copy_from_bbox(self.canvas.figure.bbox) for line in self.lines: line.set_visible(False)
'Create a span selector in ax. When a selection is made, clear the span and call onselect with onselect(vmin, vmax) and clear the span. direction must be \'horizontal\' or \'vertical\' If minspan is not None, ignore events smaller than minspan The span rect is drawn with rectprops; default rectprops = dict(facecolor=\'red\', alpha=0.5) set the visible attribute to False if you want to turn off the functionality of the span selector'
def __init__(self, ax, onselect, direction, minspan=None, useblit=False, rectprops=None, onmove_callback=None):
if (rectprops is None): rectprops = dict(facecolor='red', alpha=0.5) assert (direction in ['horizontal', 'vertical']), 'Must choose horizontal or vertical for direction' self.direction = direction self.ax = None self.canvas = None self.visible = True self.cids = [] self.rect = None self.background = None self.pressv = None self.rectprops = rectprops self.onselect = onselect self.onmove_callback = onmove_callback self.useblit = useblit self.minspan = minspan self.buttonDown = False self.prev = (0, 0) self.new_axes(ax)
'force an update of the background'
def update_background(self, event):
if self.useblit: self.background = self.canvas.copy_from_bbox(self.ax.bbox)
'return True if event should be ignored'
def ignore(self, event):
return ((event.inaxes != self.ax) or (not self.visible) or (event.button != 1))
'on button press event'
def press(self, event):
if self.ignore(event): return self.buttonDown = True self.rect.set_visible(self.visible) if (self.direction == 'horizontal'): self.pressv = event.xdata else: self.pressv = event.ydata return False
'on button release event'
def release(self, event):
if ((self.pressv is None) or (self.ignore(event) and (not self.buttonDown))): return self.buttonDown = False self.rect.set_visible(False) self.canvas.draw() vmin = self.pressv if (self.direction == 'horizontal'): vmax = (event.xdata or self.prev[0]) else: vmax = (event.ydata or self.prev[1]) if (vmin > vmax): (vmin, vmax) = (vmax, vmin) span = (vmax - vmin) if ((self.minspan is not None) and (span < self.minspan)): return self.onselect(vmin, vmax) self.pressv = None return False
'draw using newfangled blit or oldfangled draw depending on useblit'
def update(self):
if self.useblit: if (self.background is not None): self.canvas.restore_region(self.background) self.ax.draw_artist(self.rect) self.canvas.blit(self.ax.bbox) else: self.canvas.draw_idle() return False
'on motion notify event'
def onmove(self, event):
if ((self.pressv is None) or self.ignore(event)): return (x, y) = (event.xdata, event.ydata) self.prev = (x, y) if (self.direction == 'horizontal'): v = x else: v = y (minv, maxv) = (v, self.pressv) if (minv > maxv): (minv, maxv) = (maxv, minv) if (self.direction == 'horizontal'): self.rect.set_x(minv) self.rect.set_width((maxv - minv)) else: self.rect.set_y(minv) self.rect.set_height((maxv - minv)) if (self.onmove_callback is not None): vmin = self.pressv if (self.direction == 'horizontal'): vmax = (event.xdata or self.prev[0]) else: vmax = (event.ydata or self.prev[1]) if (vmin > vmax): (vmin, vmax) = (vmax, vmin) self.onmove_callback(vmin, vmax) self.update() return False
'Create a selector in ax. When a selection is made, clear the span and call onselect with onselect(pos_1, pos_2) and clear the drawn box/line. There pos_i are arrays of length 2 containing the x- and y-coordinate. If minspanx is not None then events smaller than minspanx in x direction are ignored(it\'s the same for y). The rect is drawn with rectprops; default rectprops = dict(facecolor=\'red\', edgecolor = \'black\', alpha=0.5, fill=False) The line is drawn with lineprops; default lineprops = dict(color=\'black\', linestyle=\'-\', linewidth = 2, alpha=0.5) Use type if you want the mouse to draw a line, a box or nothing between click and actual position ny setting drawtype = \'line\', drawtype=\'box\' or drawtype = \'none\'. spancoords is one of \'data\' or \'pixels\'. If \'data\', minspanx and minspanx will be interpreted in the same coordinates as the x and ya axis, if \'pixels\', they are in pixels'
def __init__(self, ax, onselect, drawtype='box', minspanx=None, minspany=None, useblit=False, lineprops=None, rectprops=None, spancoords='data'):
self.ax = ax self.visible = True self.canvas = ax.figure.canvas self.canvas.mpl_connect('motion_notify_event', self.onmove) self.canvas.mpl_connect('button_press_event', self.press) self.canvas.mpl_connect('button_release_event', self.release) self.canvas.mpl_connect('draw_event', self.update_background) self.active = True self.to_draw = None self.background = None if (drawtype == 'none'): drawtype = 'line' self.visible = False if (drawtype == 'box'): if (rectprops is None): rectprops = dict(facecolor='white', edgecolor='black', alpha=0.5, fill=False) self.rectprops = rectprops self.to_draw = Rectangle((0, 0), 0, 1, visible=False, **self.rectprops) self.ax.add_patch(self.to_draw) if (drawtype == 'line'): if (lineprops is None): lineprops = dict(color='black', linestyle='-', linewidth=2, alpha=0.5) self.lineprops = lineprops self.to_draw = Line2D([0, 0], [0, 0], visible=False, **self.lineprops) self.ax.add_line(self.to_draw) self.onselect = onselect self.useblit = useblit self.minspanx = minspanx self.minspany = minspany assert (spancoords in ('data', 'pixels')) self.spancoords = spancoords self.drawtype = drawtype self.eventpress = None self.eventrelease = None
'force an update of the background'
def update_background(self, event):
if self.useblit: self.background = self.canvas.copy_from_bbox(self.ax.bbox)
'return True if event should be ignored'
def ignore(self, event):
if (not self.active): return True if (not self.canvas.widgetlock.available(self)): return True if (self.eventpress == None): return (event.inaxes != self.ax) return ((event.inaxes != self.ax) or (event.button != self.eventpress.button))