""" This module contains all the 2D line class which can draw with a variety of line styles, markers and colors. """
# TODO: expose cap and join style attrs
_to_unmasked_float_array, iterable, ls_mapper, ls_mapper_r, STEP_LOOKUP_MAP)
# Imported here for backward compatibility, even though they don't # really belong. CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN, CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE, TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN)
"""Convert linestyle -> dash pattern """ # go from short hand -> full strings # un-dashed styles # dashed styles # offset, dashes = style else: raise ValueError('Unrecognized linestyle: %s' % str(style))
# normalize offset to be positive and shorter than the dash cycle
return offset, dashes
for x in dashes]
""" Determine if any line segments are within radius of a point. Returns the list of line segments that are within that radius. """ # Process single points specially if len(x) < 2: res, = np.nonzero((cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2) return res
# We need to lop the last element off a lot. xr, yr = x[:-1], y[:-1]
# Only look at line segments whose nearest point to C on the line # lies within the segment. dx, dy = x[1:] - xr, y[1:] - yr Lnorm_sq = dx ** 2 + dy ** 2 # Possibly want to eliminate Lnorm==0 u = ((cx - xr) * dx + (cy - yr) * dy) / Lnorm_sq candidates = (u >= 0) & (u <= 1)
# Note that there is a little area near one side of each point # which will be near neither segment, and another which will # be near both, depending on the angle of the lines. The # following radius test eliminates these ambiguities. point_hits = (cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2 candidates = candidates & ~(point_hits[:-1] | point_hits[1:])
# For those candidates which remain, determine how far they lie away # from the line. px, py = xr + u * dx, yr + u * dy line_hits = (cx - px) ** 2 + (cy - py) ** 2 <= radius ** 2 line_hits = line_hits & candidates points, = point_hits.ravel().nonzero() lines, = line_hits.ravel().nonzero() return np.concatenate((points, lines))
""" Helper function that sorts out how to deal the input `markevery` and returns the points where markers should be drawn.
Takes in the `markevery` value and the line path and returns the sub-sampled path. """ # pull out the two bits of data we want from the path codes, verts = tpath.codes, tpath.vertices
def _slice_or_none(in_v, slc): ''' Helper function to cope with `codes` being an ndarray or `None` ''' if in_v is None: return None return in_v[slc]
# if just an int, assume starting at 0 and make a tuple if isinstance(markevery, Integral): markevery = (0, markevery) # if just a float, assume starting at 0.0 and make a tuple elif isinstance(markevery, Real): markevery = (0.0, markevery)
if isinstance(markevery, tuple): if len(markevery) != 2: raise ValueError('`markevery` is a tuple but its len is not 2; ' 'markevery={}'.format(markevery)) start, step = markevery # if step is an int, old behavior if isinstance(step, Integral): # tuple of 2 int is for backwards compatibility, if not isinstance(start, Integral): raise ValueError( '`markevery` is a tuple with len 2 and second element is ' 'an int, but the first element is not an int; markevery={}' .format(markevery)) # just return, we are done here
return Path(verts[slice(start, None, step)], _slice_or_none(codes, slice(start, None, step)))
elif isinstance(step, Real): if not isinstance(start, Real): raise ValueError( '`markevery` is a tuple with len 2 and second element is ' 'a float, but the first element is not a float or an int; ' 'markevery={}'.format(markevery)) # calc cumulative distance along path (in display coords): disp_coords = affine.transform(tpath.vertices) delta = np.empty((len(disp_coords), 2)) delta[0, :] = 0 delta[1:, :] = disp_coords[1:, :] - disp_coords[:-1, :] delta = np.sum(delta**2, axis=1) delta = np.sqrt(delta) delta = np.cumsum(delta) # calc distance between markers along path based on the axes # bounding box diagonal being a distance of unity: scale = ax_transform.transform(np.array([[0, 0], [1, 1]])) scale = np.diff(scale, axis=0) scale = np.sum(scale**2) scale = np.sqrt(scale) marker_delta = np.arange(start * scale, delta[-1], step * scale) # find closest actual data point that is closest to # the theoretical distance along the path: inds = np.abs(delta[np.newaxis, :] - marker_delta[:, np.newaxis]) inds = inds.argmin(axis=1) inds = np.unique(inds) # return, we are done here return Path(verts[inds], _slice_or_none(codes, inds)) else: raise ValueError( '`markevery` is a tuple with len 2, but its second element is ' 'not an int or a float; markevery=%s' % (markevery,))
elif isinstance(markevery, slice): # mazol tov, it's already a slice, just return return Path(verts[markevery], _slice_or_none(codes, markevery))
elif iterable(markevery): #fancy indexing try: return Path(verts[markevery], _slice_or_none(codes, markevery))
except (ValueError, IndexError): raise ValueError('`markevery` is iterable but ' 'not a valid form of numpy fancy indexing; ' 'markevery=%s' % (markevery,)) else: raise ValueError('Value of `markevery` is not ' 'recognized; ' 'markevery=%s' % (markevery,))
"antialiased": ["aa"], "color": ["c"], "linestyle": ["ls"], "linewidth": ["lw"], "markeredgecolor": ["mec"], "markeredgewidth": ["mew"], "markerfacecolor": ["mfc"], "markerfacecoloralt": ["mfcalt"], "markersize": ["ms"], }) """ A line - the line can have both a solid linestyle connecting all the vertices, and a marker at each vertex. Additionally, the drawing of the solid line is influenced by the drawstyle, e.g., one can create "stepped" lines in various styles. """
'-': '_draw_solid', '--': '_draw_dashed', '-.': '_draw_dash_dot', ':': '_draw_dotted', 'None': '_draw_nothing', ' ': '_draw_nothing', '': '_draw_nothing', }
'default': '_draw_lines', 'steps-mid': '_draw_steps_mid', 'steps-pre': '_draw_steps_pre', 'steps-post': '_draw_steps_post', }
'steps': '_draw_steps_pre', }
# drawStyles should now be deprecated. # Need a list ordered with long names first:
# Referenced here to maintain API. These are defined in # MarkerStyle
def __str__(self): if self._label != "": return "Line2D(%s)" % (self._label) elif self._x is None: return "Line2D()" elif len(self._x) > 3: return "Line2D((%g,%g),(%g,%g),...,(%g,%g))"\ % (self._x[0], self._y[0], self._x[0], self._y[0], self._x[-1], self._y[-1]) else: return "Line2D(%s)"\ % (",".join(["(%g,%g)" % (x, y) for x, y in zip(self._x, self._y)]))
linewidth=None, # all Nones default to rc linestyle=None, color=None, marker=None, markersize=None, markeredgewidth=None, markeredgecolor=None, markerfacecolor=None, markerfacecoloralt='none', fillstyle=None, antialiased=None, dash_capstyle=None, solid_capstyle=None, dash_joinstyle=None, solid_joinstyle=None, pickradius=5, drawstyle=None, markevery=None, **kwargs ): """ Create a :class:`~matplotlib.lines.Line2D` instance with *x* and *y* data in sequences *xdata*, *ydata*.
The kwargs are :class:`~matplotlib.lines.Line2D` properties:
%(Line2D)s
See :meth:`set_linestyle` for a description of the line styles, :meth:`set_marker` for a description of the markers, and :meth:`set_drawstyle` for a description of the draw styles.
"""
#convert sequences to numpy arrays raise RuntimeError('xdata must be a sequence') raise RuntimeError('ydata must be a sequence')
raise ValueError("Inconsistent drawstyle ({!r}) and linestyle " "({!r})".format(drawstyle, linestyle))
drawstyle = ds
# scaled dash + offset # unscaled dash + offset # this is needed scaling the dash pattern by linewidth
# update kwargs before updating data to give the caller a # chance to init axes (and hence unit support) self.pickradius = self._picker
""" Test whether the mouse event occurred on the line. The pick radius determines the precision of the location test (usually within five points of the value). Use :meth:`~matplotlib.lines.Line2D.get_pickradius` or :meth:`~matplotlib.lines.Line2D.set_pickradius` to view or modify it.
Returns *True* if any values are within the radius along with ``{'ind': pointlist}``, where *pointlist* is the set of points within the radius.
TODO: sort returned indices by distance """ if callable(self._contains): return self._contains(self, mouseevent)
if not isinstance(self.pickradius, Number): raise ValueError("pick radius should be a distance")
# Make sure we have data to plot if self._invalidy or self._invalidx: self.recache() if len(self._xy) == 0: return False, {}
# Convert points to pixels transformed_path = self._get_transformed_path() path, affine = transformed_path.get_transformed_path_and_affine() path = affine.transform_path(path) xy = path.vertices xt = xy[:, 0] yt = xy[:, 1]
# Convert pick radius from points to pixels if self.figure is None: warnings.warn('no figure set when check if mouse is on line') pixels = self.pickradius else: pixels = self.figure.dpi / 72. * self.pickradius
# the math involved in checking for containment (here and inside of # segment_hits) assumes that it is OK to overflow. In case the # application has set the error flags such that an exception is raised # on overflow, we temporarily set the appropriate error flags here and # set them back when we are finished. with np.errstate(all='ignore'): # Check for collision if self._linestyle in ['None', None]: # If no line, return the nearby point(s) d = (xt - mouseevent.x) ** 2 + (yt - mouseevent.y) ** 2 ind, = np.nonzero(np.less_equal(d, pixels ** 2)) else: # If line, return the nearby segment(s) ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels) if self._drawstyle.startswith("steps"): ind //= 2
ind += self.ind_offset
# Return the point(s) within radius return len(ind) > 0, dict(ind=ind)
"""return the pick radius used for containment tests""" return self.pickradius
"""Set the pick radius used for containment tests.
Parameters ---------- d : float Pick radius, in points. """ self.pickradius = d
""" return the marker fillstyle """
""" Set the marker fill style; 'full' means fill the whole marker. 'none' means no filling; other options are for half-filled markers.
Parameters ---------- fs : {'full', 'left', 'right', 'bottom', 'top', 'none'} """ self._marker.set_fillstyle(fs) self.stale = True
"""Set the markevery property to subsample the plot when using markers.
e.g., if `every=5`, every 5-th marker will be plotted.
Parameters ---------- every: None or int or (int, int) or slice or List[int] or float or \ (float, float) Which markers to plot.
- every=None, every point will be plotted. - every=N, every N-th marker will be plotted starting with marker 0. - every=(start, N), every N-th marker, starting at point start, will be plotted. - every=slice(start, end, N), every N-th marker, starting at point start, up to but not including point end, will be plotted. - every=[i, j, m, n], only markers at points i, j, m, and n will be plotted. - every=0.1, (i.e. a float) then markers will be spaced at approximately equal distances along the line; the distance along the line between markers is determined by multiplying the display-coordinate distance of the axes bounding-box diagonal by the value of every. - every=(0.5, 0.1) (i.e. a length-2 tuple of float), the same functionality as every=0.1 is exhibited but the first marker will be 0.5 multiplied by the display-cordinate-diagonal-distance along the line.
Notes ----- Setting the markevery property will only show markers at actual data points. When using float arguments to set the markevery property on irregularly spaced data, the markers will likely not appear evenly spaced because the actual data points do not coincide with the theoretical spacing between markers.
When using a start offset to specify the first marker, the offset will be from the first data point which may be different from the first the visible data point if the plot is zoomed in.
If zooming in on a plot when using float arguments then the actual data points that have markers will change because the distance between markers is always determined from the display-coordinates axes-bounding-box-diagonal regardless of the actual axes data limits.
""" self.stale = True
"""return the markevery setting"""
"""Sets the event picker details for the line.
Parameters ---------- p : float or callable[[Artist, Event], Tuple[bool, dict]] If a float, it is used as the pick radius in points. """ if callable(p): self._contains = p else: self.pickradius = p self._picker = p
bbox = Bbox([[0, 0], [0, 0]]) trans_data_to_xy = self.get_transform().transform bbox.update_from_data_xy(trans_data_to_xy(self.get_xydata()), ignore=True) # correct for marker size, if any if self._marker: ms = (self._markersize / 72.0 * self.figure.dpi) * 0.5 bbox = bbox.padded(ms) return bbox
def axes(self, ax): # call the set method from the base-class property # connect unit-related callbacks self.recache_always) self.recache_always)
""" Set the x and y data
ACCEPTS: 2D array (rows are x, y) or two 1D arrays """ x, y = args[0] else:
self.recache(always=True)
else: else:
self.axes.name == 'rectilinear' and self.axes.get_xscale() == 'linear' and self._markevery is None and self.get_clip_on() is True): self._x_filled = self._x.copy() indices = np.arange(len(x)) self._x_filled[nanmask] = np.interp(indices[nanmask], indices[~nanmask], self._x[~nanmask]) else:
else: _interpolation_steps=interpolation_steps)
""" Puts a TransformedPath instance at self._transformed_path; all invalidation of the transform is then handled by the TransformedPath instance. """ # Masked arrays are now handled by the Path class itself _interpolation_steps=self._path._interpolation_steps) else:
""" Return the :class:`~matplotlib.transforms.TransformedPath` instance of this line. """
""" set the Transformation instance used by this artist
Parameters ---------- t : matplotlib.transforms.Transform """
"""return True if x is sorted in ascending order""" # We don't handle the monotonically decreasing case.
def draw(self, renderer): """draw the Line with `renderer` unless visibility is False""" return
else:
from matplotlib.patheffects import PathEffectRenderer renderer = PathEffectRenderer(self.get_path_effects(), renderer)
.get_transformed_path_and_affine())
else: gc.set_sketch_params(*self.get_sketch_params())
self.get_markeredgecolor(), self._alpha) self._get_markerfacecolor(), self._alpha) self._get_markerfacecolor(alt=True), self._alpha) # If the edgecolor is "auto", it is set according to the *line* # color but inherits the alpha value of the *face* color, if any. and not cbook._str_lower_equal( self.get_markerfacecolor(), "none")): scale, length, randomness = self.get_sketch_params() gc.set_sketch_params(scale/2, length/2, 2*randomness)
# Markers *must* be drawn ignoring the drawstyle (but don't pay the # recaching if drawstyle is already "default"). with cbook._setattr_cm( self, _drawstyle="default", _transformed_path=None): self.recache() self._transform_path(subslice) tpath, affine = (self._get_transformed_path() .get_transformed_path_and_affine()) else: .get_transformed_path_and_affine())
# subsample the markers if markevery is not None subsampled = _mark_every_path(markevery, tpath, affine, self.axes.transAxes) else:
gc.set_linewidth(0) else: # Don't scale for pixels, and don't stroke them subsampled, affine.frozen(), fc_rgba)
alt_marker_trans = marker.get_alt_transform() alt_marker_trans = alt_marker_trans.scale(w) renderer.draw_markers( gc, alt_marker_path, alt_marker_trans, subsampled, affine.frozen(), fcalt_rgba)
return self._antialiased
return self._color
return self._linestyle
return self._linewidth
if self._marker.get_marker() in ('.', ','): return self._color if self._marker.is_filled() and self.get_fillstyle() != 'none': return 'k' # Bad hard-wired default... else:
return self._markeredgewidth
return 'none' else: else:
return self._get_markerfacecolor(alt=True)
return self._markersize
""" Return the xdata, ydata.
If *orig* is *True*, return the original data. """ return self.get_xdata(orig=orig), self.get_ydata(orig=orig)
""" Return the xdata.
If *orig* is *True*, return the original data, else the processed data. """ if orig: return self._xorig if self._invalidx: self.recache() return self._x
""" Return the ydata.
If *orig* is *True*, return the original data, else the processed data. """ if orig: return self._yorig if self._invalidy: self.recache() return self._y
""" Return the :class:`~matplotlib.path.Path` object associated with this line. """
""" Return the *xy* data as a Nx2 numpy array. """ if self._invalidy or self._invalidx: self.recache() return self._xy
""" Set whether to use antialiased rendering.
Parameters ---------- b : bool """
""" Set the color of the line
Parameters ---------- color : color """
""" Set the drawstyle of the plot
'default' connects the points with lines. The steps variants produce step-plots. 'steps' is equivalent to 'steps-pre' and is maintained for backward-compatibility.
Parameters ---------- drawstyle : {'default', 'steps', 'steps-pre', 'steps-mid', \ 'steps-post'} """ drawstyle = 'default' raise ValueError('Unrecognized drawstyle {!r}'.format(drawstyle)) # invalidate to trigger a recache of the path
""" Set the line width in points
Parameters ---------- w : float """
# rescale the dashes + offset self._us_dashOffset, self._us_dashSeq, self._linewidth)
'''Split drawstyle from linestyle string
If `ls` is only a drawstyle default to returning a linestyle of '-'.
Parameters ---------- ls : str The linestyle to be processed
Returns ------- ret_ds : str or None If the linestyle string does not contain a drawstyle prefix return None, otherwise return it.
ls : str The linestyle with the drawstyle (if any) stripped. ''' return ds, ls[len(ds):] or '-'
""" Set the linestyle of the line (also accepts drawstyles, e.g., ``'steps--'``)
=========================== ================= linestyle description =========================== ================= ``'-'`` or ``'solid'`` solid line ``'--'`` or ``'dashed'`` dashed line ``'-.'`` or ``'dashdot'`` dash-dotted line ``':'`` or ``'dotted'`` dotted line ``'None'`` draw nothing ``' '`` draw nothing ``''`` draw nothing =========================== =================
'steps' is equivalent to 'steps-pre' and is maintained for backward-compatibility.
Alternatively a dash tuple of the following form can be provided::
(offset, onoffseq),
where ``onoffseq`` is an even length tuple of on and off ink in points.
.. seealso::
:meth:`set_drawstyle` To set the drawing style (stepping) of the plot.
Parameters ---------- ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} The line style. """ self.set_drawstyle(ds)
try: ls = ls_mapper_r[ls] except KeyError: raise ValueError("Invalid linestyle {!r}; see docs of " "Line2D.set_linestyle for valid values" .format(ls)) else: self._linestyle = '--'
# get the unscaled dashes # compute the linewidth scaled dashes self._us_dashOffset, self._us_dashSeq, self._linewidth)
def set_marker(self, marker): """ Set the line marker.
Parameters ---------- marker: marker style See `~matplotlib.markers` for full description of possible arguments. """
""" Set the marker edge color.
Parameters ---------- ec : color """ ec = 'auto' or np.any(self._markeredgecolor != ec)):
""" Set the marker edge width in points.
Parameters ---------- ew : float """
""" Set the marker face color.
Parameters ---------- fc : color """ fc = 'auto'
""" Set the alternate marker face color.
Parameters ---------- fc : color """ fc = 'auto'
""" Set the marker size in points.
Parameters ---------- sz : float """
""" Set the data array for x.
Parameters ---------- x : 1D array """
""" Set the data array for y.
Parameters ---------- y : 1D array """
""" Set the dash sequence, sequence of dashes with on off ink in points. If seq is empty or if seq = (None, None), the linestyle will be set to solid.
Parameters ---------- seq : sequence of floats (on/off ink in points) or (None, None) """ if seq == (None, None) or len(seq) == 0: self.set_linestyle('-') else: self.set_linestyle((0, seq))
"""copy properties from other to self"""
other._marker.get_fillstyle())
""" Set the join style for dashed linestyles.
Parameters ---------- s : {'miter', 'round', 'bevel'} """ raise ValueError('set_dash_joinstyle passed "%s";\n' % (s,) + 'valid joinstyles are %s' % (self.validJoin,))
""" Set the join style for solid linestyles.
Parameters ---------- s : {'miter', 'round', 'bevel'} """ raise ValueError('set_solid_joinstyle passed "%s";\n' % (s,) + 'valid joinstyles are %s' % (self.validJoin,))
""" Get the join style for dashed linestyles """ return self._dashjoinstyle
""" Get the join style for solid linestyles """ return self._solidjoinstyle
""" Set the cap style for dashed linestyles.
Parameters ---------- s : {'butt', 'round', 'projecting'} """ raise ValueError('set_dash_capstyle passed "%s";\n' % (s,) + 'valid capstyles are %s' % (self.validCap,))
""" Set the cap style for solid linestyles.
Parameters ---------- s : {'butt', 'round', 'projecting'} """ raise ValueError('set_solid_capstyle passed "%s";\n' % (s,) + 'valid capstyles are %s' % (self.validCap,))
""" Get the cap style for dashed linestyles """ return self._dashcapstyle
""" Get the cap style for solid linestyles """ return self._solidcapstyle
'return True if line is dashstyle'
""" Manage the callbacks to maintain a list of selected vertices for :class:`matplotlib.lines.Line2D`. Derived classes should override :meth:`~matplotlib.lines.VertexSelector.process_selected` to do something with the picks.
Here is an example which highlights the selected verts with red circles::
import numpy as np import matplotlib.pyplot as plt import matplotlib.lines as lines
class HighlightSelected(lines.VertexSelector): def __init__(self, line, fmt='ro', **kwargs): lines.VertexSelector.__init__(self, line) self.markers, = self.axes.plot([], [], fmt, **kwargs)
def process_selected(self, ind, xs, ys): self.markers.set_data(xs, ys) self.canvas.draw()
fig, ax = plt.subplots() x, y = np.random.rand(2, 30) line, = ax.plot(x, y, 'bs-', picker=5)
selector = HighlightSelected(line) plt.show()
""" """ Initialize the class with a :class:`matplotlib.lines.Line2D` instance. The line should already be added to some :class:`matplotlib.axes.Axes` instance and should have the picker property set. """ if line.axes is None: raise RuntimeError('You must first add the line to the Axes')
if line.get_picker() is None: raise RuntimeError('You must first set the picker property ' 'of the line')
self.axes = line.axes self.line = line self.canvas = self.axes.figure.canvas self.cid = self.canvas.mpl_connect('pick_event', self.onpick)
self.ind = set()
""" Default "do nothing" implementation of the :meth:`process_selected` method.
*ind* are the indices of the selected vertices. *xs* and *ys* are the coordinates of the selected vertices. """ pass
"""When the line is picked, update the set of selected indices.""" if event.artist is not self.line: return self.ind ^= set(event.ind) ind = sorted(self.ind) xdata, ydata = self.line.get_data() self.process_selected(ind, xdata[ind], ydata[ind])
# You can not set the docstring of an instancemethod, # but you can on the underlying function. Go figure. |