desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'alias for set_facecolor'
def set_fc(self, color):
return self.set_facecolor(color)
'Set the patch linewidth in points ACCEPTS: float or None for default'
def set_linewidth(self, w):
if (w is None): w = mpl.rcParams['patch.linewidth'] self._linewidth = w
'alias for set_linewidth'
def set_lw(self, lw):
return self.set_linewidth(lw)
'Set the patch linestyle ACCEPTS: [\'solid\' | \'dashed\' | \'dashdot\' | \'dotted\']'
def set_linestyle(self, ls):
if (ls is None): ls = 'solid' self._linestyle = ls
'alias for set_linestyle'
def set_ls(self, ls):
return self.set_linestyle(ls)
'Set whether to fill the patch ACCEPTS: [True | False]'
def set_fill(self, b):
self.fill = b
'return whether fill is set'
def get_fill(self):
return self.fill
'Set the hatching pattern hatch can be one of:: / - diagonal hatching \ - back diagonal | - vertical - - horizontal # - crossed x - crossed diagonal Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching in that direction. CURRENT LIMITATIONS: 1. Hatching is supported in the PostScript backend only. 2. Hatching is done with solid black lines of width 0. ACCEPTS: [ \'/\' | \'\\' | \'|\' | \'-\' | \'#\' | \'x\' ]'
def set_hatch(self, h):
self._hatch = h
'Return the current hatching pattern'
def get_hatch(self):
return self._hatch
'Draw the :class:`Patch` to the given *renderer*.'
def draw(self, renderer):
if (not self.get_visible()): return gc = renderer.new_gc() if (cbook.is_string_like(self._edgecolor) and (self._edgecolor.lower() == 'none')): gc.set_linewidth(0) else: gc.set_foreground(self._edgecolor) gc.set_linewidth(self._linewidth) gc.set_linestyle(self._linestyle) gc.set_antialiased(self._antialiased) self._set_gc_clip(gc) gc.set_capstyle('projecting') gc.set_url(self._url) gc.set_snap(self._snap) if ((not self.fill) or (self._facecolor is None) or (cbook.is_string_like(self._facecolor) and (self._facecolor.lower() == 'none'))): rgbFace = None gc.set_alpha(1.0) else: (r, g, b, a) = colors.colorConverter.to_rgba(self._facecolor, self._alpha) rgbFace = (r, g, b) gc.set_alpha(a) if self._hatch: gc.set_hatch(self._hatch) path = self.get_path() transform = self.get_transform() tpath = transform.transform_path_non_affine(path) affine = transform.get_affine() renderer.draw_path(gc, tpath, affine, rgbFace)
'Return the path of this patch'
def get_path(self):
raise NotImplementedError('Derived must override')
'Create a shadow of the given *patch* offset by *ox*, *oy*. *props*, if not *None*, is a patch property update dictionary. If *None*, the shadow will have have the same color as the face, but darkened. kwargs are %(Patch)s'
def __init__(self, patch, ox, oy, props=None, **kwargs):
Patch.__init__(self) self.patch = patch self.props = props (self._ox, self._oy) = (ox, oy) self._update_transform() self._update()
'*fill* is a boolean indicating whether to fill the rectangle Valid kwargs are: %(Patch)s'
def __init__(self, xy, width, height, **kwargs):
Patch.__init__(self, **kwargs) self._x = xy[0] self._y = xy[1] self._width = width self._height = height self._rect_transform = transforms.IdentityTransform()
'Return the vertices of the rectangle'
def get_path(self):
return Path.unit_rectangle()
'NOTE: This cannot be called until after this has been added to an Axes, otherwise unit conversion will fail. This maxes it very important to call the accessor method and not directly access the transformation member variable.'
def _update_patch_transform(self):
x = self.convert_xunits(self._x) y = self.convert_yunits(self._y) width = self.convert_xunits(self._width) height = self.convert_yunits(self._height) bbox = transforms.Bbox.from_bounds(x, y, width, height) self._rect_transform = transforms.BboxTransformTo(bbox)
'Return the left coord of the rectangle'
def get_x(self):
return self._x
'Return the bottom coord of the rectangle'
def get_y(self):
return self._y
'Return the left and bottom coords of the rectangle'
def get_xy(self):
return (self._x, self._y)
'Return the width of the rectangle'
def get_width(self):
return self._width
'Return the height of the rectangle'
def get_height(self):
return self._height
'Set the left coord of the rectangle ACCEPTS: float'
def set_x(self, x):
self._x = x
'Set the bottom coord of the rectangle ACCEPTS: float'
def set_y(self, y):
self._y = y
'Set the left and bottom coords of the rectangle ACCEPTS: 2-item sequence'
def set_xy(self, xy):
(self._x, self._y) = xy
'Set the width rectangle ACCEPTS: float'
def set_width(self, w):
self._width = w
'Set the width rectangle ACCEPTS: float'
def set_height(self, h):
self._height = h
'Set the bounds of the rectangle: l,b,w,h ACCEPTS: (left, bottom, width, height)'
def set_bounds(self, *args):
if (len(args) == 0): (l, b, w, h) = args[0] else: (l, b, w, h) = args self._x = l self._y = b self._width = w self._height = h
'Constructor arguments: *xy* A length 2 tuple (*x*, *y*) of the center. *numVertices* the number of vertices. *radius* The distance from the center to each of the vertices. *orientation* rotates the polygon (in radians). Valid kwargs are: %(Patch)s'
def __init__(self, xy, numVertices, radius=5, orientation=0, **kwargs):
self._xy = xy self._numVertices = numVertices self._orientation = orientation self._radius = radius self._path = Path.unit_regular_polygon(numVertices) self._poly_transform = transforms.Affine2D() self._update_transform() Patch.__init__(self, **kwargs)
'*path* is a :class:`matplotlib.path.Path` object. Valid kwargs are: %(Patch)s .. seealso:: :class:`Patch`: For additional kwargs'
def __init__(self, path, **kwargs):
Patch.__init__(self, **kwargs) self._path = path
'*xy* is a numpy array with shape Nx2. If *closed* is *True*, the polygon will be closed so the starting and ending points are the same. Valid kwargs are: %(Patch)s .. seealso:: :class:`Patch`: For additional kwargs'
def __init__(self, xy, closed=True, **kwargs):
Patch.__init__(self, **kwargs) xy = np.asarray(xy, np.float_) self._path = Path(xy) self.set_closed(closed)
'Draw a wedge centered at *x*, *y* center with radius *r* that sweeps *theta1* to *theta2* (in degrees). If *width* is given, then a partial wedge is drawn from inner radius *r* - *width* to outer radius *r*. Valid kwargs are: %(Patch)s'
def __init__(self, center, r, theta1, theta2, width=None, **kwargs):
Patch.__init__(self, **kwargs) self.center = center (self.r, self.width) = (r, width) (self.theta1, self.theta2) = (theta1, theta2) delta = (theta2 - theta1) if (abs(((theta2 - theta1) - 360)) <= 1e-12): (theta1, theta2) = (0, 360) connector = Path.MOVETO else: connector = Path.LINETO arc = Path.arc(theta1, theta2) if (width is not None): v1 = arc.vertices v2 = ((arc.vertices[::(-1)] * float((r - width))) / r) v = np.vstack([v1, v2, v1[0, :], (0, 0)]) c = np.hstack([arc.codes, arc.codes, connector, Path.CLOSEPOLY]) c[len(arc.codes)] = connector else: v = np.vstack([arc.vertices, [(0, 0), arc.vertices[0, :], (0, 0)]]) c = np.hstack([arc.codes, [connector, connector, Path.CLOSEPOLY]]) v *= r v += np.asarray(center) self._path = Path(v, c) self._patch_transform = transforms.IdentityTransform()
'Draws an arrow, starting at (*x*, *y*), direction and length given by (*dx*, *dy*) the width of the arrow is scaled by *width*. Valid kwargs are: %(Patch)s'
def __init__(self, x, y, dx, dy, width=1.0, **kwargs):
Patch.__init__(self, **kwargs) L = (np.sqrt(((dx ** 2) + (dy ** 2))) or 1) cx = (float(dx) / L) sx = (float(dy) / L) trans1 = transforms.Affine2D().scale(L, width) trans2 = transforms.Affine2D.from_values(cx, sx, (- sx), cx, 0.0, 0.0) trans3 = transforms.Affine2D().translate(x, y) trans = ((trans1 + trans2) + trans3) self._patch_transform = trans.frozen()
'Constructor arguments *length_includes_head*: *True* if head is counted in calculating the length. *shape*: [\'full\', \'left\', \'right\'] *overhang*: distance that the arrow is swept back (0 overhang means triangular shape). *head_starts_at_zero*: If *True*, the head starts being drawn at coordinate 0 instead of ending at coordinate 0. Valid kwargs are: %(Patch)s'
def __init__(self, x, y, dx, dy, width=0.001, length_includes_head=False, head_width=None, head_length=None, shape='full', overhang=0, head_starts_at_zero=False, **kwargs):
if (head_width is None): head_width = (3 * width) if (head_length is None): head_length = (1.5 * head_width) distance = np.sqrt(((dx ** 2) + (dy ** 2))) if length_includes_head: length = distance else: length = (distance + head_length) if (not length): verts = [] else: (hw, hl, hs, lw) = (head_width, head_length, overhang, width) left_half_arrow = np.array([[0.0, 0.0], [(- hl), ((- hw) / 2.0)], [((- hl) * (1 - hs)), ((- lw) / 2.0)], [(- length), ((- lw) / 2.0)], [(- length), 0]]) if (not length_includes_head): left_half_arrow += [head_length, 0] if head_starts_at_zero: left_half_arrow += [(head_length / 2.0), 0] if (shape == 'left'): coords = left_half_arrow else: right_half_arrow = (left_half_arrow * [1, (-1)]) if (shape == 'right'): coords = right_half_arrow elif (shape == 'full'): coords = np.concatenate([left_half_arrow[:(-1)], right_half_arrow[(-2)::(-1)]]) else: raise ValueError, ('Got unknown shape: %s' % shape) cx = (float(dx) / distance) sx = (float(dy) / distance) M = np.array([[cx, sx], [(- sx), cx]]) verts = (np.dot(coords, M) + ((x + dx), (y + dy))) Polygon.__init__(self, map(tuple, verts), **kwargs)
'Constructor arguments: *xytip* (*x*, *y*) location of arrow tip *xybase* (*x*, *y*) location the arrow base mid point *figure* The :class:`~matplotlib.figure.Figure` instance (fig.dpi) *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 Valid kwargs are: %(Patch)s'
def __init__(self, figure, xytip, xybase, width=4, frac=0.1, headwidth=12, **kwargs):
self.figure = figure self.xytip = xytip self.xybase = xybase self.width = width self.frac = frac self.headwidth = headwidth Patch.__init__(self, **kwargs)
'For line segment defined by (*x1*, *y1*) and (*x2*, *y2*) return the points on the line that is perpendicular to the line and intersects (*x2*, *y2*) and the distance from (*x2*, *y2*) of the returned points is *k*.'
def getpoints(self, x1, y1, x2, y2, k):
(x1, y1, x2, y2, k) = map(float, (x1, y1, x2, y2, k)) if ((y2 - y1) == 0): return (x2, (y2 + k), x2, (y2 - k)) elif ((x2 - x1) == 0): return ((x2 + k), y2, (x2 - k), y2) m = ((y2 - y1) / (x2 - x1)) pm = ((-1.0) / m) a = 1 b = ((-2) * y2) c = ((y2 ** 2.0) - (((k ** 2.0) * (pm ** 2.0)) / (1.0 + (pm ** 2.0)))) y3a = (((- b) + math.sqrt(((b ** 2.0) - ((4 * a) * c)))) / (2.0 * a)) x3a = (((y3a - y2) / pm) + x2) y3b = (((- b) - math.sqrt(((b ** 2.0) - ((4 * a) * c)))) / (2.0 * a)) x3b = (((y3b - y2) / pm) + x2) return (x3a, y3a, x3b, y3b)
'Create a circle at *xy* = (*x*, *y*) with given *radius*. This circle is approximated by a regular polygon with *resolution* sides. For a smoother circle drawn with splines, see :class:`~matplotlib.patches.Circle`. Valid kwargs are: %(Patch)s'
def __init__(self, xy, radius=5, resolution=20, **kwargs):
RegularPolygon.__init__(self, xy, resolution, radius, orientation=0, **kwargs)
'*xy* center of ellipse *width* length of horizontal axis *height* length of vertical axis *angle* rotation in degrees (anti-clockwise) Valid kwargs are: %(Patch)s'
def __init__(self, xy, width, height, angle=0.0, **kwargs):
Patch.__init__(self, **kwargs) self.center = xy (self.width, self.height) = (width, height) self.angle = angle self._path = Path.unit_circle() self._patch_transform = transforms.IdentityTransform()
'NOTE: This cannot be called until after this has been added to an Axes, otherwise unit conversion will fail. This maxes it very important to call the accessor method and not directly access the transformation member variable.'
def _recompute_transform(self):
center = (self.convert_xunits(self.center[0]), self.convert_yunits(self.center[1])) width = self.convert_xunits(self.width) height = self.convert_yunits(self.height) self._patch_transform = transforms.Affine2D().scale((width * 0.5), (height * 0.5)).rotate_deg(self.angle).translate(*center)
'Return the vertices of the rectangle'
def get_path(self):
return self._path
'Create true circle at center *xy* = (*x*, *y*) with given *radius*. Unlike :class:`~matplotlib.patches.CirclePolygon` which is a polygonal approximation, this uses Bézier splines and is much closer to a scale-free circle. Valid kwargs are: %(Patch)s'
def __init__(self, xy, radius=5, **kwargs):
if ('resolution' in kwargs): import warnings warnings.warn('Circle is now scale free. Use CirclePolygon instead!', DeprecationWarning) kwargs.pop('resolution') self.radius = radius Ellipse.__init__(self, xy, (radius * 2), (radius * 2), **kwargs)
'The following args are supported: *xy* center of ellipse *width* length of horizontal axis *height* length of vertical axis *angle* rotation in degrees (anti-clockwise) *theta1* starting angle of the arc in degrees *theta2* ending angle of the arc in degrees If *theta1* and *theta2* are not provided, the arc will form a complete ellipse. Valid kwargs are: %(Patch)s'
def __init__(self, xy, width, height, angle=0.0, theta1=0.0, theta2=360.0, **kwargs):
fill = kwargs.pop('fill') if fill: raise ValueError('Arc objects can not be filled') kwargs['fill'] = False Ellipse.__init__(self, xy, width, height, angle, **kwargs) self.theta1 = theta1 self.theta2 = theta2
'Ellipses are normally drawn using an approximation that uses eight cubic bezier splines. The error of this approximation is 1.89818e-6, according to this unverified source: Lancaster, Don. Approximating a Circle or an Ellipse Using Four Bezier Cubic Splines. http://www.tinaja.com/glib/ellipse4.pdf There is a use case where very large ellipses must be drawn with very high accuracy, and it is too expensive to render the entire ellipse with enough segments (either splines or line segments). Therefore, in the case where either radius of the ellipse is large enough that the error of the spline approximation will be visible (greater than one pixel offset from the ideal), a different technique is used. In that case, only the visible parts of the ellipse are drawn, with each visible arc using a fixed number of spline segments (8). The algorithm proceeds as follows: 1. The points where the ellipse intersects the axes bounding box are located. (This is done be performing an inverse transformation on the axes bbox such that it is relative to the unit circle -- this makes the intersection calculation much easier than doing rotated ellipse intersection directly). This uses the "line intersecting a circle" algorithm from: Vince, John. Geometry for Computer Graphics: Formulae, Examples & Proofs. London: Springer-Verlag, 2005. 2. The angles of each of the intersection points are calculated. 3. Proceeding counterclockwise starting in the positive x-direction, each of the visible arc-segments between the pairs of vertices are drawn using the bezier arc approximation technique implemented in :meth:`matplotlib.path.Path.arc`.'
def draw(self, renderer):
if (not hasattr(self, 'axes')): raise RuntimeError('Arcs can only be used in Axes instances') self._recompute_transform() width = self.convert_xunits(self.width) height = self.convert_yunits(self.height) (width, height) = self.get_transform().transform_point((width, height)) inv_error = ((1.0 / 1.89818e-06) * 0.5) if ((width < inv_error) and (height < inv_error)): self._path = Path.arc(self.theta1, self.theta2) return Patch.draw(self, renderer) def iter_circle_intersect_on_line(x0, y0, x1, y1): dx = (x1 - x0) dy = (y1 - y0) dr2 = ((dx * dx) + (dy * dy)) D = ((x0 * y1) - (x1 * y0)) D2 = (D * D) discrim = (dr2 - D2) if (discrim == 0.0): x = ((D * dy) / dr2) y = (((- D) * dx) / dr2) (yield (x, y)) elif (discrim > 0.0): if (dy < 0.0): sign_dy = (-1.0) else: sign_dy = 1.0 sqrt_discrim = np.sqrt(discrim) for sign in (1.0, (-1.0)): x = (((D * dy) + (((sign * sign_dy) * dx) * sqrt_discrim)) / dr2) y = ((((- D) * dx) + ((sign * np.abs(dy)) * sqrt_discrim)) / dr2) (yield (x, y)) def iter_circle_intersect_on_line_seg(x0, y0, x1, y1): epsilon = 1e-09 if (x1 < x0): (x0e, x1e) = (x1, x0) else: (x0e, x1e) = (x0, x1) if (y1 < y0): (y0e, y1e) = (y1, y0) else: (y0e, y1e) = (y0, y1) x0e -= epsilon y0e -= epsilon x1e += epsilon y1e += epsilon for (x, y) in iter_circle_intersect_on_line(x0, y0, x1, y1): if ((x >= x0e) and (x <= x1e) and (y >= y0e) and (y <= y1e)): (yield (x, y)) box_path = Path.unit_rectangle() box_path_transform = (transforms.BboxTransformTo(self.axes.bbox) + self.get_transform().inverted()) box_path = box_path.transformed(box_path_transform) PI = np.pi TWOPI = (PI * 2.0) RAD2DEG = (180.0 / PI) DEG2RAD = (PI / 180.0) theta1 = self.theta1 theta2 = self.theta2 thetas = {} for (p0, p1) in zip(box_path.vertices[:(-1)], box_path.vertices[1:]): (x0, y0) = p0 (x1, y1) = p1 for (x, y) in iter_circle_intersect_on_line_seg(x0, y0, x1, y1): theta = np.arccos(x) if (y < 0): theta = (TWOPI - theta) theta *= RAD2DEG if ((theta > theta1) and (theta < theta2)): thetas[theta] = None thetas = thetas.keys() thetas.sort() thetas.append(theta2) last_theta = theta1 theta1_rad = (theta1 * DEG2RAD) inside = box_path.contains_point((np.cos(theta1_rad), np.sin(theta1_rad))) for theta in thetas: if inside: self._path = Path.arc(last_theta, theta, 8) Patch.draw(self, renderer) inside = False else: inside = True last_theta = theta
'return the instance of the subclass with the given style name.'
def __new__(self, stylename, **kw):
_list = stylename.replace(' ', '').split(',') _name = _list[0].lower() try: _cls = self._style_list[_name] except KeyError: raise ValueError(('Unknown style : %s' % stylename)) try: _args_pair = [cs.split('=') for cs in _list[1:]] _args = dict([(k, float(v)) for (k, v) in _args_pair]) except ValueError: raise ValueError(('Incorrect style argument : %s' % stylename)) _args.update(kw) return _cls(**_args)
'A class method which returns a dictionary of available styles.'
@classmethod def get_styles(klass):
return klass._style_list
'A class method which returns a string of the available styles.'
@classmethod def pprint_styles(klass):
return _pprint_styles(klass._style_list)
'initializtion.'
def __init__(self):
super(BoxStyle._Base, self).__init__()
'The transmute method is a very core of the :class:`BboxTransmuter` class and must be overriden in the subclasses. It receives the location and size of the rectangle, and the mutation_size, with which the amount of padding and etc. will be scaled. It returns a :class:`~matplotlib.path.Path` instance.'
def transmute(self, x0, y0, width, height, mutation_size):
raise NotImplementedError('Derived must override')
'Given the location and size of the box, return the path of the box around it. - *x0*, *y0*, *width*, *height* : location and size of the box - *mutation_size* : a reference scale for the mutation. - *aspect_ratio* : aspect-ration for the mutation.'
def __call__(self, x0, y0, width, height, mutation_size, aspect_ratio=1.0):
if (aspect_ratio is not None): (y0, height) = ((y0 / aspect_ratio), (height / aspect_ratio)) path = self.transmute(x0, y0, width, height, mutation_size) (vertices, codes) = (path.vertices, path.codes) vertices[:, 1] = (vertices[:, 1] * aspect_ratio) return Path(vertices, codes) else: return self.transmute(x0, y0, width, height, mutation_size)
'*pad* amount of padding'
def __init__(self, pad=0.3):
self.pad = pad super(BoxStyle.Square, self).__init__()
'*pad* amount of padding *rounding_size* rounding radius of corners. *pad* if None'
def __init__(self, pad=0.3, rounding_size=None):
self.pad = pad self.rounding_size = rounding_size super(BoxStyle.Round, self).__init__()
'*pad* amount of padding *rounding_size* rounding size of edges. *pad* if None'
def __init__(self, pad=0.3, rounding_size=None):
self.pad = pad self.rounding_size = rounding_size super(BoxStyle.Round4, self).__init__()
'*pad* amount of padding *tooth_size* size of the sawtooth. pad* if None'
def __init__(self, pad=0.3, tooth_size=None):
self.pad = pad self.tooth_size = tooth_size super(BoxStyle.Sawtooth, self).__init__()
'*pad* amount of padding *tooth_size* size of the sawtooth. pad* if None'
def __init__(self, pad=0.3, tooth_size=None):
super(BoxStyle.Roundtooth, self).__init__(pad, tooth_size)
'*xy* = lower left corner *width*, *height* *boxstyle* determines what kind of fancy box will be drawn. It can be a string of the style name with a comma separated attribute, or an instance of :class:`BoxStyle`. Following box styles are available. %(AvailableBoxstyles)s *mutation_scale* : a value with which attributes of boxstyle (e.g., pad) will be scaled. default=1. *mutation_aspect* : The height of the rectangle will be squeezed by this value before the mutation and the mutated box will be stretched by the inverse of it. default=None. Valid kwargs are: %(Patch)s'
def __init__(self, xy, width, height, boxstyle='round', bbox_transmuter=None, mutation_scale=1.0, mutation_aspect=None, **kwargs):
Patch.__init__(self, **kwargs) self._x = xy[0] self._y = xy[1] self._width = width self._height = height if (boxstyle == 'custom'): if (bbox_transmuter is None): raise ValueError('bbox_transmuter argument is needed with custom boxstyle') self._bbox_transmuter = bbox_transmuter else: self.set_boxstyle(boxstyle) self._mutation_scale = mutation_scale self._mutation_aspect = mutation_aspect
'Set the box style. *boxstyle* can be a string with boxstyle name with optional comma-separated attributes. Alternatively, the attrs can be provided as keywords:: set_boxstyle("round,pad=0.2") set_boxstyle("round", pad=0.2) Old attrs simply are forgotten. Without argument (or with *boxstyle* = None), it returns available box styles. ACCEPTS: [ %(AvailableBoxstyles)s ]'
def set_boxstyle(self, boxstyle=None, **kw):
if (boxstyle == None): return BoxStyle.pprint_styles() if isinstance(boxstyle, BoxStyle._Base): self._bbox_transmuter = boxstyle elif callable(boxstyle): self._bbox_transmuter = boxstyle else: self._bbox_transmuter = BoxStyle(boxstyle, **kw)
'Set the mutation scale. ACCEPTS: float'
def set_mutation_scale(self, scale):
self._mutation_scale = scale
'Return the mutation scale.'
def get_mutation_scale(self):
return self._mutation_scale
'Set the aspect ratio of the bbox mutation. ACCEPTS: float'
def set_mutation_aspect(self, aspect):
self._mutation_aspect = aspect
'Return the aspect ratio of the bbox mutation.'
def get_mutation_aspect(self):
return self._mutation_aspect
'Return the boxstyle object'
def get_boxstyle(self):
return self._bbox_transmuter
'Return the mutated path of the rectangle'
def get_path(self):
_path = self.get_boxstyle()(self._x, self._y, self._width, self._height, self.get_mutation_scale(), self.get_mutation_aspect()) return _path
'Return the left coord of the rectangle'
def get_x(self):
return self._x
'Return the bottom coord of the rectangle'
def get_y(self):
return self._y
'Return the width of the rectangle'
def get_width(self):
return self._width
'Return the height of the rectangle'
def get_height(self):
return self._height
'Set the left coord of the rectangle ACCEPTS: float'
def set_x(self, x):
self._x = x
'Set the bottom coord of the rectangle ACCEPTS: float'
def set_y(self, y):
self._y = y
'Set the width rectangle ACCEPTS: float'
def set_width(self, w):
self._width = w
'Set the width rectangle ACCEPTS: float'
def set_height(self, h):
self._height = h
'Set the bounds of the rectangle: l,b,w,h ACCEPTS: (left, bottom, width, height)'
def set_bounds(self, *args):
if (len(args) == 0): (l, b, w, h) = args[0] else: (l, b, w, h) = args self._x = l self._y = b self._width = w self._height = h
'Clip the path to the boundary of the patchA and patchB. The starting point of the path needed to be inside of the patchA and the end point inside the patch B. The *contains* methods of each patch object is utilized to test if the point is inside the path.'
def _clip(self, path, patchA, patchB):
if patchA: def insideA(xy_display): xy_event = ConnectionStyle._Base.SimpleEvent(xy_display) return patchA.contains(xy_event)[0] try: (left, right) = split_path_inout(path, insideA) except ValueError: right = path path = right if patchB: def insideB(xy_display): xy_event = ConnectionStyle._Base.SimpleEvent(xy_display) return patchB.contains(xy_event)[0] try: (left, right) = split_path_inout(path, insideB) except ValueError: left = path path = left return path
'Shrink the path by fixed size (in points) with shrinkA and shrinkB'
def _shrink(self, path, shrinkA, shrinkB):
if shrinkA: (x, y) = path.vertices[0] insideA = inside_circle(x, y, shrinkA) (left, right) = split_path_inout(path, insideA) path = right if shrinkB: (x, y) = path.vertices[(-1)] insideB = inside_circle(x, y, shrinkB) (left, right) = split_path_inout(path, insideB) path = left return path
'Calls the *connect* method to create a path between *posA* and *posB*. The path is clipped and shrinked.'
def __call__(self, posA, posB, shrinkA=2.0, shrinkB=2.0, patchA=None, patchB=None):
path = self.connect(posA, posB) clipped_path = self._clip(path, patchA, patchB) shrinked_path = self._shrink(clipped_path, shrinkA, shrinkB) return shrinked_path
'*rad* curvature of the curve.'
def __init__(self, rad=0.0):
self.rad = rad
'*angleA* starting angle of the path *angleB* ending angle of the path'
def __init__(self, angleA=90, angleB=0):
self.angleA = angleA self.angleB = angleB
'*angleA* starting angle of the path *angleB* ending angle of the path *rad* rounding radius of the edge'
def __init__(self, angleA=90, angleB=0, rad=0.0):
self.angleA = angleA self.angleB = angleB self.rad = rad
'*angleA* : starting angle of the path *angleB* : ending angle of the path *armA* : length of the starting arm *armB* : length of the ending arm *rad* : rounding radius of the edges'
def __init__(self, angleA=0, angleB=0, armA=None, armB=None, rad=0.0):
self.angleA = angleA self.angleB = angleB self.armA = armA self.armB = armB self.rad = rad
'Some ArrowStyle class only wokrs with a simple quaratic bezier curve (created with Arc3Connetion or Angle3Connector). This static method is to check if the provided path is a simple quadratic bezier curve and returns its control points if true.'
@staticmethod def ensure_quadratic_bezier(path):
segments = list(path.iter_segments()) assert (len(segments) == 2) assert (segments[0][1] == Path.MOVETO) assert (segments[1][1] == Path.CURVE3) return (list(segments[0][0]) + list(segments[1][0]))
'The transmute method is a very core of the ArrowStyle class and must be overriden in the subclasses. It receives the path object along which the arrow will be drawn, and the mutation_size, with which the amount arrow head and etc. will be scaled. It returns a Path instance. The linewidth may be used to adjust the the path so that it does not pass beyond the given points.'
def transmute(self, path, mutation_size, linewidth):
raise NotImplementedError('Derived must override')
'The __call__ method is a thin wrapper around the transmute method and take care of the aspect ratio.'
def __call__(self, path, mutation_size, linewidth, aspect_ratio=1.0):
if (aspect_ratio is not None): (vertices, codes) = (path.vertices[:], path.codes[:]) vertices[:, 1] = (vertices[:, 1] / aspect_ratio) path_shrinked = Path(vertices, codes) (path_mutated, closed) = self.transmute(path_shrinked, linewidth, mutation_size) (vertices, codes) = (path_mutated.vertices, path_mutated.codes) vertices[:, 1] = (vertices[:, 1] * aspect_ratio) return (Path(vertices, codes), closed) else: return self.transmute(path, mutation_size, linewidth)
'The arrows are drawn if *beginarrow* and/or *endarrow* are true. *head_length* and *head_width* determines the size of the arrow relative to the *mutation scale*.'
def __init__(self, beginarrow=None, endarrow=None, head_length=0.2, head_width=0.1):
(self.beginarrow, self.endarrow) = (beginarrow, endarrow) (self.head_length, self.head_width) = (head_length, head_width) super(ArrowStyle._Curve, self).__init__()
'Return the paths for arrow heads. Since arrow lines are drawn with capstyle=projected, The arrow is goes beyond the desired point. This method also returns the amount of the path to be shrinked so that it does not overshoot.'
def _get_arrow_wedge(self, x0, y0, x1, y1, head_dist, cos_t, sin_t, linewidth):
(dx, dy) = ((x0 - x1), (y0 - y1)) cp_distance = math.sqrt(((dx ** 2) + (dy ** 2))) padx_projected = ((0.5 * linewidth) / cos_t) pady_projected = ((0.5 * linewidth) / sin_t) ddx = ((padx_projected * dx) / cp_distance) ddy = ((pady_projected * dy) / cp_distance) (dx, dy) = (((dx / cp_distance) * head_dist), ((dy / cp_distance) * head_dist)) (dx1, dy1) = (((cos_t * dx) + (sin_t * dy)), (((- sin_t) * dx) + (cos_t * dy))) (dx2, dy2) = (((cos_t * dx) - (sin_t * dy)), ((sin_t * dx) + (cos_t * dy))) vertices_arrow = [(((x1 + ddx) + dx1), ((y1 + ddy) + dy1)), ((x1 + ddx), (y1 + (+ ddy))), (((x1 + ddx) + dx2), ((y1 + ddy) + dy2))] codes_arrow = [Path.MOVETO, Path.LINETO, Path.LINETO] return (vertices_arrow, codes_arrow, ddx, ddy)
'*head_length* length of the arrow head *head_width* width of the arrow head'
def __init__(self, head_length=0.4, head_width=0.2):
super(ArrowStyle.CurveA, self).__init__(beginarrow=True, endarrow=False, head_length=head_length, head_width=head_width)
'*head_length* length of the arrow head *head_width* width of the arrow head'
def __init__(self, head_length=0.4, head_width=0.2):
super(ArrowStyle.CurveB, self).__init__(beginarrow=False, endarrow=True, head_length=head_length, head_width=head_width)
'*head_length* length of the arrow head *head_width* width of the arrow head'
def __init__(self, head_length=0.4, head_width=0.2):
super(ArrowStyle.CurveAB, self).__init__(beginarrow=True, endarrow=True, head_length=head_length, head_width=head_width)
'*widthB* width of the bracket *lengthB* length of the bracket *angleB* angle between the bracket and the line'
def __init__(self, widthB=1.0, lengthB=0.2, angleB=None):
super(ArrowStyle.BracketB, self).__init__(None, True, widthB=widthB, lengthB=lengthB, angleB=None)
'*head_length* length of the arrow head *head_with* width of the arrow head *tail_width* width of the arrow tail'
def __init__(self, head_length=0.5, head_width=0.5, tail_width=0.2):
(self.head_length, self.head_width, self.tail_width) = (head_length, head_width, tail_width) super(ArrowStyle.Simple, self).__init__()
'*head_length* length of the arrow head *head_with* width of the arrow head *tail_width* width of the arrow tail'
def __init__(self, head_length=0.4, head_width=0.4, tail_width=0.4):
(self.head_length, self.head_width, self.tail_width) = (head_length, head_width, tail_width) super(ArrowStyle.Fancy, self).__init__()
'*tail_width* width of the tail *shrink_factor* fraction of the arrow width at the middle point'
def __init__(self, tail_width=0.3, shrink_factor=0.5):
self.tail_width = tail_width self.shrink_factor = shrink_factor super(ArrowStyle.Wedge, self).__init__()
'If *posA* and *posB* is given, a path connecting two point are created according to the connectionstyle. The path will be clipped with *patchA* and *patchB* and further shirnked by *shrinkA* and *shrinkB*. An arrow is drawn along this resulting path using the *arrowstyle* parameter. If *path* provided, an arrow is drawn along this path and *patchA*, *patchB*, *shrinkA*, and *shrinkB* are ignored. The *connectionstyle* describes how *posA* and *posB* are connected. It can be an instance of the ConnectionStyle class (matplotlib.patches.ConnectionStlye) or a string of the connectionstyle name, with optional comma-separated attributes. The following connection styles are available. %(AvailableConnectorstyles)s The *arrowstyle* describes how the fancy arrow will be drawn. It can be string of the available arrowstyle names, with optional comma-separated attributes, or one of the ArrowStyle instance. The optional attributes are meant to be scaled with the *mutation_scale*. The following arrow styles are available. %(AvailableArrowstyles)s *mutation_scale* : a value with which attributes of arrowstyle (e.g., head_length) will be scaled. default=1. *mutation_aspect* : The height of the rectangle will be squeezed by this value before the mutation and the mutated box will be stretched by the inverse of it. default=None. Valid kwargs are: %(Patch)s'
def __init__(self, posA=None, posB=None, path=None, arrowstyle='simple', arrow_transmuter=None, connectionstyle='arc3', connector=None, patchA=None, patchB=None, shrinkA=2.0, shrinkB=2.0, mutation_scale=1.0, mutation_aspect=None, **kwargs):
if ((posA is not None) and (posB is not None) and (path is None)): self._posA_posB = [posA, posB] if (connectionstyle is None): connectionstyle = 'arc3' self.set_connectionstyle(connectionstyle) elif ((posA is None) and (posB is None) and (path is not None)): self._posA_posB = None self._connetors = None else: raise ValueError('either posA and posB, or path need to provided') self.patchA = patchA self.patchB = patchB self.shrinkA = shrinkA self.shrinkB = shrinkB Patch.__init__(self, **kwargs) self._path_original = path self.set_arrowstyle(arrowstyle) self._mutation_scale = mutation_scale self._mutation_aspect = mutation_aspect
'set the begin end end positions of the connecting path. Use current vlaue if None.'
def set_positions(self, posA, posB):
if (posA is not None): self._posA_posB[0] = posA if (posB is not None): self._posA_posB[1] = posB
'set the begin patch.'
def set_patchA(self, patchA):
self.patchA = patchA
'set the begin patch'
def set_patchB(self, patchB):
self.patchB = patchB
'Set the connection style. *connectionstyle* can be a string with connectionstyle name with optional comma-separated attributes. Alternatively, the attrs can be probided as keywords. set_connectionstyle("arc,angleA=0,armA=30,rad=10") set_connectionstyle("arc", angleA=0,armA=30,rad=10) Old attrs simply are forgotten. Without argument (or with connectionstyle=None), return available styles as a list of strings.'
def set_connectionstyle(self, connectionstyle, **kw):
if (connectionstyle == None): return ConnectionStyle.pprint_styles() if isinstance(connectionstyle, ConnectionStyle._Base): self._connector = connectionstyle elif callable(connectionstyle): self._connector = connectionstyle else: self._connector = ConnectionStyle(connectionstyle, **kw)
'Return the ConnectionStyle instance'
def get_connectionstyle(self):
return self._connector
'Set the arrow style. *arrowstyle* can be a string with arrowstyle name with optional comma-separated attributes. Alternatively, the attrs can be provided as keywords. set_arrowstyle("Fancy,head_length=0.2") set_arrowstyle("fancy", head_length=0.2) Old attrs simply are forgotten. Without argument (or with arrowstyle=None), return available box styles as a list of strings.'
def set_arrowstyle(self, arrowstyle=None, **kw):
if (arrowstyle == None): return ArrowStyle.pprint_styles() if isinstance(arrowstyle, ConnectionStyle._Base): self._arrow_transmuter = arrowstyle else: self._arrow_transmuter = ArrowStyle(arrowstyle, **kw)
'Return the arrowstyle object'
def get_arrowstyle(self):
return self._arrow_transmuter
'Set the mutation scale. ACCEPTS: float'
def set_mutation_scale(self, scale):
self._mutation_scale = scale
'Return the mutation scale.'
def get_mutation_scale(self):
return self._mutation_scale
'Set the aspect ratio of the bbox mutation. ACCEPTS: float'
def set_mutation_aspect(self, aspect):
self._mutation_aspect = aspect
'Return the aspect ratio of the bbox mutation.'
def get_mutation_aspect(self):
return self._mutation_aspect