def _recache(self): self._path = Path(np.empty((0,2))) self._transform = IdentityTransform() self._alt_path = None self._alt_transform = None self._snap_threshold = None self._filled = True self._marker_function()
def get_transform(self): """ Return the :class:`~matplotlib.transforms.Transform` instance used by this artist. """ if self._transform is None: self._transform = IdentityTransform() elif (not isinstance(self._transform, Transform) and hasattr(self._transform, '_as_mpl_transform')): self._transform = self._transform._as_mpl_transform(self.axes) return self._transform
def get_transform(self): """ Return the :class:`~matplotlib.transforms.Transform` instance used by this artist. """ if self._transform is None: self._transform = IdentityTransform() return self._transform
def _draw_steps_post(self, renderer, gc, path, trans): vertices = self._xy steps = ma.zeros((2 * len(vertices) - 1, 2), np.float_) steps[::2, 0], steps[1:-1:2, 0] = vertices[:, 0], vertices[1:, 0] steps[0::2, 1], steps[1::2, 1] = vertices[:, 1], vertices[:-1, 1] path = Path(steps) path = path.transformed(self.get_transform()) self._lineFunc(renderer, gc, path, IdentityTransform())
def get_transform(self): """ Return the :class:`~matplotlib.transforms.Transform` instance used by this artist. """ if self._transform is None: self._transform = IdentityTransform() elif not isinstance(self._transform, Transform) and hasattr(self._transform, "_as_mpl_transform"): self._transform = self._transform._as_mpl_transform(self.axes) return self._transform
class MarkerStyle: style_table = """ ============================== =============================================== marker description ============================== =============================================== %s ``'$...$'`` render the string using mathtext. *verts* a list of (x, y) pairs used for Path vertices. path a :class:`~matplotlib.path.Path` instance. (*numsides*, *style*, *angle*) see below ============================== =============================================== The marker can also be a tuple (*numsides*, *style*, *angle*), which will create a custom, regular symbol. *numsides*: the number of sides *style*: the style of the regular symbol: ===== ============================================= Value Description ===== ============================================= 0 a regular polygon 1 a star-like symbol 2 an asterisk 3 a circle (*numsides* and *angle* is ignored) ===== ============================================= *angle*: the angle of rotation of the symbol, in degrees For backward compatibility, the form (*verts*, 0) is also accepted, but it is equivalent to just *verts* for giving a raw set of vertices that define the shape. """ # TODO: Automatically generate this accepts = """ACCEPTS: [ %s | ``'$...$'`` | *tuple* | *Nx2 array* ]""" markers = { '.': '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', '8': 'octagon', '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', None: 'nothing', ' ': 'nothing', '': 'nothing' } # Just used for informational purposes. is_filled() # is calculated in the _set_* functions. filled_markers = ('o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd') fillstyles = ('full', 'left', 'right', 'bottom', 'top', 'none') _half_fillstyles = ('left', 'right', 'bottom', 'top') # TODO: Is this ever used as a non-constant? _point_size_reduction = 0.5 def __init__(self, marker=None, fillstyle='full'): self._fillstyle = fillstyle self.set_marker(marker) self.set_fillstyle(fillstyle) def __getstate__(self): d = self.__dict__.copy() d.pop('_marker_function') return d def __setstate__(self, statedict): self.__dict__ = statedict self.set_marker(self._marker) self._recache() def _recache(self): self._path = Path(np.empty((0, 2))) self._transform = IdentityTransform() self._alt_path = None self._alt_transform = None self._snap_threshold = None self._joinstyle = 'round' self._capstyle = 'butt' self._filled = True self._marker_function() def __nonzero__(self): return bool(len(self._path.vertices)) def is_filled(self): return self._filled def get_fillstyle(self): return self._fillstyle def set_fillstyle(self, fillstyle): # TODO: Raise exception for markers where fillstyle doesn't make sense assert fillstyle in self.fillstyles self._fillstyle = fillstyle self._recache() def get_joinstyle(self): return self._joinstyle def get_capstyle(self): return self._capstyle def get_marker(self): return self._marker def set_marker(self, marker): if (iterable(marker) and len(marker) in (2, 3) and marker[1] in (0, 1, 2, 3)): self._marker_function = self._set_tuple_marker elif isinstance(marker, np.ndarray): self._marker_function = self._set_vertices elif not isinstance(marker, list) and marker in self.markers: self._marker_function = getattr(self, '_set_' + self.markers[marker]) elif is_string_like(marker) and is_math_text(marker): self._marker_function = self._set_mathtext_path elif isinstance(marker, Path): self._marker_function = self._set_path_marker else: try: _ = Path(marker) self._marker_function = self._set_vertices except ValueError: raise ValueError('Unrecognized marker style {}'.format(marker)) self._marker = marker self._recache() def get_path(self): return self._path def get_transform(self): return self._transform.frozen() def get_alt_path(self): return self._alt_path def get_alt_transform(self): return self._alt_transform.frozen() def get_snap_threshold(self): return self._snap_threshold def _set_nothing(self): self._filled = False def _set_custom_marker(self, path): verts = path.vertices rescale = max(np.max(np.abs(verts[:, 0])), np.max(np.abs(verts[:, 1]))) self._transform = Affine2D().scale(1.0 / rescale) self._path = path def _set_path_marker(self): self._set_custom_marker(self._marker) def _set_vertices(self): verts = self._marker marker = Path(verts) self._set_custom_marker(marker) def _set_tuple_marker(self): marker = self._marker if is_numlike(marker[0]): if len(marker) == 2: numsides, rotation = marker[0], 0.0 elif len(marker) == 3: numsides, rotation = marker[0], marker[2] symstyle = marker[1] if symstyle == 0: self._path = Path.unit_regular_polygon(numsides) self._joinstyle = 'miter' elif symstyle == 1: self._path = Path.unit_regular_star(numsides) self._joinstyle = 'bevel' elif symstyle == 2: self._path = Path.unit_regular_asterisk(numsides) self._filled = False self._joinstyle = 'bevel' elif symstyle == 3: self._path = Path.unit_circle() self._transform = Affine2D().scale(0.5).rotate_deg(rotation) else: verts = np.asarray(marker[0]) path = Path(verts) self._set_custom_marker(path) def _set_mathtext_path(self): """ Draws mathtext markers '$...$' using TextPath object. Submitted by tcb """ from matplotlib.text import TextPath from matplotlib.font_manager import FontProperties # again, the properties could be initialised just once outside # this function # Font size is irrelevant here, it will be rescaled based on # the drawn size later props = FontProperties(size=1.0) text = TextPath(xy=(0, 0), s=self.get_marker(), fontproperties=props, usetex=rcParams['text.usetex']) if len(text.vertices) == 0: return xmin, ymin = text.vertices.min(axis=0) xmax, ymax = text.vertices.max(axis=0) width = xmax - xmin height = ymax - ymin max_dim = max(width, height) self._transform = Affine2D() \ .translate(-xmin + 0.5 * -width, -ymin + 0.5 * -height) \ .scale(1.0 / max_dim) self._path = text self._snap = False def _half_fill(self): fs = self.get_fillstyle() result = fs in self._half_fillstyles return result def _set_circle(self, reduction=1.0): self._transform = Affine2D().scale(0.5 * reduction) self._snap_threshold = 6.0 fs = self.get_fillstyle() if not self._half_fill(): self._path = Path.unit_circle() else: # build a right-half circle if fs == 'bottom': rotate = 270. elif fs == 'top': rotate = 90. elif fs == 'left': rotate = 180. else: rotate = 0. self._path = self._alt_path = Path.unit_circle_righthalf() self._transform.rotate_deg(rotate) self._alt_transform = self._transform.frozen().rotate_deg(180.) def _set_pixel(self): self._path = Path.unit_rectangle() # Ideally, you'd want -0.5, -0.5 here, but then the snapping # algorithm in the Agg backend will round this to a 2x2 # rectangle from (-1, -1) to (1, 1). By offsetting it # slightly, we can force it to be (0, 0) to (1, 1), which both # makes it only be a single pixel and places it correctly # aligned to 1-width stroking (i.e. the ticks). This hack is # the best of a number of bad alternatives, mainly because the # backends are not aware of what marker is actually being used # beyond just its path data. self._transform = Affine2D().translate(-0.49999, -0.49999) self._snap_threshold = None def _set_point(self): self._set_circle(reduction=self._point_size_reduction) _triangle_path = Path( [[0.0, 1.0], [-1.0, -1.0], [1.0, -1.0], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]) # Going down halfway looks to small. Golden ratio is too far. _triangle_path_u = Path( [[0.0, 1.0], [-3 / 5., -1 / 5.], [3 / 5., -1 / 5.], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]) _triangle_path_d = Path( [[-3 / 5., -1 / 5.], [3 / 5., -1 / 5.], [1.0, -1.0], [-1.0, -1.0], [-3 / 5., -1 / 5.]], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]) _triangle_path_l = Path( [[0.0, 1.0], [0.0, -1.0], [-1.0, -1.0], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]) _triangle_path_r = Path( [[0.0, 1.0], [0.0, -1.0], [1.0, -1.0], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]) def _set_triangle(self, rot, skip): self._transform = Affine2D().scale(0.5, 0.5).rotate_deg(rot) self._snap_threshold = 5.0 fs = self.get_fillstyle() if not self._half_fill(): self._path = self._triangle_path else: mpaths = [ self._triangle_path_u, self._triangle_path_l, self._triangle_path_d, self._triangle_path_r ] if fs == 'top': self._path = mpaths[(0 + skip) % 4] self._alt_path = mpaths[(2 + skip) % 4] elif fs == 'bottom': self._path = mpaths[(2 + skip) % 4] self._alt_path = mpaths[(0 + skip) % 4] elif fs == 'left': self._path = mpaths[(1 + skip) % 4] self._alt_path = mpaths[(3 + skip) % 4] else: self._path = mpaths[(3 + skip) % 4] self._alt_path = mpaths[(1 + skip) % 4] self._alt_transform = self._transform self._joinstyle = 'miter' def _set_triangle_up(self): return self._set_triangle(0.0, 0) def _set_triangle_down(self): return self._set_triangle(180.0, 2) def _set_triangle_left(self): return self._set_triangle(90.0, 3) def _set_triangle_right(self): return self._set_triangle(270.0, 1) def _set_square(self): self._transform = Affine2D().translate(-0.5, -0.5) self._snap_threshold = 2.0 fs = self.get_fillstyle() if not self._half_fill(): self._path = Path.unit_rectangle() else: # build a bottom filled square out of two rectangles, one # filled. Use the rotation to support left, right, bottom # or top if fs == 'bottom': rotate = 0. elif fs == 'top': rotate = 180. elif fs == 'left': rotate = 270. else: rotate = 90. self._path = Path([[0.0, 0.0], [1.0, 0.0], [1.0, 0.5], [0.0, 0.5], [0.0, 0.0]]) self._alt_path = Path([[0.0, 0.5], [1.0, 0.5], [1.0, 1.0], [0.0, 1.0], [0.0, 0.5]]) self._transform.rotate_deg(rotate) self._alt_transform = self._transform self._joinstyle = 'miter' def _set_diamond(self): self._transform = Affine2D().translate(-0.5, -0.5).rotate_deg(45) self._snap_threshold = 5.0 fs = self.get_fillstyle() if not self._half_fill(): self._path = Path.unit_rectangle() else: self._path = Path([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 0.0]]) self._alt_path = Path([[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.0, 0.0]]) if fs == 'bottom': rotate = 270. elif fs == 'top': rotate = 90. elif fs == 'left': rotate = 180. else: rotate = 0. self._transform.rotate_deg(rotate) self._alt_transform = self._transform self._joinstyle = 'miter' def _set_thin_diamond(self): self._set_diamond() self._transform.scale(0.6, 1.0) def _set_pentagon(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0 polypath = Path.unit_regular_polygon(5) fs = self.get_fillstyle() if not self._half_fill(): self._path = polypath else: verts = polypath.vertices y = (1 + np.sqrt(5)) / 4. top = Path([verts[0], verts[1], verts[4], verts[0]]) bottom = Path([verts[1], verts[2], verts[3], verts[4], verts[1]]) left = Path([verts[0], verts[1], verts[2], [0, -y], verts[0]]) right = Path([verts[0], verts[4], verts[3], [0, -y], verts[0]]) if fs == 'top': mpath, mpath_alt = top, bottom elif fs == 'bottom': mpath, mpath_alt = bottom, top elif fs == 'left': mpath, mpath_alt = left, right else: mpath, mpath_alt = right, left self._path = mpath self._alt_path = mpath_alt self._alt_transform = self._transform self._joinstyle = 'miter' def _set_star(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0 fs = self.get_fillstyle() polypath = Path.unit_regular_star(5, innerCircle=0.381966) if not self._half_fill(): self._path = polypath else: verts = polypath.vertices top = Path(np.vstack((verts[0:4, :], verts[7:10, :], verts[0]))) bottom = Path(np.vstack((verts[3:8, :], verts[3]))) left = Path(np.vstack((verts[0:6, :], verts[0]))) right = Path(np.vstack((verts[0], verts[5:10, :], verts[0]))) if fs == 'top': mpath, mpath_alt = top, bottom elif fs == 'bottom': mpath, mpath_alt = bottom, top elif fs == 'left': mpath, mpath_alt = left, right else: mpath, mpath_alt = right, left self._path = mpath self._alt_path = mpath_alt self._alt_transform = self._transform self._joinstyle = 'bevel' def _set_hexagon1(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = None fs = self.get_fillstyle() polypath = Path.unit_regular_polygon(6) if not self._half_fill(): self._path = polypath else: verts = polypath.vertices # not drawing inside lines x = np.abs(np.cos(5 * np.pi / 6.)) top = Path(np.vstack(([-x, 0], verts[(1, 0, 5), :], [x, 0]))) bottom = Path(np.vstack(([-x, 0], verts[2:5, :], [x, 0]))) left = Path(verts[(0, 1, 2, 3), :]) right = Path(verts[(0, 5, 4, 3), :]) if fs == 'top': mpath, mpath_alt = top, bottom elif fs == 'bottom': mpath, mpath_alt = bottom, top elif fs == 'left': mpath, mpath_alt = left, right else: mpath, mpath_alt = right, left self._path = mpath self._alt_path = mpath_alt self._alt_transform = self._transform self._joinstyle = 'miter' def _set_hexagon2(self): self._transform = Affine2D().scale(0.5).rotate_deg(30) self._snap_threshold = None fs = self.get_fillstyle() polypath = Path.unit_regular_polygon(6) if not self._half_fill(): self._path = polypath else: verts = polypath.vertices # not drawing inside lines x, y = np.sqrt(3) / 4, 3 / 4. top = Path(verts[(1, 0, 5, 4, 1), :]) bottom = Path(verts[(1, 2, 3, 4), :]) left = Path( np.vstack(([x, y], verts[(0, 1, 2), :], [-x, -y], [x, y]))) right = Path(np.vstack(([x, y], verts[(5, 4, 3), :], [-x, -y]))) if fs == 'top': mpath, mpath_alt = top, bottom elif fs == 'bottom': mpath, mpath_alt = bottom, top elif fs == 'left': mpath, mpath_alt = left, right else: mpath, mpath_alt = right, left self._path = mpath self._alt_path = mpath_alt self._alt_transform = self._transform self._joinstyle = 'miter' def _set_octagon(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0 fs = self.get_fillstyle() polypath = Path.unit_regular_polygon(8) if not self._half_fill(): self._transform.rotate_deg(22.5) self._path = polypath else: x = np.sqrt(2.) / 4. half = Path([[0, -1], [0, 1], [-x, 1], [-1, x], [-1, -x], [-x, -1], [0, -1]]) if fs == 'bottom': rotate = 90. elif fs == 'top': rotate = 270. elif fs == 'right': rotate = 180. else: rotate = 0. self._transform.rotate_deg(rotate) self._path = self._alt_path = half self._alt_transform = self._transform.frozen().rotate_deg(180.0) self._joinstyle = 'miter' _line_marker_path = Path([[0.0, -1.0], [0.0, 1.0]]) def _set_vline(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 1.0 self._filled = False self._path = self._line_marker_path def _set_hline(self): self._transform = Affine2D().scale(0.5).rotate_deg(90) self._snap_threshold = 1.0 self._filled = False self._path = self._line_marker_path _tickhoriz_path = Path([[0.0, 0.0], [1.0, 0.0]]) def _set_tickleft(self): self._transform = Affine2D().scale(-1.0, 1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickhoriz_path def _set_tickright(self): self._transform = Affine2D().scale(1.0, 1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickhoriz_path _tickvert_path = Path([[-0.0, 0.0], [-0.0, 1.0]]) def _set_tickup(self): self._transform = Affine2D().scale(1.0, 1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickvert_path def _set_tickdown(self): self._transform = Affine2D().scale(1.0, -1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickvert_path _plus_path = Path([[-1.0, 0.0], [1.0, 0.0], [0.0, -1.0], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO]) def _set_plus(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 1.0 self._filled = False self._path = self._plus_path _tri_path = Path([[0.0, 0.0], [0.0, -1.0], [0.0, 0.0], [0.8, 0.5], [0.0, 0.0], [-0.8, 0.5]], [ Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO ]) def _set_tri_down(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0 self._filled = False self._path = self._tri_path def _set_tri_up(self): self._transform = Affine2D().scale(0.5).rotate_deg(90) self._snap_threshold = 5.0 self._filled = False self._path = self._tri_path def _set_tri_left(self): self._transform = Affine2D().scale(0.5).rotate_deg(270) self._snap_threshold = 5.0 self._filled = False self._path = self._tri_path def _set_tri_right(self): self._transform = Affine2D().scale(0.5).rotate_deg(180) self._snap_threshold = 5.0 self._filled = False self._path = self._tri_path _caret_path = Path([[-1.0, 1.5], [0.0, 0.0], [1.0, 1.5]]) def _set_caretdown(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 3.0 self._filled = False self._path = self._caret_path self._joinstyle = 'miter' def _set_caretup(self): self._transform = Affine2D().scale(0.5).rotate_deg(180) self._snap_threshold = 3.0 self._filled = False self._path = self._caret_path self._joinstyle = 'miter' def _set_caretleft(self): self._transform = Affine2D().scale(0.5).rotate_deg(270) self._snap_threshold = 3.0 self._filled = False self._path = self._caret_path self._joinstyle = 'miter' def _set_caretright(self): self._transform = Affine2D().scale(0.5).rotate_deg(90) self._snap_threshold = 3.0 self._filled = False self._path = self._caret_path self._joinstyle = 'miter' _x_path = Path([[-1.0, -1.0], [1.0, 1.0], [-1.0, 1.0], [1.0, -1.0]], [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO]) def _set_x(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 3.0 self._filled = False self._path = self._x_path
class MarkerStyle: style_table = """ ============================== =============================================== marker description ============================== =============================================== %s ``'$...$'`` render the string using mathtext *verts* a list of (x, y) pairs in range (0, 1) (*numsides*, *style*, *angle*) see below ============================== =============================================== The marker can also be a tuple (*numsides*, *style*, *angle*), which will create a custom, regular symbol. *numsides*: the number of sides *style*: the style of the regular symbol: ===== ============================================= Value Description ===== ============================================= 0 a regular polygon 1 a star-like symbol 2 an asterisk 3 a circle (*numsides* and *angle* is ignored) ===== ============================================= *angle*: the angle of rotation of the symbol For backward compatibility, the form (*verts*, 0) is also accepted, but it is equivalent to just *verts* for giving a raw set of vertices that define the shape. """ # TODO: Automatically generate this accepts = """ACCEPTS: [ %s | ``'$...$'`` | *tuple* | *Nx2 array* ]""" markers = { '.' : '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', '8' : 'octagon', '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', None : 'nothing', ' ' : 'nothing', '' : 'nothing' } # Just used for informational purposes. is_filled() # is calculated in the _set_* functions. filled_markers = ( 'o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd') fillstyles = ('full', 'left' , 'right' , 'bottom' , 'top', 'none') _half_fillstyles = ('left' , 'right' , 'bottom' , 'top') # TODO: Is this ever used as a non-constant? _point_size_reduction = 0.5 def __init__(self, marker=None, fillstyle='full'): self._fillstyle = fillstyle self.set_marker(marker) self.set_fillstyle(fillstyle) def _recache(self): self._path = Path(np.empty((0,2))) self._transform = IdentityTransform() self._alt_path = None self._alt_transform = None self._snap_threshold = None self._joinstyle = 'round' self._capstyle = 'butt' self._filled = True self._marker_function() def __nonzero__(self): return bool(len(self._path.vertices)) def is_filled(self): return self._filled def get_fillstyle(self): return self._fillstyle def set_fillstyle(self, fillstyle): # TODO: Raise exception for markers where fillstyle doesn't make sense assert fillstyle in self.fillstyles self._fillstyle = fillstyle self._recache() def get_joinstyle(self): return self._joinstyle def get_capstyle(self): return self._capstyle def get_marker(self): return self._marker def set_marker(self, marker): if (iterable(marker) and len(marker) in (2, 3) and marker[1] in (0, 1, 2, 3)): self._marker_function = self._set_tuple_marker elif marker in self.markers: self._marker_function = getattr( self, '_set_' + self.markers[marker]) elif is_string_like(marker) and is_math_text(marker): self._marker_function = self._set_mathtext_path elif isinstance(marker, Path): self._marker_function = self._set_path_marker else: try: path = Path(marker) self._marker_function = self._set_vertices except: raise ValueError('Unrecognized marker style %s' % marker) self._marker = marker self._recache() def get_path(self): return self._path def get_transform(self): return self._transform.frozen() def get_alt_path(self): return self._alt_path def get_alt_transform(self): return self._alt_transform.frozen() def get_snap_threshold(self): return self._snap_threshold def _set_nothing(self): self._filled = False def _set_custom_marker(self, path): verts = path.vertices rescale = max(np.max(np.abs(verts[:,0])), np.max(np.abs(verts[:,1]))) self._transform = Affine2D().scale(1.0 / rescale) self._path = path def _set_path_marker(self): self._set_custom_marker(self._marker) def _set_vertices(self): path = Path(verts) self._set_custom_marker(path) def _set_tuple_marker(self): marker = self._marker if is_numlike(marker[0]): if len(marker) == 2: numsides, rotation = marker[0], 0.0 elif len(marker) == 3: numsides, rotation = marker[0], marker[2] symstyle = marker[1] if symstyle == 0: self._path = Path.unit_regular_polygon(numsides) self._joinstyle = 'miter' elif symstyle == 1: self._path = Path.unit_regular_star(numsides) self._joinstyle = 'bevel' elif symstyle == 2: self._path = Path.unit_regular_asterisk(numsides) self._filled = False self._joinstyle = 'bevel' elif symstyle == 3: self._path = Path.unit_circle() self._transform = Affine2D().scale(0.5).rotate_deg(rotation) else: verts = np.asarray(marker[0]) path = Path(verts) self._set_custom_marker(path) def _set_mathtext_path(self): """ Draws mathtext markers '$...$' using TextPath object. Submitted by tcb """ from matplotlib.patches import PathPatch from matplotlib.text import TextPath from matplotlib.font_manager import FontProperties # again, the properties could be initialised just once outside # this function # Font size is irrelevant here, it will be rescaled based on # the drawn size later props = FontProperties(size=1.0) text = TextPath(xy=(0,0), s=self.get_marker(), fontproperties=props, usetex=rcParams['text.usetex']) if len(text.vertices) == 0: return xmin, ymin = text.vertices.min(axis=0) xmax, ymax = text.vertices.max(axis=0) width = xmax - xmin height = ymax - ymin max_dim = max(width, height) self._transform = Affine2D() \ .translate(-xmin + 0.5 * -width, -ymin + 0.5 * -height) \ .scale(1.0 / max_dim) self._path = text self._snap = False def _half_fill(self): fs = self.get_fillstyle() result = fs in self._half_fillstyles return result def _set_circle(self, reduction = 1.0): self._transform = Affine2D().scale(0.5 * reduction) self._snap_threshold = 3.0 fs = self.get_fillstyle() if not self._half_fill(): self._path = Path.unit_circle() else: # build a right-half circle if fs=='bottom': rotate = 270. elif fs=='top': rotate = 90. elif fs=='left': rotate = 180. else: rotate = 0. self._path = self._alt_path = Path.unit_circle_righthalf() self._transform.rotate_deg(rotate) self._alt_transform = self._transform.frozen().rotate_deg(180.) def _set_pixel(self): self._path = Path.unit_rectangle() # Ideally, you'd want -0.5, -0.5 here, but then the snapping # algorithm in the Agg backend will round this to a 2x2 # rectangle from (-1, -1) to (1, 1). By offsetting it # slightly, we can force it to be (0, 0) to (1, 1), which both # makes it only be a single pixel and places it correctly # aligned to 1-width stroking (i.e. the ticks). This hack is # the best of a number of bad alternatives, mainly because the # backends are not aware of what marker is actually being used # beyond just its path data. self._transform = Affine2D().translate(-0.49999, -0.49999) self._snap_threshold = None def _set_point(self): self._set_circle(reduction = self._point_size_reduction) _triangle_path = Path( [[0.0, 1.0], [-1.0, -1.0], [1.0, -1.0], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]) # Going down halfway looks to small. Golden ratio is too far. _triangle_path_u = Path( [[0.0, 1.0], [-3/5., -1/5.], [3/5., -1/5.], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]) _triangle_path_d = Path( [[-3/5., -1/5.], [3/5., -1/5.], [1.0, -1.0], [-1.0, -1.0], [-3/5., -1/5.]], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]) _triangle_path_l = Path( [[0.0, 1.0], [0.0, -1.0], [-1.0, -1.0], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]) _triangle_path_r = Path( [[0.0, 1.0], [0.0, -1.0], [1.0, -1.0], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]) def _set_triangle(self, rot, skip): self._transform = Affine2D().scale(0.5, 0.5).rotate_deg(rot) self._snap_threshold = 5.0 fs = self.get_fillstyle() if not self._half_fill(): self._path = self._triangle_path else: mpaths = [self._triangle_path_u, self._triangle_path_l, self._triangle_path_d, self._triangle_path_r] if fs=='top': self._path = mpaths[(0+skip) % 4] self._alt_path = mpaths[(2+skip) % 4] elif fs=='bottom': self._path = mpaths[(2+skip) % 4] self._alt_path = mpaths[(0+skip) % 4] elif fs=='left': self._path = mpaths[(1+skip) % 4] self._alt_path = mpaths[(3+skip) % 4] else: self._path = mpaths[(3+skip) % 4] self._alt_path = mpaths[(1+skip) % 4] self._alt_transform = self._transform self._joinstyle = 'miter' def _set_triangle_up(self): return self._set_triangle(0.0, 0) def _set_triangle_down(self): return self._set_triangle(180.0, 2) def _set_triangle_left(self): return self._set_triangle(90.0, 3) def _set_triangle_right(self): return self._set_triangle(270.0, 1) def _set_square(self): self._transform = Affine2D().translate(-0.5, -0.5) self._snap_threshold = 2.0 fs = self.get_fillstyle() if not self._half_fill(): self._path = Path.unit_rectangle() else: # build a bottom filled square out of two rectangles, one # filled. Use the rotation to support left, right, bottom # or top if fs=='bottom': rotate = 0. elif fs=='top': rotate = 180. elif fs=='left': rotate = 270. else: rotate = 90. self._path = Path([[0.0, 0.0], [1.0, 0.0], [1.0, 0.5], [0.0, 0.5], [0.0, 0.0]]) self._alt_path = Path([[0.0, 0.5], [1.0, 0.5], [1.0, 1.0], [0.0, 1.0], [0.0, 0.5]]) self._transform.rotate_deg(rotate) self._alt_transform = self._transform self._joinstyle = 'miter' def _set_diamond(self): self._transform = Affine2D().translate(-0.5, -0.5).rotate_deg(45) self._snap_threshold = 5.0 fs = self.get_fillstyle() if not self._half_fill(): self._path = Path.unit_rectangle() else: self._path = Path([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 0.0]]) self._alt_path = Path([[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.0, 0.0]]) if fs=='bottom': rotate = 270. elif fs=='top': rotate = 90. elif fs=='left': rotate = 180. else: rotate = 0. self._transform.rotate_deg(rotate) self._alt_transform = self._transform self._joinstyle = 'miter' def _set_thin_diamond(self): self._set_diamond() self._transform.scale(0.6, 1.0) def _set_pentagon(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0 polypath = Path.unit_regular_polygon(5) fs = self.get_fillstyle() if not self._half_fill(): self._path = polypath else: verts = polypath.vertices y = (1+np.sqrt(5))/4. top = Path([verts[0], verts[1], verts[4], verts[0]]) bottom = Path([verts[1], verts[2], verts[3], verts[4], verts[1]]) left = Path([verts[0], verts[1], verts[2], [0,-y], verts[0]]) right = Path([verts[0], verts[4], verts[3], [0,-y], verts[0]]) if fs == 'top': mpath, mpath_alt = top, bottom elif fs == 'bottom': mpath, mpath_alt = bottom, top elif fs == 'left': mpath, mpath_alt = left, right else: mpath, mpath_alt = right, left self._path = mpath self._alt_path = mpath_alt self._alt_transform = self._transform self._joinstyle = 'miter' def _set_star(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0 fs = self.get_fillstyle() polypath = Path.unit_regular_star(5, innerCircle=0.381966) if not self._half_fill(): self._path = polypath else: verts = polypath.vertices top = Path(np.vstack((verts[0:4,:], verts[7:10,:], verts[0]))) bottom = Path(np.vstack((verts[3:8,:], verts[3]))) left = Path(np.vstack((verts[0:6,:], verts[0]))) right = Path(np.vstack((verts[0], verts[5:10,:], verts[0]))) if fs == 'top': mpath, mpath_alt = top, bottom elif fs == 'bottom': mpath, mpath_alt = bottom, top elif fs == 'left': mpath, mpath_alt = left, right else: mpath, mpath_alt = right, left self._path = mpath self._alt_path = mpath_alt self._alt_transform = self._transform self._joinstyle = 'bevel' def _set_hexagon1(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0 fs = self.get_fillstyle() polypath = Path.unit_regular_polygon(6) if not self._half_fill(): self._path = polypath else: verts = polypath.vertices # not drawing inside lines x = np.abs(np.cos(5*np.pi/6.)) top = Path(np.vstack(([-x,0],verts[(1,0,5),:],[x,0]))) bottom = Path(np.vstack(([-x,0],verts[2:5,:],[x,0]))) left = Path(verts[(0,1,2,3),:]) right = Path(verts[(0,5,4,3),:]) if fs == 'top': mpath, mpath_alt = top, bottom elif fs == 'bottom': mpath, mpath_alt = bottom, top elif fs == 'left': mpath, mpath_alt = left, right else: mpath, mpath_alt = right, left self._path = mpath self._alt_path = mpath_alt self._alt_transform = self._transform self._joinstyle = 'miter' def _set_hexagon2(self): self._transform = Affine2D().scale(0.5).rotate_deg(30) self._snap_threshold = 5.0 fs = self.get_fillstyle() polypath = Path.unit_regular_polygon(6) if not self._half_fill(): self._path = polypath else: verts = polypath.vertices # not drawing inside lines x, y = np.sqrt(3)/4, 3/4. top = Path(verts[(1,0,5,4,1),:]) bottom = Path(verts[(1,2,3,4),:]) left = Path(np.vstack(([x,y],verts[(0,1,2),:],[-x,-y],[x,y]))) right = Path(np.vstack(([x,y],verts[(5,4,3),:],[-x,-y]))) if fs == 'top': mpath, mpath_alt = top, bottom elif fs == 'bottom': mpath, mpath_alt = bottom, top elif fs == 'left': mpath, mpath_alt = left, right else: mpath, mpath_alt = right, left self._path = mpath self._alt_path = mpath_alt self._alt_transform = self._transform self._joinstyle = 'miter' def _set_octagon(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0 fs = self.get_fillstyle() polypath = Path.unit_regular_polygon(8) if not self._half_fill(): self._transform.rotate_deg(22.5) self._path = polypath else: x = np.sqrt(2.)/4. half = Path([[0, -1], [0, 1], [-x, 1], [-1, x], [-1, -x], [-x, -1], [0, -1]]) if fs=='bottom': rotate = 90. elif fs=='top': rotate = 270. elif fs=='right': rotate = 180. else: rotate = 0. self._transform.rotate_deg(rotate) self._path = self._alt_path = half self._alt_transform = self._transform.frozen().rotate_deg(180.0) self._joinstyle = 'miter' _line_marker_path = Path([[0.0, -1.0], [0.0, 1.0]]) def _set_vline(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 1.0 self._filled = False self._path = self._line_marker_path def _set_hline(self): self._transform = Affine2D().scale(0.5).rotate_deg(90) self._snap_threshold = 1.0 self._filled = False self._path = self._line_marker_path _tickhoriz_path = Path([[0.0, 0.0], [1.0, 0.0]]) def _set_tickleft(self): self._transform = Affine2D().scale(-1.0, 1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickhoriz_path def _set_tickright(self): self._transform = Affine2D().scale(1.0, 1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickhoriz_path _tickvert_path = Path([[-0.0, 0.0], [-0.0, 1.0]]) def _set_tickup(self): self._transform = Affine2D().scale(1.0, 1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickvert_path def _set_tickdown(self): self._transform = Affine2D().scale(1.0, -1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickvert_path _plus_path = Path([[-1.0, 0.0], [1.0, 0.0], [0.0, -1.0], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO]) def _set_plus(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 1.0 self._filled = False self._path = self._plus_path _tri_path = Path([[0.0, 0.0], [0.0, -1.0], [0.0, 0.0], [0.8, 0.5], [0.0, 0.0], [-0.8, 0.5]], [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO]) def _set_tri_down(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0 self._filled = False self._path = self._tri_path def _set_tri_up(self): self._transform = Affine2D().scale(0.5).rotate_deg(90) self._snap_threshold = 5.0 self._filled = False self._path = self._tri_path def _set_tri_left(self): self._transform = Affine2D().scale(0.5).rotate_deg(270) self._snap_threshold = 5.0 self._filled = False self._path = self._tri_path def _set_tri_right(self): self._transform = Affine2D().scale(0.5).rotate_deg(180) self._snap_threshold = 5.0 self._filled = False self._path = self._tri_path _caret_path = Path([[-1.0, 1.5], [0.0, 0.0], [1.0, 1.5]]) def _set_caretdown(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 3.0 self._filled = False self._path = self._caret_path self._joinstyle = 'miter' def _set_caretup(self): self._transform = Affine2D().scale(0.5).rotate_deg(180) self._snap_threshold = 3.0 self._filled = False self._path = self._caret_path self._joinstyle = 'miter' def _set_caretleft(self): self._transform = Affine2D().scale(0.5).rotate_deg(270) self._snap_threshold = 3.0 self._filled = False self._path = self._caret_path self._joinstyle = 'miter' def _set_caretright(self): self._transform = Affine2D().scale(0.5).rotate_deg(90) self._snap_threshold = 3.0 self._filled = False self._path = self._caret_path self._joinstyle = 'miter' _x_path = Path([[-1.0, -1.0], [1.0, 1.0], [-1.0, 1.0], [1.0, -1.0]], [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO]) def _set_x(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 3.0 self._filled = False self._path = self._x_path
class Artist(object): """ Abstract base class for someone who renders into a :class:`FigureCanvas`. """ aname = 'Artist' zorder = 0 def __init__(self): self.figure = None self._transform = None self._transformSet = False self._visible = True self._animated = False self._alpha = None self.clipbox = None self._clippath = None self._clipon = True self._lod = False self._label = '' self._picker = None self._contains = None self._rasterized = None self._agg_filter = None self.eventson = False # fire events only if eventson self._oid = 0 # an observer id self._propobservers = {} # a dict from oids to funcs try: self.axes = None except AttributeError: # Handle self.axes as a read-only property, as in Figure. pass self._remove_method = None self._url = None self._gid = None self._snap = None def __getstate__(self): d = self.__dict__.copy() # remove the unpicklable remove method, this will get re-added on load # (by the axes) if the artist lives on an axes. d['_remove_method'] = None return d def remove(self): """ Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with :meth:`matplotlib.axes.Axes.draw_idle`. Call :meth:`matplotlib.axes.Axes.relim` to update the axes limits if desired. Note: :meth:`~matplotlib.axes.Axes.relim` will not see collections even if the collection was added to axes with *autolim* = True. Note: there is no support for removing the artist's legend entry. """ # There is no method to set the callback. Instead the parent should # set the _remove_method attribute directly. This would be a # protected attribute if Python supported that sort of thing. The # callback has one parameter, which is the child to be removed. if self._remove_method is not None: self._remove_method(self) else: raise NotImplementedError('cannot remove artist') # TODO: the fix for the collections relim problem is to move the # limits calculation into the artist itself, including the property of # whether or not the artist should affect the limits. Then there will # be no distinction between axes.add_line, axes.add_patch, etc. # TODO: add legend support def have_units(self): 'Return *True* if units are set on the *x* or *y* axes' ax = self.axes if ax is None or ax.xaxis is None: return False return ax.xaxis.have_units() or ax.yaxis.have_units() def convert_xunits(self, x): """For artists in an axes, if the xaxis has units support, convert *x* using xaxis unit type """ ax = getattr(self, 'axes', None) if ax is None or ax.xaxis is None: #print 'artist.convert_xunits no conversion: ax=%s'%ax return x return ax.xaxis.convert_units(x) def convert_yunits(self, y): """For artists in an axes, if the yaxis has units support, convert *y* using yaxis unit type """ ax = getattr(self, 'axes', None) if ax is None or ax.yaxis is None: return y return ax.yaxis.convert_units(y) def set_axes(self, axes): """ Set the :class:`~matplotlib.axes.Axes` instance in which the artist resides, if any. ACCEPTS: an :class:`~matplotlib.axes.Axes` instance """ self.axes = axes def get_axes(self): """ Return the :class:`~matplotlib.axes.Axes` instance the artist resides in, or *None* """ return self.axes def add_callback(self, func): """ Adds a callback function that will be called whenever one of the :class:`Artist`'s properties changes. Returns an *id* that is useful for removing the callback with :meth:`remove_callback` later. """ oid = self._oid self._propobservers[oid] = func self._oid += 1 return oid def remove_callback(self, oid): """ Remove a callback based on its *id*. .. seealso:: :meth:`add_callback` For adding callbacks """ try: del self._propobservers[oid] except KeyError: pass def pchanged(self): """ Fire an event when property changed, calling all of the registered callbacks. """ for oid, func in self._propobservers.iteritems(): func(self) def is_transform_set(self): """ Returns *True* if :class:`Artist` has a transform explicitly set. """ return self._transformSet def set_transform(self, t): """ Set the :class:`~matplotlib.transforms.Transform` instance used by this artist. ACCEPTS: :class:`~matplotlib.transforms.Transform` instance """ self._transform = t self._transformSet = t is not None self.pchanged() def get_transform(self): """ Return the :class:`~matplotlib.transforms.Transform` instance used by this artist. """ if self._transform is None: self._transform = IdentityTransform() elif (not isinstance(self._transform, Transform) and hasattr(self._transform, '_as_mpl_transform')): self._transform = self._transform._as_mpl_transform(self.axes) return self._transform def hitlist(self, event): """ List the children of the artist which contain the mouse event *event*. """ L = [] try: hascursor, info = self.contains(event) if hascursor: L.append(self) except: import traceback traceback.print_exc() print("while checking", self.__class__) for a in self.get_children(): L.extend(a.hitlist(event)) return L def get_children(self): """ Return a list of the child :class:`Artist`s this :class:`Artist` contains. """ return [] def contains(self, mouseevent): """Test whether the artist contains the mouse event. Returns the truth value and a dictionary of artist specific details of selection, such as which points are contained in the pick radius. See individual artists for details. """ if callable(self._contains): return self._contains(self, mouseevent) warnings.warn("'%s' needs 'contains' method" % self.__class__.__name__) return False, {} def set_contains(self, picker): """ Replace the contains test used by this artist. The new picker should be a callable function which determines whether the artist is hit by the mouse event:: hit, props = picker(artist, mouseevent) If the mouse event is over the artist, return *hit* = *True* and *props* is a dictionary of properties you want returned with the contains test. ACCEPTS: a callable function """ self._contains = picker def get_contains(self): """ Return the _contains test used by the artist, or *None* for default. """ return self._contains def pickable(self): 'Return *True* if :class:`Artist` is pickable.' return (self.figure is not None and self.figure.canvas is not None and self._picker is not None) def pick(self, mouseevent): """ call signature:: pick(mouseevent) each child artist will fire a pick event if *mouseevent* is over the artist and the artist has picker set """ # Pick self if self.pickable(): picker = self.get_picker() if callable(picker): inside, prop = picker(self, mouseevent) else: inside, prop = self.contains(mouseevent) if inside: self.figure.canvas.pick_event(mouseevent, self, **prop) # Pick children for a in self.get_children(): # make sure the event happened in the same axes ax = getattr(a, 'axes', None) if mouseevent.inaxes is None or mouseevent.inaxes == ax: # we need to check if mouseevent.inaxes is None # because some objects associated with an axes (eg a # tick label) can be outside the bounding box of the # axes and inaxes will be None a.pick(mouseevent) def set_picker(self, picker): """ Set the epsilon for picking used by this artist *picker* can be one of the following: * *None*: picking is disabled for this artist (default) * A boolean: if *True* then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist * A float: if picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if it's data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g. the indices of the data within epsilon of the pick event * A function: if picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event:: hit, props = picker(artist, mouseevent) to determine the hit test. if the mouse event is over the artist, return *hit=True* and props is a dictionary of properties you want added to the PickEvent attributes. ACCEPTS: [None|float|boolean|callable] """ self._picker = picker def get_picker(self): 'Return the picker object used by this artist' return self._picker def is_figure_set(self): """ Returns True if the artist is assigned to a :class:`~matplotlib.figure.Figure`. """ return self.figure is not None def get_url(self): """ Returns the url """ return self._url def set_url(self, url): """ Sets the url for the artist ACCEPTS: a url string """ self._url = url def get_gid(self): """ Returns the group id """ return self._gid def set_gid(self, gid): """ Sets the (group) id for the artist ACCEPTS: an id string """ self._gid = gid def get_snap(self): """ Returns the snap setting which may be: * True: snap vertices to the nearest pixel center * False: leave vertices as-is * None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center Only supported by the Agg and MacOSX backends. """ if rcParams['path.snap']: return self._snap else: return False def set_snap(self, snap): """ Sets the snap setting which may be: * True: snap vertices to the nearest pixel center * False: leave vertices as-is * None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center Only supported by the Agg and MacOSX backends. """ self._snap = snap def get_figure(self): """ Return the :class:`~matplotlib.figure.Figure` instance the artist belongs to. """ return self.figure def set_figure(self, fig): """ Set the :class:`~matplotlib.figure.Figure` instance the artist belongs to. ACCEPTS: a :class:`matplotlib.figure.Figure` instance """ self.figure = fig self.pchanged() def set_clip_box(self, clipbox): """ Set the artist's clip :class:`~matplotlib.transforms.Bbox`. ACCEPTS: a :class:`matplotlib.transforms.Bbox` instance """ self.clipbox = clipbox self.pchanged() def set_clip_path(self, path, transform=None): """ Set the artist's clip path, which may be: * a :class:`~matplotlib.patches.Patch` (or subclass) instance * a :class:`~matplotlib.path.Path` instance, in which case an optional :class:`~matplotlib.transforms.Transform` instance may be provided, which will be applied to the path before using it for clipping. * *None*, to remove the clipping path For efficiency, if the path happens to be an axis-aligned rectangle, this method will set the clipping box to the corresponding rectangle and set the clipping path to *None*. ACCEPTS: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] """ from matplotlib.patches import Patch, Rectangle success = False if transform is None: if isinstance(path, Rectangle): self.clipbox = TransformedBbox(Bbox.unit(), path.get_transform()) self._clippath = None success = True elif isinstance(path, Patch): self._clippath = TransformedPath( path.get_path(), path.get_transform()) success = True elif isinstance(path, tuple): path, transform = path if path is None: self._clippath = None success = True elif isinstance(path, Path): self._clippath = TransformedPath(path, transform) success = True elif isinstance(path, TransformedPath): self._clippath = path success = True if not success: print(type(path), type(transform)) raise TypeError("Invalid arguments to set_clip_path") self.pchanged() def get_alpha(self): """ Return the alpha value used for blending - not supported on all backends """ return self._alpha def get_visible(self): "Return the artist's visiblity" return self._visible def get_animated(self): "Return the artist's animated state" return self._animated def get_clip_on(self): 'Return whether artist uses clipping' return self._clipon def get_clip_box(self): 'Return artist clipbox' return self.clipbox def get_clip_path(self): 'Return artist clip path' return self._clippath def get_transformed_clip_path_and_affine(self): ''' Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation. ''' if self._clippath is not None: return self._clippath.get_transformed_path_and_affine() return None, None def set_clip_on(self, b): """ Set whether artist uses clipping. ACCEPTS: [True | False] """ self._clipon = b self.pchanged() def _set_gc_clip(self, gc): 'Set the clip properly for the gc' if self._clipon: if self.clipbox is not None: gc.set_clip_rectangle(self.clipbox) gc.set_clip_path(self._clippath) else: gc.set_clip_rectangle(None) gc.set_clip_path(None) def get_rasterized(self): "return True if the artist is to be rasterized" return self._rasterized def set_rasterized(self, rasterized): """ Force rasterized (bitmap) drawing in vector backend output. Defaults to None, which implies the backend's default behavior ACCEPTS: [True | False | None] """ if rasterized and not hasattr(self.draw, "_supports_rasterization"): warnings.warn("Rasterization of '%s' will be ignored" % self) self._rasterized = rasterized def get_agg_filter(self): "return filter function to be used for agg filter" return self._agg_filter def set_agg_filter(self, filter_func): """ set agg_filter fuction. """ self._agg_filter = filter_func def draw(self, renderer, *args, **kwargs): 'Derived classes drawing method' if not self.get_visible(): return def set_alpha(self, alpha): """ Set the alpha value used for blending - not supported on all backends. ACCEPTS: float (0.0 transparent through 1.0 opaque) """ self._alpha = alpha self.pchanged() def set_lod(self, on): """ Set Level of Detail on or off. If on, the artists may examine things like the pixel width of the axes and draw a subset of their contents accordingly ACCEPTS: [True | False] """ self._lod = on self.pchanged() def set_visible(self, b): """ Set the artist's visiblity. ACCEPTS: [True | False] """ self._visible = b self.pchanged() def set_animated(self, b): """ Set the artist's animation state. ACCEPTS: [True | False] """ self._animated = b self.pchanged() def update(self, props): """ Update the properties of this :class:`Artist` from the dictionary *prop*. """ store = self.eventson self.eventson = False changed = False for k, v in props.iteritems(): func = getattr(self, 'set_' + k, None) if func is None or not callable(func): raise AttributeError('Unknown property %s' % k) func(v) changed = True self.eventson = store if changed: self.pchanged() def get_label(self): """ Get the label used for this artist in the legend. """ return self._label def set_label(self, s): """ Set the label to *s* for auto legend. ACCEPTS: string or anything printable with '%s' conversion. """ self._label = '%s' % (s, ) self.pchanged() def get_zorder(self): """ Return the :class:`Artist`'s zorder. """ return self.zorder def set_zorder(self, level): """ Set the zorder for the artist. Artists with lower zorder values are drawn first. ACCEPTS: any number """ self.zorder = level self.pchanged() def update_from(self, other): 'Copy properties from *other* to *self*.' self._transform = other._transform self._transformSet = other._transformSet self._visible = other._visible self._alpha = other._alpha self.clipbox = other.clipbox self._clipon = other._clipon self._clippath = other._clippath self._lod = other._lod self._label = other._label self.pchanged() def properties(self): """ return a dictionary mapping property name -> value for all Artist props """ return ArtistInspector(self).properties() def set(self, **kwargs): """ A tkstyle set command, pass *kwargs* to set properties """ ret = [] for k, v in kwargs.iteritems(): k = k.lower() funcName = "set_%s" % k func = getattr(self, funcName) ret.extend([func(v)]) return ret def findobj(self, match=None, include_self=True): """ Find artist objects. pyplot signature: findobj(o=gcf(), match=None, include_self=True) Recursively find all :class:matplotlib.artist.Artist instances contained in self. *match* can be - None: return all objects contained in artist. - function with signature ``boolean = match(artist)`` used to filter matches - class instance: eg Line2D. Only return artists of class type. If *include_self* is True (default), include self in the list to be checked for a match. .. plot:: mpl_examples/pylab_examples/findobj_demo.py """ if match is None: # always return True def matchfunc(x): return True elif cbook.issubclass_safe(match, Artist): def matchfunc(x): return isinstance(x, match) elif callable(match): matchfunc = match else: raise ValueError('match must be None, a matplotlib.artist.Artist ' 'subclass, or a callable') artists = [] for c in self.get_children(): if matchfunc(c): artists.append(c) artists.extend([thisc for thisc in c.findobj(matchfunc, include_self=False) if matchfunc(thisc)]) if include_self and matchfunc(self): artists.append(self) return artists
def get_transform(self): """ The transform for linear scaling is just the :class:`~matplotlib.transforms.IdentityTransform`. """ return IdentityTransform()
def get_transform(self): return IdentityTransform()
class MarkerStyle(object): markers = { ".": "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", "8": "octagon", "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", None: "nothing", " ": "nothing", "": "nothing", } # Just used for informational purposes. is_filled() # is calculated in the _set_* functions. filled_markers = ("o", "v", "^", "<", ">", "8", "s", "p", "*", "h", "H", "D", "d") fillstyles = ("full", "left", "right", "bottom", "top", "none") _half_fillstyles = ("left", "right", "bottom", "top") # TODO: Is this ever used as a non-constant? _point_size_reduction = 0.5 def __init__(self, marker=None, fillstyle="full"): """ MarkerStyle Attributes ---------- markers : list of known markes fillstyles : list of known fillstyles filled_markers : list of known filled markers. Parameters ---------- marker : string or array_like, optional, default: None See the descriptions of possible markers in the module docstring. fillstyle : string, optional, default: 'full' 'full', 'left", 'right', 'bottom', 'top', 'none' """ self._fillstyle = fillstyle self.set_marker(marker) self.set_fillstyle(fillstyle) def __getstate__(self): d = self.__dict__.copy() d.pop("_marker_function") return d def __setstate__(self, statedict): self.__dict__ = statedict self.set_marker(self._marker) self._recache() def _recache(self): self._path = Path(np.empty((0, 2))) self._transform = IdentityTransform() self._alt_path = None self._alt_transform = None self._snap_threshold = None self._joinstyle = "round" self._capstyle = "butt" self._filled = True self._marker_function() def __nonzero__(self): return bool(len(self._path.vertices)) def is_filled(self): return self._filled def get_fillstyle(self): return self._fillstyle def set_fillstyle(self, fillstyle): """ Sets fillstyle Parameters ---------- fillstyle : string amongst known fillstyles """ if fillstyle not in self.fillstyles: raise ValueError("Unrecognized fillstyle %s" % " ".join(self.fillstyles)) self._fillstyle = fillstyle self._recache() def get_joinstyle(self): return self._joinstyle def get_capstyle(self): return self._capstyle def get_marker(self): return self._marker def set_marker(self, marker): if iterable(marker) and len(marker) in (2, 3) and marker[1] in (0, 1, 2, 3): self._marker_function = self._set_tuple_marker elif isinstance(marker, np.ndarray): self._marker_function = self._set_vertices elif marker in self.markers: self._marker_function = getattr(self, "_set_" + self.markers[marker]) elif is_string_like(marker) and is_math_text(marker): self._marker_function = self._set_mathtext_path elif isinstance(marker, Path): self._marker_function = self._set_path_marker else: try: Path(marker) self._marker_function = self._set_vertices except ValueError: raise ValueError("Unrecognized marker style {}".format(marker)) self._marker = marker self._recache() def get_path(self): return self._path def get_transform(self): return self._transform.frozen() def get_alt_path(self): return self._alt_path def get_alt_transform(self): return self._alt_transform.frozen() def get_snap_threshold(self): return self._snap_threshold def _set_nothing(self): self._filled = False def _set_custom_marker(self, path): verts = path.vertices rescale = max(np.max(np.abs(verts[:, 0])), np.max(np.abs(verts[:, 1]))) self._transform = Affine2D().scale(1.0 / rescale) self._path = path def _set_path_marker(self): self._set_custom_marker(self._marker) def _set_vertices(self): verts = self._marker marker = Path(verts) self._set_custom_marker(marker) def _set_tuple_marker(self): marker = self._marker if is_numlike(marker[0]): if len(marker) == 2: numsides, rotation = marker[0], 0.0 elif len(marker) == 3: numsides, rotation = marker[0], marker[2] symstyle = marker[1] if symstyle == 0: self._path = Path.unit_regular_polygon(numsides) self._joinstyle = "miter" elif symstyle == 1: self._path = Path.unit_regular_star(numsides) self._joinstyle = "bevel" elif symstyle == 2: self._path = Path.unit_regular_asterisk(numsides) self._filled = False self._joinstyle = "bevel" elif symstyle == 3: self._path = Path.unit_circle() self._transform = Affine2D().scale(0.5).rotate_deg(rotation) else: verts = np.asarray(marker[0]) path = Path(verts) self._set_custom_marker(path) def _set_mathtext_path(self): """ Draws mathtext markers '$...$' using TextPath object. Submitted by tcb """ from matplotlib.text import TextPath from matplotlib.font_manager import FontProperties # again, the properties could be initialised just once outside # this function # Font size is irrelevant here, it will be rescaled based on # the drawn size later props = FontProperties(size=1.0) text = TextPath(xy=(0, 0), s=self.get_marker(), fontproperties=props, usetex=rcParams["text.usetex"]) if len(text.vertices) == 0: return xmin, ymin = text.vertices.min(axis=0) xmax, ymax = text.vertices.max(axis=0) width = xmax - xmin height = ymax - ymin max_dim = max(width, height) self._transform = Affine2D().translate(-xmin + 0.5 * -width, -ymin + 0.5 * -height).scale(1.0 / max_dim) self._path = text self._snap = False def _half_fill(self): fs = self.get_fillstyle() result = fs in self._half_fillstyles return result def _set_circle(self, reduction=1.0): self._transform = Affine2D().scale(0.5 * reduction) self._snap_threshold = 6.0 fs = self.get_fillstyle() if not self._half_fill(): self._path = Path.unit_circle() else: # build a right-half circle if fs == "bottom": rotate = 270.0 elif fs == "top": rotate = 90.0 elif fs == "left": rotate = 180.0 else: rotate = 0.0 self._path = self._alt_path = Path.unit_circle_righthalf() self._transform.rotate_deg(rotate) self._alt_transform = self._transform.frozen().rotate_deg(180.0) def _set_pixel(self): self._path = Path.unit_rectangle() # Ideally, you'd want -0.5, -0.5 here, but then the snapping # algorithm in the Agg backend will round this to a 2x2 # rectangle from (-1, -1) to (1, 1). By offsetting it # slightly, we can force it to be (0, 0) to (1, 1), which both # makes it only be a single pixel and places it correctly # aligned to 1-width stroking (i.e. the ticks). This hack is # the best of a number of bad alternatives, mainly because the # backends are not aware of what marker is actually being used # beyond just its path data. self._transform = Affine2D().translate(-0.49999, -0.49999) self._snap_threshold = None def _set_point(self): self._set_circle(reduction=self._point_size_reduction) _triangle_path = Path( [[0.0, 1.0], [-1.0, -1.0], [1.0, -1.0], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] ) # Going down halfway looks to small. Golden ratio is too far. _triangle_path_u = Path( [[0.0, 1.0], [-3 / 5.0, -1 / 5.0], [3 / 5.0, -1 / 5.0], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY], ) _triangle_path_d = Path( [[-3 / 5.0, -1 / 5.0], [3 / 5.0, -1 / 5.0], [1.0, -1.0], [-1.0, -1.0], [-3 / 5.0, -1 / 5.0]], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY], ) _triangle_path_l = Path( [[0.0, 1.0], [0.0, -1.0], [-1.0, -1.0], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] ) _triangle_path_r = Path( [[0.0, 1.0], [0.0, -1.0], [1.0, -1.0], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] ) def _set_triangle(self, rot, skip): self._transform = Affine2D().scale(0.5, 0.5).rotate_deg(rot) self._snap_threshold = 5.0 fs = self.get_fillstyle() if not self._half_fill(): self._path = self._triangle_path else: mpaths = [self._triangle_path_u, self._triangle_path_l, self._triangle_path_d, self._triangle_path_r] if fs == "top": self._path = mpaths[(0 + skip) % 4] self._alt_path = mpaths[(2 + skip) % 4] elif fs == "bottom": self._path = mpaths[(2 + skip) % 4] self._alt_path = mpaths[(0 + skip) % 4] elif fs == "left": self._path = mpaths[(1 + skip) % 4] self._alt_path = mpaths[(3 + skip) % 4] else: self._path = mpaths[(3 + skip) % 4] self._alt_path = mpaths[(1 + skip) % 4] self._alt_transform = self._transform self._joinstyle = "miter" def _set_triangle_up(self): return self._set_triangle(0.0, 0) def _set_triangle_down(self): return self._set_triangle(180.0, 2) def _set_triangle_left(self): return self._set_triangle(90.0, 3) def _set_triangle_right(self): return self._set_triangle(270.0, 1) def _set_square(self): self._transform = Affine2D().translate(-0.5, -0.5) self._snap_threshold = 2.0 fs = self.get_fillstyle() if not self._half_fill(): self._path = Path.unit_rectangle() else: # build a bottom filled square out of two rectangles, one # filled. Use the rotation to support left, right, bottom # or top if fs == "bottom": rotate = 0.0 elif fs == "top": rotate = 180.0 elif fs == "left": rotate = 270.0 else: rotate = 90.0 self._path = Path([[0.0, 0.0], [1.0, 0.0], [1.0, 0.5], [0.0, 0.5], [0.0, 0.0]]) self._alt_path = Path([[0.0, 0.5], [1.0, 0.5], [1.0, 1.0], [0.0, 1.0], [0.0, 0.5]]) self._transform.rotate_deg(rotate) self._alt_transform = self._transform self._joinstyle = "miter" def _set_diamond(self): self._transform = Affine2D().translate(-0.5, -0.5).rotate_deg(45) self._snap_threshold = 5.0 fs = self.get_fillstyle() if not self._half_fill(): self._path = Path.unit_rectangle() else: self._path = Path([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 0.0]]) self._alt_path = Path([[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.0, 0.0]]) if fs == "bottom": rotate = 270.0 elif fs == "top": rotate = 90.0 elif fs == "left": rotate = 180.0 else: rotate = 0.0 self._transform.rotate_deg(rotate) self._alt_transform = self._transform self._joinstyle = "miter" def _set_thin_diamond(self): self._set_diamond() self._transform.scale(0.6, 1.0) def _set_pentagon(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0 polypath = Path.unit_regular_polygon(5) fs = self.get_fillstyle() if not self._half_fill(): self._path = polypath else: verts = polypath.vertices y = (1 + np.sqrt(5)) / 4.0 top = Path([verts[0], verts[1], verts[4], verts[0]]) bottom = Path([verts[1], verts[2], verts[3], verts[4], verts[1]]) left = Path([verts[0], verts[1], verts[2], [0, -y], verts[0]]) right = Path([verts[0], verts[4], verts[3], [0, -y], verts[0]]) if fs == "top": mpath, mpath_alt = top, bottom elif fs == "bottom": mpath, mpath_alt = bottom, top elif fs == "left": mpath, mpath_alt = left, right else: mpath, mpath_alt = right, left self._path = mpath self._alt_path = mpath_alt self._alt_transform = self._transform self._joinstyle = "miter" def _set_star(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0 fs = self.get_fillstyle() polypath = Path.unit_regular_star(5, innerCircle=0.381966) if not self._half_fill(): self._path = polypath else: verts = polypath.vertices top = Path(np.vstack((verts[0:4, :], verts[7:10, :], verts[0]))) bottom = Path(np.vstack((verts[3:8, :], verts[3]))) left = Path(np.vstack((verts[0:6, :], verts[0]))) right = Path(np.vstack((verts[0], verts[5:10, :], verts[0]))) if fs == "top": mpath, mpath_alt = top, bottom elif fs == "bottom": mpath, mpath_alt = bottom, top elif fs == "left": mpath, mpath_alt = left, right else: mpath, mpath_alt = right, left self._path = mpath self._alt_path = mpath_alt self._alt_transform = self._transform self._joinstyle = "bevel" def _set_hexagon1(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0 fs = self.get_fillstyle() polypath = Path.unit_regular_polygon(6) if not self._half_fill(): self._path = polypath else: verts = polypath.vertices # not drawing inside lines x = np.abs(np.cos(5 * np.pi / 6.0)) top = Path(np.vstack(([-x, 0], verts[(1, 0, 5), :], [x, 0]))) bottom = Path(np.vstack(([-x, 0], verts[2:5, :], [x, 0]))) left = Path(verts[(0, 1, 2, 3), :]) right = Path(verts[(0, 5, 4, 3), :]) if fs == "top": mpath, mpath_alt = top, bottom elif fs == "bottom": mpath, mpath_alt = bottom, top elif fs == "left": mpath, mpath_alt = left, right else: mpath, mpath_alt = right, left self._path = mpath self._alt_path = mpath_alt self._alt_transform = self._transform self._joinstyle = "miter" def _set_hexagon2(self): self._transform = Affine2D().scale(0.5).rotate_deg(30) self._snap_threshold = 5.0 fs = self.get_fillstyle() polypath = Path.unit_regular_polygon(6) if not self._half_fill(): self._path = polypath else: verts = polypath.vertices # not drawing inside lines x, y = np.sqrt(3) / 4, 3 / 4.0 top = Path(verts[(1, 0, 5, 4, 1), :]) bottom = Path(verts[(1, 2, 3, 4), :]) left = Path(np.vstack(([x, y], verts[(0, 1, 2), :], [-x, -y], [x, y]))) right = Path(np.vstack(([x, y], verts[(5, 4, 3), :], [-x, -y]))) if fs == "top": mpath, mpath_alt = top, bottom elif fs == "bottom": mpath, mpath_alt = bottom, top elif fs == "left": mpath, mpath_alt = left, right else: mpath, mpath_alt = right, left self._path = mpath self._alt_path = mpath_alt self._alt_transform = self._transform self._joinstyle = "miter" def _set_octagon(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0 fs = self.get_fillstyle() polypath = Path.unit_regular_polygon(8) if not self._half_fill(): self._transform.rotate_deg(22.5) self._path = polypath else: x = np.sqrt(2.0) / 4.0 half = Path([[0, -1], [0, 1], [-x, 1], [-1, x], [-1, -x], [-x, -1], [0, -1]]) if fs == "bottom": rotate = 90.0 elif fs == "top": rotate = 270.0 elif fs == "right": rotate = 180.0 else: rotate = 0.0 self._transform.rotate_deg(rotate) self._path = self._alt_path = half self._alt_transform = self._transform.frozen().rotate_deg(180.0) self._joinstyle = "miter" _line_marker_path = Path([[0.0, -1.0], [0.0, 1.0]]) def _set_vline(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 1.0 self._filled = False self._path = self._line_marker_path def _set_hline(self): self._transform = Affine2D().scale(0.5).rotate_deg(90) self._snap_threshold = 1.0 self._filled = False self._path = self._line_marker_path _tickhoriz_path = Path([[0.0, 0.0], [1.0, 0.0]]) def _set_tickleft(self): self._transform = Affine2D().scale(-1.0, 1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickhoriz_path def _set_tickright(self): self._transform = Affine2D().scale(1.0, 1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickhoriz_path _tickvert_path = Path([[-0.0, 0.0], [-0.0, 1.0]]) def _set_tickup(self): self._transform = Affine2D().scale(1.0, 1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickvert_path def _set_tickdown(self): self._transform = Affine2D().scale(1.0, -1.0) self._snap_threshold = 1.0 self._filled = False self._path = self._tickvert_path _plus_path = Path( [[-1.0, 0.0], [1.0, 0.0], [0.0, -1.0], [0.0, 1.0]], [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO] ) def _set_plus(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 1.0 self._filled = False self._path = self._plus_path _tri_path = Path( [[0.0, 0.0], [0.0, -1.0], [0.0, 0.0], [0.8, 0.5], [0.0, 0.0], [-0.8, 0.5]], [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO], ) def _set_tri_down(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 5.0 self._filled = False self._path = self._tri_path def _set_tri_up(self): self._transform = Affine2D().scale(0.5).rotate_deg(90) self._snap_threshold = 5.0 self._filled = False self._path = self._tri_path def _set_tri_left(self): self._transform = Affine2D().scale(0.5).rotate_deg(270) self._snap_threshold = 5.0 self._filled = False self._path = self._tri_path def _set_tri_right(self): self._transform = Affine2D().scale(0.5).rotate_deg(180) self._snap_threshold = 5.0 self._filled = False self._path = self._tri_path _caret_path = Path([[-1.0, 1.5], [0.0, 0.0], [1.0, 1.5]]) def _set_caretdown(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 3.0 self._filled = False self._path = self._caret_path self._joinstyle = "miter" def _set_caretup(self): self._transform = Affine2D().scale(0.5).rotate_deg(180) self._snap_threshold = 3.0 self._filled = False self._path = self._caret_path self._joinstyle = "miter" def _set_caretleft(self): self._transform = Affine2D().scale(0.5).rotate_deg(270) self._snap_threshold = 3.0 self._filled = False self._path = self._caret_path self._joinstyle = "miter" def _set_caretright(self): self._transform = Affine2D().scale(0.5).rotate_deg(90) self._snap_threshold = 3.0 self._filled = False self._path = self._caret_path self._joinstyle = "miter" _x_path = Path( [[-1.0, -1.0], [1.0, 1.0], [-1.0, 1.0], [1.0, -1.0]], [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO] ) def _set_x(self): self._transform = Affine2D().scale(0.5) self._snap_threshold = 3.0 self._filled = False self._path = self._x_path
class Artist(object): """ Abstract base class for someone who renders into a :class:`FigureCanvas`. """ aname = 'Artist' zorder = 0 def __init__(self): self.figure = None self._transform = None self._transformSet = False self._visible = True self._animated = False self._alpha = None self.clipbox = None self._clippath = None self._clipon = True self._lod = False self._label = '' self._picker = None self._contains = None self._rasterized = None self._agg_filter = None self.eventson = False # fire events only if eventson self._oid = 0 # an observer id self._propobservers = {} # a dict from oids to funcs try: self.axes = None except AttributeError: # Handle self.axes as a read-only property, as in Figure. pass self._remove_method = None self._url = None self._gid = None self._snap = None self._sketch = rcParams['path.sketch'] self._path_effects = rcParams['path.effects'] def __getstate__(self): d = self.__dict__.copy() # remove the unpicklable remove method, this will get re-added on load # (by the axes) if the artist lives on an axes. d['_remove_method'] = None return d def remove(self): """ Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with :meth:`matplotlib.axes.Axes.draw_idle`. Call :meth:`matplotlib.axes.Axes.relim` to update the axes limits if desired. Note: :meth:`~matplotlib.axes.Axes.relim` will not see collections even if the collection was added to axes with *autolim* = True. Note: there is no support for removing the artist's legend entry. """ # There is no method to set the callback. Instead the parent should # set the _remove_method attribute directly. This would be a # protected attribute if Python supported that sort of thing. The # callback has one parameter, which is the child to be removed. if self._remove_method is not None: self._remove_method(self) else: raise NotImplementedError('cannot remove artist') # TODO: the fix for the collections relim problem is to move the # limits calculation into the artist itself, including the property of # whether or not the artist should affect the limits. Then there will # be no distinction between axes.add_line, axes.add_patch, etc. # TODO: add legend support def have_units(self): 'Return *True* if units are set on the *x* or *y* axes' ax = self.axes if ax is None or ax.xaxis is None: return False return ax.xaxis.have_units() or ax.yaxis.have_units() def convert_xunits(self, x): """For artists in an axes, if the xaxis has units support, convert *x* using xaxis unit type """ ax = getattr(self, 'axes', None) if ax is None or ax.xaxis is None: #print 'artist.convert_xunits no conversion: ax=%s'%ax return x return ax.xaxis.convert_units(x) def convert_yunits(self, y): """For artists in an axes, if the yaxis has units support, convert *y* using yaxis unit type """ ax = getattr(self, 'axes', None) if ax is None or ax.yaxis is None: return y return ax.yaxis.convert_units(y) def set_axes(self, axes): """ Set the :class:`~matplotlib.axes.Axes` instance in which the artist resides, if any. ACCEPTS: an :class:`~matplotlib.axes.Axes` instance """ self.axes = axes def get_axes(self): """ Return the :class:`~matplotlib.axes.Axes` instance the artist resides in, or *None* """ return self.axes def get_window_extent(self, renderer): """ Get the axes bounding box in display space. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. """ return Bbox([[0, 0], [0, 0]]) def add_callback(self, func): """ Adds a callback function that will be called whenever one of the :class:`Artist`'s properties changes. Returns an *id* that is useful for removing the callback with :meth:`remove_callback` later. """ oid = self._oid self._propobservers[oid] = func self._oid += 1 return oid def remove_callback(self, oid): """ Remove a callback based on its *id*. .. seealso:: :meth:`add_callback` For adding callbacks """ try: del self._propobservers[oid] except KeyError: pass def pchanged(self): """ Fire an event when property changed, calling all of the registered callbacks. """ for oid, func in self._propobservers.iteritems(): func(self) def is_transform_set(self): """ Returns *True* if :class:`Artist` has a transform explicitly set. """ return self._transformSet def set_transform(self, t): """ Set the :class:`~matplotlib.transforms.Transform` instance used by this artist. ACCEPTS: :class:`~matplotlib.transforms.Transform` instance """ self._transform = t self._transformSet = True self.pchanged() def get_transform(self): """ Return the :class:`~matplotlib.transforms.Transform` instance used by this artist. """ if self._transform is None: self._transform = IdentityTransform() elif (not isinstance(self._transform, Transform) and hasattr(self._transform, '_as_mpl_transform')): self._transform = self._transform._as_mpl_transform(self.axes) return self._transform def hitlist(self, event): """ List the children of the artist which contain the mouse event *event*. """ L = [] try: hascursor, info = self.contains(event) if hascursor: L.append(self) except: import traceback traceback.print_exc() print("while checking", self.__class__) for a in self.get_children(): L.extend(a.hitlist(event)) return L def get_children(self): """ Return a list of the child :class:`Artist`s this :class:`Artist` contains. """ return [] def contains(self, mouseevent): """Test whether the artist contains the mouse event. Returns the truth value and a dictionary of artist specific details of selection, such as which points are contained in the pick radius. See individual artists for details. """ if callable(self._contains): return self._contains(self, mouseevent) warnings.warn("'%s' needs 'contains' method" % self.__class__.__name__) return False, {} def set_contains(self, picker): """ Replace the contains test used by this artist. The new picker should be a callable function which determines whether the artist is hit by the mouse event:: hit, props = picker(artist, mouseevent) If the mouse event is over the artist, return *hit* = *True* and *props* is a dictionary of properties you want returned with the contains test. ACCEPTS: a callable function """ self._contains = picker def get_contains(self): """ Return the _contains test used by the artist, or *None* for default. """ return self._contains def pickable(self): 'Return *True* if :class:`Artist` is pickable.' return (self.figure is not None and self.figure.canvas is not None and self._picker is not None) def pick(self, mouseevent): """ call signature:: pick(mouseevent) each child artist will fire a pick event if *mouseevent* is over the artist and the artist has picker set """ # Pick self if self.pickable(): picker = self.get_picker() if callable(picker): inside, prop = picker(self, mouseevent) else: inside, prop = self.contains(mouseevent) if inside: self.figure.canvas.pick_event(mouseevent, self, **prop) # Pick children for a in self.get_children(): # make sure the event happened in the same axes ax = getattr(a, 'axes', None) if mouseevent.inaxes is None or mouseevent.inaxes == ax: # we need to check if mouseevent.inaxes is None # because some objects associated with an axes (e.g., a # tick label) can be outside the bounding box of the # axes and inaxes will be None a.pick(mouseevent) def set_picker(self, picker): """ Set the epsilon for picking used by this artist *picker* can be one of the following: * *None*: picking is disabled for this artist (default) * A boolean: if *True* then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist * A float: if picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if it's data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event * A function: if picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event:: hit, props = picker(artist, mouseevent) to determine the hit test. if the mouse event is over the artist, return *hit=True* and props is a dictionary of properties you want added to the PickEvent attributes. ACCEPTS: [None|float|boolean|callable] """ self._picker = picker def get_picker(self): 'Return the picker object used by this artist' return self._picker def is_figure_set(self): """ Returns True if the artist is assigned to a :class:`~matplotlib.figure.Figure`. """ return self.figure is not None def get_url(self): """ Returns the url """ return self._url def set_url(self, url): """ Sets the url for the artist ACCEPTS: a url string """ self._url = url def get_gid(self): """ Returns the group id """ return self._gid def set_gid(self, gid): """ Sets the (group) id for the artist ACCEPTS: an id string """ self._gid = gid def get_snap(self): """ Returns the snap setting which may be: * True: snap vertices to the nearest pixel center * False: leave vertices as-is * None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center Only supported by the Agg and MacOSX backends. """ if rcParams['path.snap']: return self._snap else: return False def set_snap(self, snap): """ Sets the snap setting which may be: * True: snap vertices to the nearest pixel center * False: leave vertices as-is * None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center Only supported by the Agg and MacOSX backends. """ self._snap = snap def get_sketch_params(self): """ Returns the sketch parameters for the artist. Returns ------- sketch_params : tuple or `None` A 3-tuple with the following elements: * `scale`: The amplitude of the wiggle perpendicular to the source line. * `length`: The length of the wiggle along the line. * `randomness`: The scale factor by which the length is shrunken or expanded. May return `None` if no sketch parameters were set. """ return self._sketch def set_sketch_params(self, scale=None, length=None, randomness=None): """ Sets the the sketch parameters. Parameters ---------- scale : float, optional The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is `None`, or not provided, no sketch filter will be provided. length : float, optional The length of the wiggle along the line, in pixels (default 128.0) randomness : float, optional The scale factor by which the length is shrunken or expanded (default 16.0) """ if scale is None: self._sketch = None else: self._sketch = (scale, length or 128.0, randomness or 16.0) def set_path_effects(self, path_effects): """ set path_effects, which should be a list of instances of matplotlib.patheffect._Base class or its derivatives. """ self._path_effects = path_effects def get_path_effects(self): return self._path_effects def get_figure(self): """ Return the :class:`~matplotlib.figure.Figure` instance the artist belongs to. """ return self.figure def set_figure(self, fig): """ Set the :class:`~matplotlib.figure.Figure` instance the artist belongs to. ACCEPTS: a :class:`matplotlib.figure.Figure` instance """ self.figure = fig self.pchanged() def set_clip_box(self, clipbox): """ Set the artist's clip :class:`~matplotlib.transforms.Bbox`. ACCEPTS: a :class:`matplotlib.transforms.Bbox` instance """ self.clipbox = clipbox self.pchanged() def set_clip_path(self, path, transform=None): """ Set the artist's clip path, which may be: * a :class:`~matplotlib.patches.Patch` (or subclass) instance * a :class:`~matplotlib.path.Path` instance, in which case an optional :class:`~matplotlib.transforms.Transform` instance may be provided, which will be applied to the path before using it for clipping. * *None*, to remove the clipping path For efficiency, if the path happens to be an axis-aligned rectangle, this method will set the clipping box to the corresponding rectangle and set the clipping path to *None*. ACCEPTS: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] """ from matplotlib.patches import Patch, Rectangle success = False if transform is None: if isinstance(path, Rectangle): self.clipbox = TransformedBbox(Bbox.unit(), path.get_transform()) self._clippath = None success = True elif isinstance(path, Patch): self._clippath = TransformedPath(path.get_path(), path.get_transform()) success = True elif isinstance(path, tuple): path, transform = path if path is None: self._clippath = None success = True elif isinstance(path, Path): self._clippath = TransformedPath(path, transform) success = True elif isinstance(path, TransformedPath): self._clippath = path success = True if not success: print(type(path), type(transform)) raise TypeError("Invalid arguments to set_clip_path") self.pchanged() def get_alpha(self): """ Return the alpha value used for blending - not supported on all backends """ return self._alpha def get_visible(self): "Return the artist's visiblity" return self._visible def get_animated(self): "Return the artist's animated state" return self._animated def get_clip_on(self): 'Return whether artist uses clipping' return self._clipon def get_clip_box(self): 'Return artist clipbox' return self.clipbox def get_clip_path(self): 'Return artist clip path' return self._clippath def get_transformed_clip_path_and_affine(self): ''' Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation. ''' if self._clippath is not None: return self._clippath.get_transformed_path_and_affine() return None, None def set_clip_on(self, b): """ Set whether artist uses clipping. ACCEPTS: [True | False] """ self._clipon = b self.pchanged() def _set_gc_clip(self, gc): 'Set the clip properly for the gc' if self._clipon: if self.clipbox is not None: gc.set_clip_rectangle(self.clipbox) gc.set_clip_path(self._clippath) else: gc.set_clip_rectangle(None) gc.set_clip_path(None) def get_rasterized(self): "return True if the artist is to be rasterized" return self._rasterized def set_rasterized(self, rasterized): """ Force rasterized (bitmap) drawing in vector backend output. Defaults to None, which implies the backend's default behavior ACCEPTS: [True | False | None] """ if rasterized and not hasattr(self.draw, "_supports_rasterization"): warnings.warn("Rasterization of '%s' will be ignored" % self) self._rasterized = rasterized def get_agg_filter(self): "return filter function to be used for agg filter" return self._agg_filter def set_agg_filter(self, filter_func): """ set agg_filter fuction. """ self._agg_filter = filter_func def draw(self, renderer, *args, **kwargs): 'Derived classes drawing method' if not self.get_visible(): return def set_alpha(self, alpha): """ Set the alpha value used for blending - not supported on all backends. ACCEPTS: float (0.0 transparent through 1.0 opaque) """ self._alpha = alpha self.pchanged() def set_lod(self, on): """ Set Level of Detail on or off. If on, the artists may examine things like the pixel width of the axes and draw a subset of their contents accordingly ACCEPTS: [True | False] """ self._lod = on self.pchanged() def set_visible(self, b): """ Set the artist's visiblity. ACCEPTS: [True | False] """ self._visible = b self.pchanged() def set_animated(self, b): """ Set the artist's animation state. ACCEPTS: [True | False] """ self._animated = b self.pchanged() def update(self, props): """ Update the properties of this :class:`Artist` from the dictionary *prop*. """ store = self.eventson self.eventson = False changed = False for k, v in props.iteritems(): func = getattr(self, 'set_' + k, None) if func is None or not callable(func): raise AttributeError('Unknown property %s' % k) func(v) changed = True self.eventson = store if changed: self.pchanged() def get_label(self): """ Get the label used for this artist in the legend. """ return self._label def set_label(self, s): """ Set the label to *s* for auto legend. ACCEPTS: string or anything printable with '%s' conversion. """ if s is not None: self._label = '%s' % (s, ) else: self._label = None self.pchanged() def get_zorder(self): """ Return the :class:`Artist`'s zorder. """ return self.zorder def set_zorder(self, level): """ Set the zorder for the artist. Artists with lower zorder values are drawn first. ACCEPTS: any number """ self.zorder = level self.pchanged() def update_from(self, other): 'Copy properties from *other* to *self*.' self._transform = other._transform self._transformSet = other._transformSet self._visible = other._visible self._alpha = other._alpha self.clipbox = other.clipbox self._clipon = other._clipon self._clippath = other._clippath self._lod = other._lod self._label = other._label self._sketch = other._sketch self._path_effects = other._path_effects self.pchanged() def properties(self): """ return a dictionary mapping property name -> value for all Artist props """ return ArtistInspector(self).properties() def set(self, **kwargs): """ A tkstyle set command, pass *kwargs* to set properties """ ret = [] for k, v in kwargs.iteritems(): k = k.lower() funcName = "set_%s" % k func = getattr(self, funcName) ret.extend([func(v)]) return ret def findobj(self, match=None, include_self=True): """ Find artist objects. Recursively find all :class:`~matplotlib.artist.Artist` instances contained in self. *match* can be - None: return all objects contained in artist. - function with signature ``boolean = match(artist)`` used to filter matches - class instance: e.g., Line2D. Only return artists of class type. If *include_self* is True (default), include self in the list to be checked for a match. """ if match is None: # always return True def matchfunc(x): return True elif cbook.issubclass_safe(match, Artist): def matchfunc(x): return isinstance(x, match) elif callable(match): matchfunc = match else: raise ValueError('match must be None, a matplotlib.artist.Artist ' 'subclass, or a callable') artists = [] for c in self.get_children(): if matchfunc(c): artists.append(c) artists.extend([ thisc for thisc in c.findobj(matchfunc, include_self=False) if matchfunc(thisc) ]) if include_self and matchfunc(self): artists.append(self) return artists
def get_transform(self): 'return the Transformation instance used by this artist' if self._transform is None: self._transform = IdentityTransform() return self._transform