desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return the ticks position (left, right, both or unknown)'
def get_ticks_position(self):
majt = self.majorTicks[0] mT = self.minorTicks[0] majorRight = ((not majt.tick1On) and majt.tick2On and (not majt.label1On) and majt.label2On) minorRight = ((not mT.tick1On) and mT.tick2On and (not mT.label1On) and mT.label2On) if (majorRight and minorRight): return 'right' majorLeft = (majt.tick1On and (not majt.tick2On) and majt.label1On and (not majt.label2On)) minorLeft = (mT.tick1On and (not mT.tick2On) and mT.label1On and (not mT.label2On)) if (majorLeft and minorLeft): return 'left' majorDefault = (majt.tick1On and majt.tick2On and majt.label1On and (not majt.label2On)) minorDefault = (mT.tick1On and mT.tick2On and mT.label1On and (not mT.label2On)) if (majorDefault and minorDefault): return 'default' return 'unknown'
'return the Interval instance for this axis view limits'
def get_view_interval(self):
return self.axes.viewLim.intervaly
'return the Interval instance for this axis data limits'
def get_data_interval(self):
return self.axes.dataLim.intervaly
'return the Interval instance for this axis data limits'
def set_data_interval(self, vmin, vmax, ignore=False):
if ignore: self.axes.dataLim.intervaly = (vmin, vmax) else: (Vmin, Vmax) = self.get_data_interval() self.axes.dataLim.intervaly = (min(vmin, Vmin), max(vmax, Vmax))
'Create a :class:`~matplotlib.lines.Line2D` instance with *x* and *y* data in sequences *xdata*, *ydata*. The kwargs are :class:`~matplotlib.lines.Line2D` properties: %(Line2D)s See :meth:`set_linestyle` for a decription of the line styles, :meth:`set_marker` for a description of the markers, and :meth:`set_drawstyle` for a description of the draw styles.'
def __init__(self, xdata, ydata, linewidth=None, linestyle=None, color=None, marker=None, markersize=None, markeredgewidth=None, markeredgecolor=None, markerfacecolor=None, antialiased=None, dash_capstyle=None, solid_capstyle=None, dash_joinstyle=None, solid_joinstyle=None, pickradius=5, drawstyle=None, **kwargs):
Artist.__init__(self) if (not iterable(xdata)): raise RuntimeError('xdata must be a sequence') if (not iterable(ydata)): raise RuntimeError('ydata must be a sequence') if (linewidth is None): linewidth = rcParams['lines.linewidth'] if (linestyle is None): linestyle = rcParams['lines.linestyle'] if (marker is None): marker = rcParams['lines.marker'] if (color is None): color = rcParams['lines.color'] if (markersize is None): markersize = rcParams['lines.markersize'] if (antialiased is None): antialiased = rcParams['lines.antialiased'] if (dash_capstyle is None): dash_capstyle = rcParams['lines.dash_capstyle'] if (dash_joinstyle is None): dash_joinstyle = rcParams['lines.dash_joinstyle'] if (solid_capstyle is None): solid_capstyle = rcParams['lines.solid_capstyle'] if (solid_joinstyle is None): solid_joinstyle = rcParams['lines.solid_joinstyle'] if (drawstyle is None): drawstyle = 'default' self.set_dash_capstyle(dash_capstyle) self.set_dash_joinstyle(dash_joinstyle) self.set_solid_capstyle(solid_capstyle) self.set_solid_joinstyle(solid_joinstyle) self.set_linestyle(linestyle) self.set_drawstyle(drawstyle) self.set_linewidth(linewidth) self.set_color(color) self.set_marker(marker) self.set_antialiased(antialiased) self.set_markersize(markersize) self._dashSeq = None self.set_markerfacecolor(markerfacecolor) self.set_markeredgecolor(markeredgecolor) self.set_markeredgewidth(markeredgewidth) self._point_size_reduction = 0.5 self.verticalOffset = None self.update(kwargs) self.pickradius = pickradius if is_numlike(self._picker): self.pickradius = self._picker self._xorig = np.asarray([]) self._yorig = np.asarray([]) self._invalid = True self.set_data(xdata, ydata)
'Test whether the mouse event occurred on the line. The pick radius determines the precision of the location test (usually within five points of the value). Use :meth:`~matplotlib.lines.Line2D.get_pickradius` or :meth:`~matplotlib.lines.Line2D.set_pickradius` to view or modify it. Returns *True* if any values are within the radius along with ``{\'ind\': pointlist}``, where *pointlist* is the set of points within the radius. TODO: sort returned indices by distance'
def contains(self, mouseevent):
if callable(self._contains): return self._contains(self, mouseevent) if (not is_numlike(self.pickradius)): raise ValueError, 'pick radius should be a distance' if self._invalid: self.recache() if (len(self._xy) == 0): return (False, {}) (path, affine) = self._transformed_path.get_transformed_path_and_affine() path = affine.transform_path(path) xy = path.vertices xt = xy[:, 0] yt = xy[:, 1] if (self.figure == None): warning.warn('no figure set when check if mouse is on line') pixels = self.pickradius else: pixels = ((self.figure.dpi / 72.0) * self.pickradius) if (self._linestyle in ['None', None]): d = (((xt - mouseevent.x) ** 2) + ((yt - mouseevent.y) ** 2)) (ind,) = np.nonzero(np.less_equal(d, (pixels ** 2))) else: ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels) if (False and (self._label != u'')): print 'Checking line', self._label, 'at', mouseevent.x, mouseevent.y print 'xt', xt print 'yt', yt print 'ind', ind return ((len(ind) > 0), dict(ind=ind))
'return the pick radius used for containment tests'
def get_pickradius(self):
return self.pickradius
'Sets the pick radius used for containment tests ACCEPTS: float distance in points'
def setpickradius(self, d):
self.pickradius = d
'Sets the event picker details for the line. ACCEPTS: float distance in points or callable pick function ``fn(artist, event)``'
def set_picker(self, p):
if callable(p): self._contains = p else: self.pickradius = p self._picker = p
'Set the x and y data ACCEPTS: 2D array'
def set_data(self, *args):
if (len(args) == 1): (x, y) = args[0] else: (x, y) = args not_masked = 0 if (not ma.isMaskedArray(x)): x = np.asarray(x) not_masked += 1 if (not ma.isMaskedArray(y)): y = np.asarray(y) not_masked += 1 if ((not_masked < 2) or ((x is not self._xorig) and ((x.shape != self._xorig.shape) or np.any((x != self._xorig)))) or ((y is not self._yorig) and ((y.shape != self._yorig.shape) or np.any((y != self._yorig))))): self._xorig = x self._yorig = y self._invalid = True
'set the Transformation instance used by this artist ACCEPTS: a :class:`matplotlib.transforms.Transform` instance'
def set_transform(self, t):
Artist.set_transform(self, t) self._invalid = True
'return true if x is sorted'
def _is_sorted(self, x):
if (len(x) < 2): return 1 return np.alltrue(((x[1:] - x[0:(-1)]) >= 0))
'Return the xdata, ydata. If *orig* is *True*, return the original data'
def get_data(self, orig=True):
return (self.get_xdata(orig=orig), self.get_ydata(orig=orig))
'Return the xdata. If *orig* is *True*, return the original data, else the processed data.'
def get_xdata(self, orig=True):
if orig: return self._xorig if self._invalid: self.recache() return self._x
'Return the ydata. If *orig* is *True*, return the original data, else the processed data.'
def get_ydata(self, orig=True):
if orig: return self._yorig if self._invalid: self.recache() return self._y
'Return the :class:`~matplotlib.path.Path` object associated with this line.'
def get_path(self):
if self._invalid: self.recache() return self._path
'Return the *xy* data as a Nx2 numpy array.'
def get_xydata(self):
if self._invalid: self.recache() return self._xy
'True if line should be drawin with antialiased rendering ACCEPTS: [True | False]'
def set_antialiased(self, b):
self._antialiased = b
'Set the color of the line ACCEPTS: any matplotlib color'
def set_color(self, color):
self._color = color
'Set the drawstyle of the plot \'default\' connects the points with lines. The steps variants produce step-plots. \'steps\' is equivalent to \'steps-pre\' and is maintained for backward-compatibility. ACCEPTS: [ \'default\' | \'steps\' | \'steps-pre\' | \'steps-mid\' | \'steps-post\' ]'
def set_drawstyle(self, drawstyle):
self._drawstyle = drawstyle
'Set the line width in points ACCEPTS: float value in points'
def set_linewidth(self, w):
self._linewidth = w
'Set the linestyle of the line (also accepts drawstyles) linestyle description \'-\' solid \'--\' dashed \'-.\' dash_dot \':\' dotted \'None\' draw nothing \' \' draw nothing \'\' draw nothing \'steps\' is equivalent to \'steps-pre\' and is maintained for backward-compatibility. .. seealso:: :meth:`set_drawstyle` ACCEPTS: [ \'-\' | \'--\' | \'-.\' | \':\' | \'None\' | \' \' | \'\' ] and any drawstyle in combination with a linestyle, e.g. \'steps--\'.'
def set_linestyle(self, linestyle):
for ds in flatten([k.keys() for k in (self._drawStyles_l, self._drawStyles_s)], is_string_like): if linestyle.startswith(ds): self.set_drawstyle(ds) if (len(linestyle) > len(ds)): linestyle = linestyle[len(ds):] else: linestyle = '-' if (linestyle not in self._lineStyles): if (linestyle in ls_mapper): linestyle = ls_mapper[linestyle] else: verbose.report(('Unrecognized line style %s, %s' % (linestyle, type(linestyle)))) if (linestyle in [' ', '']): linestyle = 'None' self._linestyle = linestyle
'Set the line marker marker description \'.\' point \',\' pixel \'o\' circle \'v\' triangle_down \'^\' triangle_up \'<\' triangle_left \'>\' triangle_right \'1\' tri_down \'2\' tri_up \'3\' tri_left \'4\' tri_right \'s\' square \'p\' pentagon \'*\' star \'h\' hexagon1 \'H\' hexagon2 \'+\' plus \'x\' x \'D\' diamond \'d\' thin_diamond \'|\' vline \'_\' hline TICKLEFT tickleft TICKRIGHT tickright TICKUP tickup TICKDOWN tickdown CARETLEFT caretleft CARETRIGHT caretright CARETUP caretup CARETDOWN caretdown \'None\' nothing \' \' nothing \'\' nothing ACCEPTS: [ \'+\' | \'*\' | \',\' | \'.\' | \'1\' | \'2\' | \'3\' | \'4\' | \'<\' | \'>\' | \'D\' | \'H\' | \'^\' | \'_\' | \'d\' | \'h\' | \'o\' | \'p\' | \'s\' | \'v\' | \'x\' | \'|\' | TICKUP | TICKDOWN | TICKLEFT | TICKRIGHT | \'None\' | \' \' | \'\' ]'
def set_marker(self, marker):
if (marker not in self._markers): verbose.report(('Unrecognized marker style %s, %s' % (marker, type(marker)))) if (marker in [' ', '']): marker = 'None' self._marker = marker self._markerFunc = self._markers[marker]
'Set the marker edge color ACCEPTS: any matplotlib color'
def set_markeredgecolor(self, ec):
if (ec is None): ec = 'auto' self._markeredgecolor = ec
'Set the marker edge width in points ACCEPTS: float value in points'
def set_markeredgewidth(self, ew):
if (ew is None): ew = rcParams['lines.markeredgewidth'] self._markeredgewidth = ew
'Set the marker face color ACCEPTS: any matplotlib color'
def set_markerfacecolor(self, fc):
if (fc is None): fc = 'auto' self._markerfacecolor = fc
'Set the marker size in points ACCEPTS: float'
def set_markersize(self, sz):
self._markersize = sz
'Set the data np.array for x ACCEPTS: 1D array'
def set_xdata(self, x):
x = np.asarray(x) self.set_data(x, self._yorig)
'Set the data np.array for y ACCEPTS: 1D array'
def set_ydata(self, y):
y = np.asarray(y) self.set_data(self._xorig, y)
'Set the dash sequence, sequence of dashes with on off ink in points. If seq is empty or if seq = (None, None), the linestyle will be set to solid. ACCEPTS: sequence of on/off ink in points'
def set_dashes(self, seq):
if ((seq == (None, None)) or (len(seq) == 0)): self.set_linestyle('-') else: self.set_linestyle('--') self._dashSeq = seq
'copy properties from other to self'
def update_from(self, other):
Artist.update_from(self, other) self._linestyle = other._linestyle self._linewidth = other._linewidth self._color = other._color self._markersize = other._markersize self._markerfacecolor = other._markerfacecolor self._markeredgecolor = other._markeredgecolor self._markeredgewidth = other._markeredgewidth self._dashSeq = other._dashSeq self._dashcapstyle = other._dashcapstyle self._dashjoinstyle = other._dashjoinstyle self._solidcapstyle = other._solidcapstyle self._solidjoinstyle = other._solidjoinstyle self._linestyle = other._linestyle self._marker = other._marker self._drawstyle = other._drawstyle
'alias for set_antialiased'
def set_aa(self, val):
self.set_antialiased(val)
'alias for set_color'
def set_c(self, val):
self.set_color(val)
'alias for set_linestyle'
def set_ls(self, val):
self.set_linestyle(val)
'alias for set_linewidth'
def set_lw(self, val):
self.set_linewidth(val)
'alias for set_markeredgecolor'
def set_mec(self, val):
self.set_markeredgecolor(val)
'alias for set_markeredgewidth'
def set_mew(self, val):
self.set_markeredgewidth(val)
'alias for set_markerfacecolor'
def set_mfc(self, val):
self.set_markerfacecolor(val)
'alias for set_markersize'
def set_ms(self, val):
self.set_markersize(val)
'alias for get_antialiased'
def get_aa(self):
return self.get_antialiased()
'alias for get_color'
def get_c(self):
return self.get_color()
'alias for get_linestyle'
def get_ls(self):
return self.get_linestyle()
'alias for get_linewidth'
def get_lw(self):
return self.get_linewidth()
'alias for get_markeredgecolor'
def get_mec(self):
return self.get_markeredgecolor()
'alias for get_markeredgewidth'
def get_mew(self):
return self.get_markeredgewidth()
'alias for get_markerfacecolor'
def get_mfc(self):
return self.get_markerfacecolor()
'alias for get_markersize'
def get_ms(self):
return self.get_markersize()
'Set the join style for dashed linestyles ACCEPTS: [\'miter\' | \'round\' | \'bevel\']'
def set_dash_joinstyle(self, s):
s = s.lower() if (s not in self.validJoin): raise ValueError((('set_dash_joinstyle passed "%s";\n' % (s,)) + ('valid joinstyles are %s' % (self.validJoin,)))) self._dashjoinstyle = s
'Set the join style for solid linestyles ACCEPTS: [\'miter\' | \'round\' | \'bevel\']'
def set_solid_joinstyle(self, s):
s = s.lower() if (s not in self.validJoin): raise ValueError((('set_solid_joinstyle passed "%s";\n' % (s,)) + ('valid joinstyles are %s' % (self.validJoin,)))) self._solidjoinstyle = s
'Get the join style for dashed linestyles'
def get_dash_joinstyle(self):
return self._dashjoinstyle
'Get the join style for solid linestyles'
def get_solid_joinstyle(self):
return self._solidjoinstyle
'Set the cap style for dashed linestyles ACCEPTS: [\'butt\' | \'round\' | \'projecting\']'
def set_dash_capstyle(self, s):
s = s.lower() if (s not in self.validCap): raise ValueError((('set_dash_capstyle passed "%s";\n' % (s,)) + ('valid capstyles are %s' % (self.validCap,)))) self._dashcapstyle = s
'Set the cap style for solid linestyles ACCEPTS: [\'butt\' | \'round\' | \'projecting\']'
def set_solid_capstyle(self, s):
s = s.lower() if (s not in self.validCap): raise ValueError((('set_solid_capstyle passed "%s";\n' % (s,)) + ('valid capstyles are %s' % (self.validCap,)))) self._solidcapstyle = s
'Get the cap style for dashed linestyles'
def get_dash_capstyle(self):
return self._dashcapstyle
'Get the cap style for solid linestyles'
def get_solid_capstyle(self):
return self._solidcapstyle
'return True if line is dashstyle'
def is_dashed(self):
return (self._linestyle in ('--', '-.', ':'))
'Initialize the class with a :class:`matplotlib.lines.Line2D` instance. The line should already be added to some :class:`matplotlib.axes.Axes` instance and should have the picker property set.'
def __init__(self, line):
if (not hasattr(line, 'axes')): raise RuntimeError('You must first add the line to the Axes') if (line.get_picker() is None): raise RuntimeError('You must first set the picker property of the line') self.axes = line.axes self.line = line self.canvas = self.axes.figure.canvas self.cid = self.canvas.mpl_connect('pick_event', self.onpick) self.ind = set()
'Default "do nothing" implementation of the :meth:`process_selected` method. *ind* are the indices of the selected vertices. *xs* and *ys* are the coordinates of the selected vertices.'
def process_selected(self, ind, xs, ys):
pass
'When the line is picked, update the set of selected indicies.'
def onpick(self, event):
if (event.artist is not self.line): return for i in event.ind: if (i in self.ind): self.ind.remove(i) else: self.ind.add(i) ind = list(self.ind) ind.sort() (xdata, ydata) = self.line.get_data() self.process_selected(ind, xdata[ind], ydata[ind])
'Creates a new :class:`TransformNode`.'
def __init__(self):
self._parents = WeakKeyDictionary() self._invalid = 1
'Invalidate this :class:`TransformNode` and all of its ancestors. Should be called any time the transform changes.'
def invalidate(self):
value = ((self.is_affine and self.INVALID_AFFINE) or self.INVALID) if (self._invalid == value): return if (not len(self._parents)): self._invalid = value return stack = [self] while len(stack): root = stack.pop() if ((root._invalid != value) or root.pass_through): root._invalid = self.INVALID stack.extend(root._parents.keys())
'Set the children of the transform, to let the invalidation system know which transforms can invalidate this transform. Should be called from the constructor of any transforms that depend on other transforms.'
def set_children(self, *children):
for child in children: child._parents[self] = None
'Returns a frozen copy of this transform node. The frozen copy will not update when its children change. Useful for storing a previously known state of a transform where ``copy.deepcopy()`` might normally be used.'
def frozen(self):
return self
'Returns True if the :class:`Bbox` is the unit bounding box from (0, 0) to (1, 1).'
def is_unit(self):
return (list(self.get_points().flatten()) == [0.0, 0.0, 1.0, 1.0])
'Returns True if *x* is between or equal to :attr:`x0` and :attr:`x1`.'
def containsx(self, x):
(x0, x1) = self.intervalx return (((x0 < x1) and ((x >= x0) and (x <= x1))) or ((x >= x1) and (x <= x0)))
'Returns True if *y* is between or equal to :attr:`y0` and :attr:`y1`.'
def containsy(self, y):
(y0, y1) = self.intervaly return (((y0 < y1) and ((y >= y0) and (y <= y1))) or ((y >= y1) and (y <= y0)))
'Returns *True* if (*x*, *y*) is a coordinate inside the bounding box or on its edge.'
def contains(self, x, y):
return (self.containsx(x) and self.containsy(y))
'Returns True if this bounding box overlaps with the given bounding box *other*.'
def overlaps(self, other):
(ax1, ay1, ax2, ay2) = self._get_extents() (bx1, by1, bx2, by2) = other._get_extents() if (ax2 < ax1): (ax2, ax1) = (ax1, ax2) if (ay2 < ay1): (ay2, ay1) = (ay1, ay2) if (bx2 < bx1): (bx2, bx1) = (bx1, bx2) if (by2 < by1): (by2, by1) = (by1, by2) return (not ((bx2 < ax1) or (by2 < ay1) or (bx1 > ax2) or (by1 > ay2)))
'Returns True if *x* is between but not equal to :attr:`x0` and :attr:`x1`.'
def fully_containsx(self, x):
(x0, x1) = self.intervalx return (((x0 < x1) and ((x > x0) and (x < x1))) or ((x > x1) and (x < x0)))
'Returns True if *y* is between but not equal to :attr:`y0` and :attr:`y1`.'
def fully_containsy(self, y):
(y0, y1) = self.intervaly return (((y0 < y1) and ((x > y0) and (x < y1))) or ((x > y1) and (x < y0)))
'Returns True if (*x*, *y*) is a coordinate inside the bounding box, but not on its edge.'
def fully_contains(self, x, y):
return (self.fully_containsx(x) and self.fully_containsy(y))
'Returns True if this bounding box overlaps with the given bounding box *other*, but not on its edge alone.'
def fully_overlaps(self, other):
(ax1, ay1, ax2, ay2) = self._get_extents() (bx1, by1, bx2, by2) = other._get_extents() if (ax2 < ax1): (ax2, ax1) = (ax1, ax2) if (ay2 < ay1): (ay2, ay1) = (ay1, ay2) if (bx2 < bx1): (bx2, bx1) = (bx1, bx2) if (by2 < by1): (by2, by1) = (by1, by2) return (not ((bx2 <= ax1) or (by2 <= ay1) or (bx1 >= ax2) or (by1 >= ay2)))
'Return a new :class:`Bbox` object, statically transformed by the given transform.'
def transformed(self, transform):
return Bbox(transform.transform(self.get_points()))
'Return a new :class:`Bbox` object, statically transformed by the inverse of the given transform.'
def inverse_transformed(self, transform):
return Bbox(transform.inverted().transform(self.get_points()))
'Return a copy of the :class:`Bbox`, shifted to position *c* within a container. *c*: may be either: * a sequence (*cx*, *cy*) where *cx* and *cy* range from 0 to 1, where 0 is left or bottom and 1 is right or top * a string: - \'C\' for centered - \'S\' for bottom-center - \'SE\' for bottom-left - \'E\' for left - etc. Optional argument *container* is the box within which the :class:`Bbox` is positioned; it defaults to the initial :class:`Bbox`.'
def anchored(self, c, container=None):
if (container is None): container = self (l, b, w, h) = container.bounds if isinstance(c, str): (cx, cy) = self.coefs[c] else: (cx, cy) = c (L, B, W, H) = self.bounds return Bbox((self._points + [((l + (cx * (w - W))) - L), ((b + (cy * (h - H))) - B)]))
'Return a copy of the :class:`Bbox`, shrunk by the factor *mx* in the *x* direction and the factor *my* in the *y* direction. The lower left corner of the box remains unchanged. Normally *mx* and *my* will be less than 1, but this is not enforced.'
def shrunk(self, mx, my):
(w, h) = self.size return Bbox([self._points[0], (self._points[0] + [(mx * w), (my * h)])])
'Return a copy of the :class:`Bbox`, shrunk so that it is as large as it can be while having the desired aspect ratio, *box_aspect*. If the box coordinates are relative---that is, fractions of a larger box such as a figure---then the physical aspect ratio of that figure is specified with *fig_aspect*, so that *box_aspect* can also be given as a ratio of the absolute dimensions, not the relative dimensions.'
def shrunk_to_aspect(self, box_aspect, container=None, fig_aspect=1.0):
assert ((box_aspect > 0) and (fig_aspect > 0)) if (container is None): container = self (w, h) = container.size H = ((w * box_aspect) / fig_aspect) if (H <= h): W = w else: W = ((h * fig_aspect) / box_aspect) H = h return Bbox([self._points[0], (self._points[0] + (W, H))])
'e.g., ``bbox.splitx(f1, f2, ...)`` Returns a list of new :class:`Bbox` objects formed by splitting the original one with vertical lines at fractional positions *f1*, *f2*, ...'
def splitx(self, *args):
boxes = [] xf = (([0] + list(args)) + [1]) (x0, y0, x1, y1) = self._get_extents() w = (x1 - x0) for (xf0, xf1) in zip(xf[:(-1)], xf[1:]): boxes.append(Bbox([[(x0 + (xf0 * w)), y0], [(x0 + (xf1 * w)), y1]])) return boxes
'e.g., ``bbox.splitx(f1, f2, ...)`` Returns a list of new :class:`Bbox` objects formed by splitting the original one with horizontal lines at fractional positions *f1*, *f2*, ...'
def splity(self, *args):
boxes = [] yf = (([0] + list(args)) + [1]) (x0, y0, x1, y1) = self._get_extents() h = (y1 - y0) for (yf0, yf1) in zip(yf[:(-1)], yf[1:]): boxes.append(Bbox([[x0, (y0 + (yf0 * h))], [x1, (y0 + (yf1 * h))]])) return boxes
'Count the number of vertices contained in the :class:`Bbox`. *vertices* is a Nx2 Numpy array.'
def count_contains(self, vertices):
if (len(vertices) == 0): return 0 vertices = np.asarray(vertices) (x0, y0, x1, y1) = self._get_extents() dx0 = np.sign((vertices[:, 0] - x0)) dy0 = np.sign((vertices[:, 1] - y0)) dx1 = np.sign((vertices[:, 0] - x1)) dy1 = np.sign((vertices[:, 1] - y1)) inside = ((abs((dx0 + dx1)) + abs((dy0 + dy1))) <= 2) return np.sum(inside)
'Count the number of bounding boxes that overlap this one. bboxes is a sequence of :class:`BboxBase` objects'
def count_overlaps(self, bboxes):
return count_bboxes_overlapping_bbox(self, bboxes)
'Return a new :class:`Bbox` which is this :class:`Bbox` expanded around its center by the given factors *sw* and *sh*.'
def expanded(self, sw, sh):
width = self.width height = self.height deltaw = (((sw * width) - width) / 2.0) deltah = (((sh * height) - height) / 2.0) a = np.array([[(- deltaw), (- deltah)], [deltaw, deltah]]) return Bbox((self._points + a))
'Return a new :class:`Bbox` that is padded on all four sides by the given value.'
def padded(self, p):
points = self._points return Bbox((points + [[(- p), (- p)], [p, p]]))
'Return a copy of the :class:`Bbox`, statically translated by *tx* and *ty*.'
def translated(self, tx, ty):
return Bbox((self._points + (tx, ty)))
'Return an array of points which are the four corners of this rectangle. For example, if this :class:`Bbox` is defined by the points (*a*, *b*) and (*c*, *d*), :meth:`corners` returns (*a*, *b*), (*a*, *d*), (*c*, *b*) and (*c*, *d*).'
def corners(self):
(l, b, r, t) = self.get_points().flatten() return np.array([[l, b], [l, t], [r, b], [r, t]])
'Return a new bounding box that bounds a rotated version of this bounding box by the given radians. The new bounding box is still aligned with the axes, of course.'
def rotated(self, radians):
corners = self.corners() corners_rotated = Affine2D().rotate(radians).transform(corners) bbox = Bbox.unit() bbox.update_from_data_xy(corners_rotated, ignore=True) return bbox
'Return a :class:`Bbox` that contains all of the given bboxes.'
def union(bboxes):
assert len(bboxes) if (len(bboxes) == 1): return bboxes[0] x0 = np.inf y0 = np.inf x1 = (- np.inf) y1 = (- np.inf) for bbox in bboxes: points = bbox.get_points() xs = points[:, 0] ys = points[:, 1] x0 = min(x0, np.min(xs)) y0 = min(y0, np.min(ys)) x1 = max(x1, np.max(xs)) y1 = max(y1, np.max(ys)) return Bbox.from_extents(x0, y0, x1, y1)
'*points*: a 2x2 numpy array of the form [[x0, y0], [x1, y1]] If you need to create a :class:`Bbox` object from another form of data, consider the static methods :meth:`unit`, :meth:`from_bounds` and :meth:`from_extents`.'
def __init__(self, points):
BboxBase.__init__(self) self._points = np.asarray(points, np.float_) self._minpos = np.array([1e-07, 1e-07]) self._ignore = True
'(staticmethod) Create a new unit :class:`Bbox` from (0, 0) to (1, 1).'
def unit():
return Bbox(Bbox._unit_values.copy())
'(staticmethod) Create a new :class:`Bbox` from *x0*, *y0*, *width* and *height*. *width* and *height* may be negative.'
def from_bounds(x0, y0, width, height):
return Bbox.from_extents(x0, y0, (x0 + width), (y0 + height))
'(staticmethod) Create a new Bbox from *left*, *bottom*, *right* and *top*. The *y*-axis increases upwards.'
def from_extents(*args):
points = np.array(args, dtype=np.float_).reshape(2, 2) return Bbox(points)
'Set whether the existing bounds of the box should be ignored by subsequent calls to :meth:`update_from_data` or :meth:`update_from_data_xy`. *value*: - When True, subsequent calls to :meth:`update_from_data` will ignore the existing bounds of the :class:`Bbox`. - When False, subsequent calls to :meth:`update_from_data` will include the existing bounds of the :class:`Bbox`.'
def ignore(self, value):
self._ignore = value
'Update the bounds of the :class:`Bbox` based on the passed in data. After updating, the bounds will have positive *width* and *height*; *x0* and *y0* will be the minimal values. *x*: a numpy array of *x*-values *y*: a numpy array of *y*-values *ignore*: - when True, ignore the existing bounds of the :class:`Bbox`. - when False, include the existing bounds of the :class:`Bbox`. - when None, use the last value passed to :meth:`ignore`.'
def update_from_data(self, x, y, ignore=None):
warnings.warn('update_from_data requires a memory copy -- please replace with update_from_data_xy') xy = np.hstack((x.reshape((len(x), 1)), y.reshape((len(y), 1)))) return self.update_from_data_xy(xy, ignore)
'Update the bounds of the :class:`Bbox` based on the passed in data. After updating, the bounds will have positive *width* and *height*; *x0* and *y0* will be the minimal values. *path*: a :class:`~matplotlib.path.Path` instance *ignore*: - when True, ignore the existing bounds of the :class:`Bbox`. - when False, include the existing bounds of the :class:`Bbox`. - when None, use the last value passed to :meth:`ignore`. *updatex*: when True, update the x values *updatey*: when True, update the y values'
def update_from_path(self, path, ignore=None, updatex=True, updatey=True):
if (ignore is None): ignore = self._ignore if (path.vertices.size == 0): return (points, minpos, changed) = update_path_extents(path, None, self._points, self._minpos, ignore) if changed: self.invalidate() if updatex: self._points[:, 0] = points[:, 0] self._minpos[0] = minpos[0] if updatey: self._points[:, 1] = points[:, 1] self._minpos[1] = minpos[1]
'Update the bounds of the :class:`Bbox` based on the passed in data. After updating, the bounds will have positive *width* and *height*; *x0* and *y0* will be the minimal values. *xy*: a numpy array of 2D points *ignore*: - when True, ignore the existing bounds of the :class:`Bbox`. - when False, include the existing bounds of the :class:`Bbox`. - when None, use the last value passed to :meth:`ignore`. *updatex*: when True, update the x values *updatey*: when True, update the y values'
def update_from_data_xy(self, xy, ignore=None, updatex=True, updatey=True):
if (len(xy) == 0): return path = Path(xy) self.update_from_path(path, ignore=ignore, updatex=updatex, updatey=updatey)
'Get the points of the bounding box directly as a numpy array of the form: [[x0, y0], [x1, y1]].'
def get_points(self):
self._invalid = 0 return self._points
'Set the points of the bounding box directly from a numpy array of the form: [[x0, y0], [x1, y1]]. No error checking is performed, as this method is mainly for internal use.'
def set_points(self, points):
if np.any((self._points != points)): self._points = points self.invalidate()
'Set this bounding box from the "frozen" bounds of another :class:`Bbox`.'
def set(self, other):
if np.any((self._points != other.get_points())): self._points = other.get_points() self.invalidate()
'*bbox*: a child :class:`Bbox` *transform*: a 2D :class:`Transform`'
def __init__(self, bbox, transform):
assert bbox.is_bbox assert isinstance(transform, Transform) assert (transform.input_dims == 2) assert (transform.output_dims == 2) BboxBase.__init__(self) self._bbox = bbox self._transform = transform self.set_children(bbox, transform) self._points = None
'Composes two transforms together such that *self* is followed by *other*.'
def __add__(self, other):
if isinstance(other, Transform): return composite_transform_factory(self, other) raise TypeError(("Can not add Transform to object of type '%s'" % type(other)))