lines.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  1. """
  2. The 2D line class which can draw with a variety of line styles, markers and
  3. colors.
  4. """
  5. # TODO: expose cap and join style attrs
  6. from numbers import Integral, Number, Real
  7. import logging
  8. import numpy as np
  9. import matplotlib as mpl
  10. from . import artist, cbook, colors as mcolors, docstring, rcParams
  11. from .artist import Artist, allow_rasterization
  12. from .cbook import (
  13. _to_unmasked_float_array, ls_mapper, ls_mapper_r, STEP_LOOKUP_MAP)
  14. from .markers import MarkerStyle
  15. from .path import Path
  16. from .transforms import (
  17. Affine2D, Bbox, BboxTransformFrom, BboxTransformTo, TransformedPath)
  18. # Imported here for backward compatibility, even though they don't
  19. # really belong.
  20. from . import _path
  21. from .markers import (
  22. CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN,
  23. CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE,
  24. TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN)
  25. _log = logging.getLogger(__name__)
  26. def _get_dash_pattern(style):
  27. """Convert linestyle to dash pattern."""
  28. # go from short hand -> full strings
  29. if isinstance(style, str):
  30. style = ls_mapper.get(style, style)
  31. # un-dashed styles
  32. if style in ['solid', 'None']:
  33. offset = 0
  34. dashes = None
  35. # dashed styles
  36. elif style in ['dashed', 'dashdot', 'dotted']:
  37. offset = 0
  38. dashes = tuple(rcParams['lines.{}_pattern'.format(style)])
  39. #
  40. elif isinstance(style, tuple):
  41. offset, dashes = style
  42. if offset is None:
  43. cbook.warn_deprecated(
  44. "3.3", message="Passing the dash offset as None is deprecated "
  45. "since %(since)s and support for it will be removed "
  46. "%(removal)s; pass it as zero instead.")
  47. offset = 0
  48. else:
  49. raise ValueError('Unrecognized linestyle: %s' % str(style))
  50. # normalize offset to be positive and shorter than the dash cycle
  51. if dashes is not None:
  52. dsum = sum(dashes)
  53. if dsum:
  54. offset %= dsum
  55. return offset, dashes
  56. def _scale_dashes(offset, dashes, lw):
  57. if not rcParams['lines.scale_dashes']:
  58. return offset, dashes
  59. scaled_offset = offset * lw
  60. scaled_dashes = ([x * lw if x is not None else None for x in dashes]
  61. if dashes is not None else None)
  62. return scaled_offset, scaled_dashes
  63. def segment_hits(cx, cy, x, y, radius):
  64. """
  65. Return the indices of the segments in the polyline with coordinates (*cx*,
  66. *cy*) that are within a distance *radius* of the point (*x*, *y*).
  67. """
  68. # Process single points specially
  69. if len(x) <= 1:
  70. res, = np.nonzero((cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2)
  71. return res
  72. # We need to lop the last element off a lot.
  73. xr, yr = x[:-1], y[:-1]
  74. # Only look at line segments whose nearest point to C on the line
  75. # lies within the segment.
  76. dx, dy = x[1:] - xr, y[1:] - yr
  77. Lnorm_sq = dx ** 2 + dy ** 2 # Possibly want to eliminate Lnorm==0
  78. u = ((cx - xr) * dx + (cy - yr) * dy) / Lnorm_sq
  79. candidates = (u >= 0) & (u <= 1)
  80. # Note that there is a little area near one side of each point
  81. # which will be near neither segment, and another which will
  82. # be near both, depending on the angle of the lines. The
  83. # following radius test eliminates these ambiguities.
  84. point_hits = (cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2
  85. candidates = candidates & ~(point_hits[:-1] | point_hits[1:])
  86. # For those candidates which remain, determine how far they lie away
  87. # from the line.
  88. px, py = xr + u * dx, yr + u * dy
  89. line_hits = (cx - px) ** 2 + (cy - py) ** 2 <= radius ** 2
  90. line_hits = line_hits & candidates
  91. points, = point_hits.ravel().nonzero()
  92. lines, = line_hits.ravel().nonzero()
  93. return np.concatenate((points, lines))
  94. def _mark_every_path(markevery, tpath, affine, ax_transform):
  95. """
  96. Helper function that sorts out how to deal the input
  97. `markevery` and returns the points where markers should be drawn.
  98. Takes in the `markevery` value and the line path and returns the
  99. sub-sampled path.
  100. """
  101. # pull out the two bits of data we want from the path
  102. codes, verts = tpath.codes, tpath.vertices
  103. def _slice_or_none(in_v, slc):
  104. """Helper function to cope with `codes` being an ndarray or `None`."""
  105. if in_v is None:
  106. return None
  107. return in_v[slc]
  108. # if just an int, assume starting at 0 and make a tuple
  109. if isinstance(markevery, Integral):
  110. markevery = (0, markevery)
  111. # if just a float, assume starting at 0.0 and make a tuple
  112. elif isinstance(markevery, Real):
  113. markevery = (0.0, markevery)
  114. if isinstance(markevery, tuple):
  115. if len(markevery) != 2:
  116. raise ValueError('`markevery` is a tuple but its len is not 2; '
  117. 'markevery={}'.format(markevery))
  118. start, step = markevery
  119. # if step is an int, old behavior
  120. if isinstance(step, Integral):
  121. # tuple of 2 int is for backwards compatibility,
  122. if not isinstance(start, Integral):
  123. raise ValueError(
  124. '`markevery` is a tuple with len 2 and second element is '
  125. 'an int, but the first element is not an int; markevery={}'
  126. .format(markevery))
  127. # just return, we are done here
  128. return Path(verts[slice(start, None, step)],
  129. _slice_or_none(codes, slice(start, None, step)))
  130. elif isinstance(step, Real):
  131. if not isinstance(start, Real):
  132. raise ValueError(
  133. '`markevery` is a tuple with len 2 and second element is '
  134. 'a float, but the first element is not a float or an int; '
  135. 'markevery={}'.format(markevery))
  136. # calc cumulative distance along path (in display coords):
  137. disp_coords = affine.transform(tpath.vertices)
  138. delta = np.empty((len(disp_coords), 2))
  139. delta[0, :] = 0
  140. delta[1:, :] = disp_coords[1:, :] - disp_coords[:-1, :]
  141. delta = np.hypot(*delta.T).cumsum()
  142. # calc distance between markers along path based on the axes
  143. # bounding box diagonal being a distance of unity:
  144. (x0, y0), (x1, y1) = ax_transform.transform([[0, 0], [1, 1]])
  145. scale = np.hypot(x1 - x0, y1 - y0)
  146. marker_delta = np.arange(start * scale, delta[-1], step * scale)
  147. # find closest actual data point that is closest to
  148. # the theoretical distance along the path:
  149. inds = np.abs(delta[np.newaxis, :] - marker_delta[:, np.newaxis])
  150. inds = inds.argmin(axis=1)
  151. inds = np.unique(inds)
  152. # return, we are done here
  153. return Path(verts[inds], _slice_or_none(codes, inds))
  154. else:
  155. raise ValueError(
  156. f"markevery={markevery!r} is a tuple with len 2, but its "
  157. f"second element is not an int or a float")
  158. elif isinstance(markevery, slice):
  159. # mazol tov, it's already a slice, just return
  160. return Path(verts[markevery], _slice_or_none(codes, markevery))
  161. elif np.iterable(markevery):
  162. # fancy indexing
  163. try:
  164. return Path(verts[markevery], _slice_or_none(codes, markevery))
  165. except (ValueError, IndexError) as err:
  166. raise ValueError(
  167. f"markevery={markevery!r} is iterable but not a valid numpy "
  168. f"fancy index") from err
  169. else:
  170. raise ValueError(f"markevery={markevery!r} is not a recognized value")
  171. @cbook._define_aliases({
  172. "antialiased": ["aa"],
  173. "color": ["c"],
  174. "drawstyle": ["ds"],
  175. "linestyle": ["ls"],
  176. "linewidth": ["lw"],
  177. "markeredgecolor": ["mec"],
  178. "markeredgewidth": ["mew"],
  179. "markerfacecolor": ["mfc"],
  180. "markerfacecoloralt": ["mfcalt"],
  181. "markersize": ["ms"],
  182. })
  183. class Line2D(Artist):
  184. """
  185. A line - the line can have both a solid linestyle connecting all
  186. the vertices, and a marker at each vertex. Additionally, the
  187. drawing of the solid line is influenced by the drawstyle, e.g., one
  188. can create "stepped" lines in various styles.
  189. """
  190. lineStyles = _lineStyles = { # hidden names deprecated
  191. '-': '_draw_solid',
  192. '--': '_draw_dashed',
  193. '-.': '_draw_dash_dot',
  194. ':': '_draw_dotted',
  195. 'None': '_draw_nothing',
  196. ' ': '_draw_nothing',
  197. '': '_draw_nothing',
  198. }
  199. _drawStyles_l = {
  200. 'default': '_draw_lines',
  201. 'steps-mid': '_draw_steps_mid',
  202. 'steps-pre': '_draw_steps_pre',
  203. 'steps-post': '_draw_steps_post',
  204. }
  205. _drawStyles_s = {
  206. 'steps': '_draw_steps_pre',
  207. }
  208. # drawStyles should now be deprecated.
  209. drawStyles = {**_drawStyles_l, **_drawStyles_s}
  210. # Need a list ordered with long names first:
  211. drawStyleKeys = [*_drawStyles_l, *_drawStyles_s]
  212. # Referenced here to maintain API. These are defined in
  213. # MarkerStyle
  214. markers = MarkerStyle.markers
  215. filled_markers = MarkerStyle.filled_markers
  216. fillStyles = MarkerStyle.fillstyles
  217. zorder = 2
  218. validCap = ('butt', 'round', 'projecting')
  219. validJoin = ('miter', 'round', 'bevel')
  220. def __str__(self):
  221. if self._label != "":
  222. return f"Line2D({self._label})"
  223. elif self._x is None:
  224. return "Line2D()"
  225. elif len(self._x) > 3:
  226. return "Line2D((%g,%g),(%g,%g),...,(%g,%g))" % (
  227. self._x[0], self._y[0], self._x[0],
  228. self._y[0], self._x[-1], self._y[-1])
  229. else:
  230. return "Line2D(%s)" % ",".join(
  231. map("({:g},{:g})".format, self._x, self._y))
  232. def __init__(self, xdata, ydata,
  233. linewidth=None, # all Nones default to rc
  234. linestyle=None,
  235. color=None,
  236. marker=None,
  237. markersize=None,
  238. markeredgewidth=None,
  239. markeredgecolor=None,
  240. markerfacecolor=None,
  241. markerfacecoloralt='none',
  242. fillstyle=None,
  243. antialiased=None,
  244. dash_capstyle=None,
  245. solid_capstyle=None,
  246. dash_joinstyle=None,
  247. solid_joinstyle=None,
  248. pickradius=5,
  249. drawstyle=None,
  250. markevery=None,
  251. **kwargs
  252. ):
  253. """
  254. Create a `.Line2D` instance with *x* and *y* data in sequences of
  255. *xdata*, *ydata*.
  256. Additional keyword arguments are `.Line2D` properties:
  257. %(_Line2D_docstr)s
  258. See :meth:`set_linestyle` for a description of the line styles,
  259. :meth:`set_marker` for a description of the markers, and
  260. :meth:`set_drawstyle` for a description of the draw styles.
  261. """
  262. Artist.__init__(self)
  263. #convert sequences to numpy arrays
  264. if not np.iterable(xdata):
  265. raise RuntimeError('xdata must be a sequence')
  266. if not np.iterable(ydata):
  267. raise RuntimeError('ydata must be a sequence')
  268. if linewidth is None:
  269. linewidth = rcParams['lines.linewidth']
  270. if linestyle is None:
  271. linestyle = rcParams['lines.linestyle']
  272. if marker is None:
  273. marker = rcParams['lines.marker']
  274. if markerfacecolor is None:
  275. markerfacecolor = rcParams['lines.markerfacecolor']
  276. if markeredgecolor is None:
  277. markeredgecolor = rcParams['lines.markeredgecolor']
  278. if color is None:
  279. color = rcParams['lines.color']
  280. if markersize is None:
  281. markersize = rcParams['lines.markersize']
  282. if antialiased is None:
  283. antialiased = rcParams['lines.antialiased']
  284. if dash_capstyle is None:
  285. dash_capstyle = rcParams['lines.dash_capstyle']
  286. if dash_joinstyle is None:
  287. dash_joinstyle = rcParams['lines.dash_joinstyle']
  288. if solid_capstyle is None:
  289. solid_capstyle = rcParams['lines.solid_capstyle']
  290. if solid_joinstyle is None:
  291. solid_joinstyle = rcParams['lines.solid_joinstyle']
  292. if drawstyle is None:
  293. drawstyle = 'default'
  294. self._dashcapstyle = None
  295. self._dashjoinstyle = None
  296. self._solidjoinstyle = None
  297. self._solidcapstyle = None
  298. self.set_dash_capstyle(dash_capstyle)
  299. self.set_dash_joinstyle(dash_joinstyle)
  300. self.set_solid_capstyle(solid_capstyle)
  301. self.set_solid_joinstyle(solid_joinstyle)
  302. self._linestyles = None
  303. self._drawstyle = None
  304. self._linewidth = linewidth
  305. # scaled dash + offset
  306. self._dashSeq = None
  307. self._dashOffset = 0
  308. # unscaled dash + offset
  309. # this is needed scaling the dash pattern by linewidth
  310. self._us_dashSeq = None
  311. self._us_dashOffset = 0
  312. self.set_linewidth(linewidth)
  313. self.set_linestyle(linestyle)
  314. self.set_drawstyle(drawstyle)
  315. self._color = None
  316. self.set_color(color)
  317. self._marker = MarkerStyle(marker, fillstyle)
  318. self._markevery = None
  319. self._markersize = None
  320. self._antialiased = None
  321. self.set_markevery(markevery)
  322. self.set_antialiased(antialiased)
  323. self.set_markersize(markersize)
  324. self._markeredgecolor = None
  325. self._markeredgewidth = None
  326. self._markerfacecolor = None
  327. self._markerfacecoloralt = None
  328. self.set_markerfacecolor(markerfacecolor)
  329. self.set_markerfacecoloralt(markerfacecoloralt)
  330. self.set_markeredgecolor(markeredgecolor)
  331. self.set_markeredgewidth(markeredgewidth)
  332. # update kwargs before updating data to give the caller a
  333. # chance to init axes (and hence unit support)
  334. self.update(kwargs)
  335. self.pickradius = pickradius
  336. self.ind_offset = 0
  337. self._xorig = np.asarray([])
  338. self._yorig = np.asarray([])
  339. self._invalidx = True
  340. self._invalidy = True
  341. self._x = None
  342. self._y = None
  343. self._xy = None
  344. self._path = None
  345. self._transformed_path = None
  346. self._subslice = False
  347. self._x_filled = None # used in subslicing; only x is needed
  348. self.set_data(xdata, ydata)
  349. def contains(self, mouseevent):
  350. """
  351. Test whether *mouseevent* occurred on the line.
  352. An event is deemed to have occurred "on" the line if it is less
  353. than ``self.pickradius`` (default: 5 points) away from it. Use
  354. `~.Line2D.get_pickradius` or `~.Line2D.set_pickradius` to get or set
  355. the pick radius.
  356. Parameters
  357. ----------
  358. mouseevent : `matplotlib.backend_bases.MouseEvent`
  359. Returns
  360. -------
  361. contains : bool
  362. Whether any values are within the radius.
  363. details : dict
  364. A dictionary ``{'ind': pointlist}``, where *pointlist* is a
  365. list of points of the line that are within the pickradius around
  366. the event position.
  367. TODO: sort returned indices by distance
  368. """
  369. inside, info = self._default_contains(mouseevent)
  370. if inside is not None:
  371. return inside, info
  372. # Make sure we have data to plot
  373. if self._invalidy or self._invalidx:
  374. self.recache()
  375. if len(self._xy) == 0:
  376. return False, {}
  377. # Convert points to pixels
  378. transformed_path = self._get_transformed_path()
  379. path, affine = transformed_path.get_transformed_path_and_affine()
  380. path = affine.transform_path(path)
  381. xy = path.vertices
  382. xt = xy[:, 0]
  383. yt = xy[:, 1]
  384. # Convert pick radius from points to pixels
  385. if self.figure is None:
  386. _log.warning('no figure set when check if mouse is on line')
  387. pixels = self.pickradius
  388. else:
  389. pixels = self.figure.dpi / 72. * self.pickradius
  390. # The math involved in checking for containment (here and inside of
  391. # segment_hits) assumes that it is OK to overflow, so temporarily set
  392. # the error flags accordingly.
  393. with np.errstate(all='ignore'):
  394. # Check for collision
  395. if self._linestyle in ['None', None]:
  396. # If no line, return the nearby point(s)
  397. ind, = np.nonzero(
  398. (xt - mouseevent.x) ** 2 + (yt - mouseevent.y) ** 2
  399. <= pixels ** 2)
  400. else:
  401. # If line, return the nearby segment(s)
  402. ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels)
  403. if self._drawstyle.startswith("steps"):
  404. ind //= 2
  405. ind += self.ind_offset
  406. # Return the point(s) within radius
  407. return len(ind) > 0, dict(ind=ind)
  408. def get_pickradius(self):
  409. """
  410. Return the pick radius used for containment tests.
  411. See `.contains` for more details.
  412. """
  413. return self._pickradius
  414. def set_pickradius(self, d):
  415. """
  416. Set the pick radius used for containment tests.
  417. See `.contains` for more details.
  418. Parameters
  419. ----------
  420. d : float
  421. Pick radius, in points.
  422. """
  423. if not isinstance(d, Number) or d < 0:
  424. raise ValueError("pick radius should be a distance")
  425. self._pickradius = d
  426. pickradius = property(get_pickradius, set_pickradius)
  427. def get_fillstyle(self):
  428. """
  429. Return the marker fill style.
  430. See also `~.Line2D.set_fillstyle`.
  431. """
  432. return self._marker.get_fillstyle()
  433. def set_fillstyle(self, fs):
  434. """
  435. Set the marker fill style.
  436. Parameters
  437. ----------
  438. fs : {'full', 'left', 'right', 'bottom', 'top', 'none'}
  439. Possible values:
  440. - 'full': Fill the whole marker with the *markerfacecolor*.
  441. - 'left', 'right', 'bottom', 'top': Fill the marker half at
  442. the given side with the *markerfacecolor*. The other
  443. half of the marker is filled with *markerfacecoloralt*.
  444. - 'none': No filling.
  445. For examples see :ref:`marker_fill_styles`.
  446. """
  447. self._marker.set_fillstyle(fs)
  448. self.stale = True
  449. def set_markevery(self, every):
  450. """
  451. Set the markevery property to subsample the plot when using markers.
  452. e.g., if ``every=5``, every 5-th marker will be plotted.
  453. Parameters
  454. ----------
  455. every : None or int or (int, int) or slice or List[int] or float or \
  456. (float, float) or List[bool]
  457. Which markers to plot.
  458. - every=None, every point will be plotted.
  459. - every=N, every N-th marker will be plotted starting with
  460. marker 0.
  461. - every=(start, N), every N-th marker, starting at point
  462. start, will be plotted.
  463. - every=slice(start, end, N), every N-th marker, starting at
  464. point start, up to but not including point end, will be plotted.
  465. - every=[i, j, m, n], only markers at points i, j, m, and n
  466. will be plotted.
  467. - every=[True, False, True], positions that are True will be
  468. plotted.
  469. - every=0.1, (i.e. a float) then markers will be spaced at
  470. approximately equal distances along the line; the distance
  471. along the line between markers is determined by multiplying the
  472. display-coordinate distance of the axes bounding-box diagonal
  473. by the value of every.
  474. - every=(0.5, 0.1) (i.e. a length-2 tuple of float), the same
  475. functionality as every=0.1 is exhibited but the first marker will
  476. be 0.5 multiplied by the display-coordinate-diagonal-distance
  477. along the line.
  478. For examples see
  479. :doc:`/gallery/lines_bars_and_markers/markevery_demo`.
  480. Notes
  481. -----
  482. Setting the markevery property will only show markers at actual data
  483. points. When using float arguments to set the markevery property
  484. on irregularly spaced data, the markers will likely not appear evenly
  485. spaced because the actual data points do not coincide with the
  486. theoretical spacing between markers.
  487. When using a start offset to specify the first marker, the offset will
  488. be from the first data point which may be different from the first
  489. the visible data point if the plot is zoomed in.
  490. If zooming in on a plot when using float arguments then the actual
  491. data points that have markers will change because the distance between
  492. markers is always determined from the display-coordinates
  493. axes-bounding-box-diagonal regardless of the actual axes data limits.
  494. """
  495. self._markevery = every
  496. self.stale = True
  497. def get_markevery(self):
  498. """
  499. Return the markevery setting for marker subsampling.
  500. See also `~.Line2D.set_markevery`.
  501. """
  502. return self._markevery
  503. def set_picker(self, p):
  504. # docstring inherited
  505. if isinstance(p, Number) and not isinstance(p, bool):
  506. # After deprecation, the whole method can be deleted and inherited.
  507. cbook.warn_deprecated(
  508. "3.3", message="Setting the line's pick radius via set_picker "
  509. "is deprecated since %(since)s and will be removed "
  510. "%(removal)s; use set_pickradius instead.")
  511. self.pickradius = p
  512. self._picker = p
  513. def get_window_extent(self, renderer):
  514. bbox = Bbox([[0, 0], [0, 0]])
  515. trans_data_to_xy = self.get_transform().transform
  516. bbox.update_from_data_xy(trans_data_to_xy(self.get_xydata()),
  517. ignore=True)
  518. # correct for marker size, if any
  519. if self._marker:
  520. ms = (self._markersize / 72.0 * self.figure.dpi) * 0.5
  521. bbox = bbox.padded(ms)
  522. return bbox
  523. @Artist.axes.setter
  524. def axes(self, ax):
  525. # call the set method from the base-class property
  526. Artist.axes.fset(self, ax)
  527. if ax is not None:
  528. # connect unit-related callbacks
  529. if ax.xaxis is not None:
  530. self._xcid = ax.xaxis.callbacks.connect('units',
  531. self.recache_always)
  532. if ax.yaxis is not None:
  533. self._ycid = ax.yaxis.callbacks.connect('units',
  534. self.recache_always)
  535. def set_data(self, *args):
  536. """
  537. Set the x and y data.
  538. Parameters
  539. ----------
  540. *args : (2, N) array or two 1D arrays
  541. """
  542. if len(args) == 1:
  543. (x, y), = args
  544. else:
  545. x, y = args
  546. self.set_xdata(x)
  547. self.set_ydata(y)
  548. def recache_always(self):
  549. self.recache(always=True)
  550. def recache(self, always=False):
  551. if always or self._invalidx:
  552. xconv = self.convert_xunits(self._xorig)
  553. x = _to_unmasked_float_array(xconv).ravel()
  554. else:
  555. x = self._x
  556. if always or self._invalidy:
  557. yconv = self.convert_yunits(self._yorig)
  558. y = _to_unmasked_float_array(yconv).ravel()
  559. else:
  560. y = self._y
  561. self._xy = np.column_stack(np.broadcast_arrays(x, y)).astype(float)
  562. self._x, self._y = self._xy.T # views
  563. self._subslice = False
  564. if (self.axes and len(x) > 1000 and self._is_sorted(x) and
  565. self.axes.name == 'rectilinear' and
  566. self.axes.get_xscale() == 'linear' and
  567. self._markevery is None and
  568. self.get_clip_on()):
  569. self._subslice = True
  570. nanmask = np.isnan(x)
  571. if nanmask.any():
  572. self._x_filled = self._x.copy()
  573. indices = np.arange(len(x))
  574. self._x_filled[nanmask] = np.interp(
  575. indices[nanmask], indices[~nanmask], self._x[~nanmask])
  576. else:
  577. self._x_filled = self._x
  578. if self._path is not None:
  579. interpolation_steps = self._path._interpolation_steps
  580. else:
  581. interpolation_steps = 1
  582. xy = STEP_LOOKUP_MAP[self._drawstyle](*self._xy.T)
  583. self._path = Path(np.asarray(xy).T,
  584. _interpolation_steps=interpolation_steps)
  585. self._transformed_path = None
  586. self._invalidx = False
  587. self._invalidy = False
  588. def _transform_path(self, subslice=None):
  589. """
  590. Puts a TransformedPath instance at self._transformed_path;
  591. all invalidation of the transform is then handled by the
  592. TransformedPath instance.
  593. """
  594. # Masked arrays are now handled by the Path class itself
  595. if subslice is not None:
  596. xy = STEP_LOOKUP_MAP[self._drawstyle](*self._xy[subslice, :].T)
  597. _path = Path(np.asarray(xy).T,
  598. _interpolation_steps=self._path._interpolation_steps)
  599. else:
  600. _path = self._path
  601. self._transformed_path = TransformedPath(_path, self.get_transform())
  602. def _get_transformed_path(self):
  603. """
  604. Return the :class:`~matplotlib.transforms.TransformedPath` instance
  605. of this line.
  606. """
  607. if self._transformed_path is None:
  608. self._transform_path()
  609. return self._transformed_path
  610. def set_transform(self, t):
  611. """
  612. Set the Transformation instance used by this artist.
  613. Parameters
  614. ----------
  615. t : `matplotlib.transforms.Transform`
  616. """
  617. Artist.set_transform(self, t)
  618. self._invalidx = True
  619. self._invalidy = True
  620. self.stale = True
  621. def _is_sorted(self, x):
  622. """Return whether x is sorted in ascending order."""
  623. # We don't handle the monotonically decreasing case.
  624. return _path.is_sorted(x)
  625. @allow_rasterization
  626. def draw(self, renderer):
  627. # docstring inherited
  628. if not self.get_visible():
  629. return
  630. if self._invalidy or self._invalidx:
  631. self.recache()
  632. self.ind_offset = 0 # Needed for contains() method.
  633. if self._subslice and self.axes:
  634. x0, x1 = self.axes.get_xbound()
  635. i0 = self._x_filled.searchsorted(x0, 'left')
  636. i1 = self._x_filled.searchsorted(x1, 'right')
  637. subslice = slice(max(i0 - 1, 0), i1 + 1)
  638. self.ind_offset = subslice.start
  639. self._transform_path(subslice)
  640. else:
  641. subslice = None
  642. if self.get_path_effects():
  643. from matplotlib.patheffects import PathEffectRenderer
  644. renderer = PathEffectRenderer(self.get_path_effects(), renderer)
  645. renderer.open_group('line2d', self.get_gid())
  646. if self._lineStyles[self._linestyle] != '_draw_nothing':
  647. tpath, affine = (self._get_transformed_path()
  648. .get_transformed_path_and_affine())
  649. if len(tpath.vertices):
  650. gc = renderer.new_gc()
  651. self._set_gc_clip(gc)
  652. gc.set_url(self.get_url())
  653. lc_rgba = mcolors.to_rgba(self._color, self._alpha)
  654. gc.set_foreground(lc_rgba, isRGBA=True)
  655. gc.set_antialiased(self._antialiased)
  656. gc.set_linewidth(self._linewidth)
  657. if self.is_dashed():
  658. cap = self._dashcapstyle
  659. join = self._dashjoinstyle
  660. else:
  661. cap = self._solidcapstyle
  662. join = self._solidjoinstyle
  663. gc.set_joinstyle(join)
  664. gc.set_capstyle(cap)
  665. gc.set_snap(self.get_snap())
  666. if self.get_sketch_params() is not None:
  667. gc.set_sketch_params(*self.get_sketch_params())
  668. gc.set_dashes(self._dashOffset, self._dashSeq)
  669. renderer.draw_path(gc, tpath, affine.frozen())
  670. gc.restore()
  671. if self._marker and self._markersize > 0:
  672. gc = renderer.new_gc()
  673. self._set_gc_clip(gc)
  674. gc.set_url(self.get_url())
  675. gc.set_linewidth(self._markeredgewidth)
  676. gc.set_antialiased(self._antialiased)
  677. ec_rgba = mcolors.to_rgba(
  678. self.get_markeredgecolor(), self._alpha)
  679. fc_rgba = mcolors.to_rgba(
  680. self._get_markerfacecolor(), self._alpha)
  681. fcalt_rgba = mcolors.to_rgba(
  682. self._get_markerfacecolor(alt=True), self._alpha)
  683. # If the edgecolor is "auto", it is set according to the *line*
  684. # color but inherits the alpha value of the *face* color, if any.
  685. if (cbook._str_equal(self._markeredgecolor, "auto")
  686. and not cbook._str_lower_equal(
  687. self.get_markerfacecolor(), "none")):
  688. ec_rgba = ec_rgba[:3] + (fc_rgba[3],)
  689. gc.set_foreground(ec_rgba, isRGBA=True)
  690. if self.get_sketch_params() is not None:
  691. scale, length, randomness = self.get_sketch_params()
  692. gc.set_sketch_params(scale/2, length/2, 2*randomness)
  693. marker = self._marker
  694. # Markers *must* be drawn ignoring the drawstyle (but don't pay the
  695. # recaching if drawstyle is already "default").
  696. if self.get_drawstyle() != "default":
  697. with cbook._setattr_cm(
  698. self, _drawstyle="default", _transformed_path=None):
  699. self.recache()
  700. self._transform_path(subslice)
  701. tpath, affine = (self._get_transformed_path()
  702. .get_transformed_points_and_affine())
  703. else:
  704. tpath, affine = (self._get_transformed_path()
  705. .get_transformed_points_and_affine())
  706. if len(tpath.vertices):
  707. # subsample the markers if markevery is not None
  708. markevery = self.get_markevery()
  709. if markevery is not None:
  710. subsampled = _mark_every_path(markevery, tpath,
  711. affine, self.axes.transAxes)
  712. else:
  713. subsampled = tpath
  714. snap = marker.get_snap_threshold()
  715. if isinstance(snap, Real):
  716. snap = renderer.points_to_pixels(self._markersize) >= snap
  717. gc.set_snap(snap)
  718. gc.set_joinstyle(marker.get_joinstyle())
  719. gc.set_capstyle(marker.get_capstyle())
  720. marker_path = marker.get_path()
  721. marker_trans = marker.get_transform()
  722. w = renderer.points_to_pixels(self._markersize)
  723. if cbook._str_equal(marker.get_marker(), ","):
  724. gc.set_linewidth(0)
  725. else:
  726. # Don't scale for pixels, and don't stroke them
  727. marker_trans = marker_trans.scale(w)
  728. renderer.draw_markers(gc, marker_path, marker_trans,
  729. subsampled, affine.frozen(),
  730. fc_rgba)
  731. alt_marker_path = marker.get_alt_path()
  732. if alt_marker_path:
  733. alt_marker_trans = marker.get_alt_transform()
  734. alt_marker_trans = alt_marker_trans.scale(w)
  735. renderer.draw_markers(
  736. gc, alt_marker_path, alt_marker_trans, subsampled,
  737. affine.frozen(), fcalt_rgba)
  738. gc.restore()
  739. renderer.close_group('line2d')
  740. self.stale = False
  741. def get_antialiased(self):
  742. """Return whether antialiased rendering is used."""
  743. return self._antialiased
  744. def get_color(self):
  745. """
  746. Return the line color.
  747. See also `~.Line2D.set_color`.
  748. """
  749. return self._color
  750. def get_drawstyle(self):
  751. """
  752. Return the drawstyle.
  753. See also `~.Line2D.set_drawstyle`.
  754. """
  755. return self._drawstyle
  756. def get_linestyle(self):
  757. """
  758. Return the linestyle.
  759. See also `~.Line2D.set_linestyle`.
  760. """
  761. return self._linestyle
  762. def get_linewidth(self):
  763. """
  764. Return the linewidth in points.
  765. See also `~.Line2D.set_linewidth`.
  766. """
  767. return self._linewidth
  768. def get_marker(self):
  769. """
  770. Return the line marker.
  771. See also `~.Line2D.set_marker`.
  772. """
  773. return self._marker.get_marker()
  774. def get_markeredgecolor(self):
  775. """
  776. Return the marker edge color.
  777. See also `~.Line2D.set_markeredgecolor`.
  778. """
  779. mec = self._markeredgecolor
  780. if cbook._str_equal(mec, 'auto'):
  781. if rcParams['_internal.classic_mode']:
  782. if self._marker.get_marker() in ('.', ','):
  783. return self._color
  784. if self._marker.is_filled() and self.get_fillstyle() != 'none':
  785. return 'k' # Bad hard-wired default...
  786. return self._color
  787. else:
  788. return mec
  789. def get_markeredgewidth(self):
  790. """
  791. Return the marker edge width in points.
  792. See also `~.Line2D.set_markeredgewidth`.
  793. """
  794. return self._markeredgewidth
  795. def _get_markerfacecolor(self, alt=False):
  796. if self.get_fillstyle() == 'none':
  797. return 'none'
  798. fc = self._markerfacecoloralt if alt else self._markerfacecolor
  799. if cbook._str_lower_equal(fc, 'auto'):
  800. return self._color
  801. else:
  802. return fc
  803. def get_markerfacecolor(self):
  804. """
  805. Return the marker face color.
  806. See also `~.Line2D.set_markerfacecolor`.
  807. """
  808. return self._get_markerfacecolor(alt=False)
  809. def get_markerfacecoloralt(self):
  810. """
  811. Return the alternate marker face color.
  812. See also `~.Line2D.set_markerfacecoloralt`.
  813. """
  814. return self._get_markerfacecolor(alt=True)
  815. def get_markersize(self):
  816. """
  817. Return the marker size in points.
  818. See also `~.Line2D.set_markersize`.
  819. """
  820. return self._markersize
  821. def get_data(self, orig=True):
  822. """
  823. Return the xdata, ydata.
  824. If *orig* is *True*, return the original data.
  825. """
  826. return self.get_xdata(orig=orig), self.get_ydata(orig=orig)
  827. def get_xdata(self, orig=True):
  828. """
  829. Return the xdata.
  830. If *orig* is *True*, return the original data, else the
  831. processed data.
  832. """
  833. if orig:
  834. return self._xorig
  835. if self._invalidx:
  836. self.recache()
  837. return self._x
  838. def get_ydata(self, orig=True):
  839. """
  840. Return the ydata.
  841. If *orig* is *True*, return the original data, else the
  842. processed data.
  843. """
  844. if orig:
  845. return self._yorig
  846. if self._invalidy:
  847. self.recache()
  848. return self._y
  849. def get_path(self):
  850. """
  851. Return the :class:`~matplotlib.path.Path` object associated
  852. with this line.
  853. """
  854. if self._invalidy or self._invalidx:
  855. self.recache()
  856. return self._path
  857. def get_xydata(self):
  858. """
  859. Return the *xy* data as a Nx2 numpy array.
  860. """
  861. if self._invalidy or self._invalidx:
  862. self.recache()
  863. return self._xy
  864. def set_antialiased(self, b):
  865. """
  866. Set whether to use antialiased rendering.
  867. Parameters
  868. ----------
  869. b : bool
  870. """
  871. if self._antialiased != b:
  872. self.stale = True
  873. self._antialiased = b
  874. def set_color(self, color):
  875. """
  876. Set the color of the line.
  877. Parameters
  878. ----------
  879. color : color
  880. """
  881. self._color = color
  882. self.stale = True
  883. def set_drawstyle(self, drawstyle):
  884. """
  885. Set the drawstyle of the plot.
  886. The drawstyle determines how the points are connected.
  887. Parameters
  888. ----------
  889. drawstyle : {'default', 'steps', 'steps-pre', 'steps-mid', \
  890. 'steps-post'}, default: 'default'
  891. For 'default', the points are connected with straight lines.
  892. The steps variants connect the points with step-like lines,
  893. i.e. horizontal lines with vertical steps. They differ in the
  894. location of the step:
  895. - 'steps-pre': The step is at the beginning of the line segment,
  896. i.e. the line will be at the y-value of point to the right.
  897. - 'steps-mid': The step is halfway between the points.
  898. - 'steps-post: The step is at the end of the line segment,
  899. i.e. the line will be at the y-value of the point to the left.
  900. - 'steps' is equal to 'steps-pre' and is maintained for
  901. backward-compatibility.
  902. For examples see :doc:`/gallery/lines_bars_and_markers/step_demo`.
  903. """
  904. if drawstyle is None:
  905. drawstyle = 'default'
  906. cbook._check_in_list(self.drawStyles, drawstyle=drawstyle)
  907. if self._drawstyle != drawstyle:
  908. self.stale = True
  909. # invalidate to trigger a recache of the path
  910. self._invalidx = True
  911. self._drawstyle = drawstyle
  912. def set_linewidth(self, w):
  913. """
  914. Set the line width in points.
  915. Parameters
  916. ----------
  917. w : float
  918. Line width, in points.
  919. """
  920. w = float(w)
  921. if self._linewidth != w:
  922. self.stale = True
  923. self._linewidth = w
  924. # rescale the dashes + offset
  925. self._dashOffset, self._dashSeq = _scale_dashes(
  926. self._us_dashOffset, self._us_dashSeq, self._linewidth)
  927. def set_linestyle(self, ls):
  928. """
  929. Set the linestyle of the line.
  930. Parameters
  931. ----------
  932. ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
  933. Possible values:
  934. - A string:
  935. =============================== =================
  936. Linestyle Description
  937. =============================== =================
  938. ``'-'`` or ``'solid'`` solid line
  939. ``'--'`` or ``'dashed'`` dashed line
  940. ``'-.'`` or ``'dashdot'`` dash-dotted line
  941. ``':'`` or ``'dotted'`` dotted line
  942. ``'None'`` or ``' '`` or ``''`` draw nothing
  943. =============================== =================
  944. - Alternatively a dash tuple of the following form can be
  945. provided::
  946. (offset, onoffseq)
  947. where ``onoffseq`` is an even length tuple of on and off ink
  948. in points. See also :meth:`set_dashes`.
  949. For examples see :doc:`/gallery/lines_bars_and_markers/linestyles`.
  950. """
  951. if isinstance(ls, str):
  952. if ls in [' ', '', 'none']:
  953. ls = 'None'
  954. cbook._check_in_list([*self._lineStyles, *ls_mapper_r], ls=ls)
  955. if ls not in self._lineStyles:
  956. ls = ls_mapper_r[ls]
  957. self._linestyle = ls
  958. else:
  959. self._linestyle = '--'
  960. # get the unscaled dashes
  961. self._us_dashOffset, self._us_dashSeq = _get_dash_pattern(ls)
  962. # compute the linewidth scaled dashes
  963. self._dashOffset, self._dashSeq = _scale_dashes(
  964. self._us_dashOffset, self._us_dashSeq, self._linewidth)
  965. @docstring.dedent_interpd
  966. def set_marker(self, marker):
  967. """
  968. Set the line marker.
  969. Parameters
  970. ----------
  971. marker : marker style string, `~.path.Path` or `~.markers.MarkerStyle`
  972. See `~matplotlib.markers` for full description of possible
  973. arguments.
  974. """
  975. self._marker.set_marker(marker)
  976. self.stale = True
  977. def set_markeredgecolor(self, ec):
  978. """
  979. Set the marker edge color.
  980. Parameters
  981. ----------
  982. ec : color
  983. """
  984. if ec is None:
  985. ec = 'auto'
  986. if (self._markeredgecolor is None
  987. or np.any(self._markeredgecolor != ec)):
  988. self.stale = True
  989. self._markeredgecolor = ec
  990. def set_markeredgewidth(self, ew):
  991. """
  992. Set the marker edge width in points.
  993. Parameters
  994. ----------
  995. ew : float
  996. Marker edge width, in points.
  997. """
  998. if ew is None:
  999. ew = rcParams['lines.markeredgewidth']
  1000. if self._markeredgewidth != ew:
  1001. self.stale = True
  1002. self._markeredgewidth = ew
  1003. def set_markerfacecolor(self, fc):
  1004. """
  1005. Set the marker face color.
  1006. Parameters
  1007. ----------
  1008. fc : color
  1009. """
  1010. if fc is None:
  1011. fc = 'auto'
  1012. if np.any(self._markerfacecolor != fc):
  1013. self.stale = True
  1014. self._markerfacecolor = fc
  1015. def set_markerfacecoloralt(self, fc):
  1016. """
  1017. Set the alternate marker face color.
  1018. Parameters
  1019. ----------
  1020. fc : color
  1021. """
  1022. if fc is None:
  1023. fc = 'auto'
  1024. if np.any(self._markerfacecoloralt != fc):
  1025. self.stale = True
  1026. self._markerfacecoloralt = fc
  1027. def set_markersize(self, sz):
  1028. """
  1029. Set the marker size in points.
  1030. Parameters
  1031. ----------
  1032. sz : float
  1033. Marker size, in points.
  1034. """
  1035. sz = float(sz)
  1036. if self._markersize != sz:
  1037. self.stale = True
  1038. self._markersize = sz
  1039. def set_xdata(self, x):
  1040. """
  1041. Set the data array for x.
  1042. Parameters
  1043. ----------
  1044. x : 1D array
  1045. """
  1046. self._xorig = x
  1047. self._invalidx = True
  1048. self.stale = True
  1049. def set_ydata(self, y):
  1050. """
  1051. Set the data array for y.
  1052. Parameters
  1053. ----------
  1054. y : 1D array
  1055. """
  1056. self._yorig = y
  1057. self._invalidy = True
  1058. self.stale = True
  1059. def set_dashes(self, seq):
  1060. """
  1061. Set the dash sequence.
  1062. The dash sequence is a sequence of floats of even length describing
  1063. the length of dashes and spaces in points.
  1064. For example, (5, 2, 1, 2) describes a sequence of 5 point and 1 point
  1065. dashes separated by 2 point spaces.
  1066. Parameters
  1067. ----------
  1068. seq : sequence of floats (on/off ink in points) or (None, None)
  1069. If *seq* is empty or ``(None, None)``, the linestyle will be set
  1070. to solid.
  1071. """
  1072. if seq == (None, None) or len(seq) == 0:
  1073. self.set_linestyle('-')
  1074. else:
  1075. self.set_linestyle((0, seq))
  1076. def update_from(self, other):
  1077. """Copy properties from *other* to self."""
  1078. Artist.update_from(self, other)
  1079. self._linestyle = other._linestyle
  1080. self._linewidth = other._linewidth
  1081. self._color = other._color
  1082. self._markersize = other._markersize
  1083. self._markerfacecolor = other._markerfacecolor
  1084. self._markerfacecoloralt = other._markerfacecoloralt
  1085. self._markeredgecolor = other._markeredgecolor
  1086. self._markeredgewidth = other._markeredgewidth
  1087. self._dashSeq = other._dashSeq
  1088. self._us_dashSeq = other._us_dashSeq
  1089. self._dashOffset = other._dashOffset
  1090. self._us_dashOffset = other._us_dashOffset
  1091. self._dashcapstyle = other._dashcapstyle
  1092. self._dashjoinstyle = other._dashjoinstyle
  1093. self._solidcapstyle = other._solidcapstyle
  1094. self._solidjoinstyle = other._solidjoinstyle
  1095. self._linestyle = other._linestyle
  1096. self._marker = MarkerStyle(other._marker.get_marker(),
  1097. other._marker.get_fillstyle())
  1098. self._drawstyle = other._drawstyle
  1099. def set_dash_joinstyle(self, s):
  1100. """
  1101. Set the join style for dashed lines.
  1102. Parameters
  1103. ----------
  1104. s : {'miter', 'round', 'bevel'}
  1105. For examples see :doc:`/gallery/lines_bars_and_markers/joinstyle`.
  1106. """
  1107. mpl.rcsetup.validate_joinstyle(s)
  1108. if self._dashjoinstyle != s:
  1109. self.stale = True
  1110. self._dashjoinstyle = s
  1111. def set_solid_joinstyle(self, s):
  1112. """
  1113. Set the join style for solid lines.
  1114. Parameters
  1115. ----------
  1116. s : {'miter', 'round', 'bevel'}
  1117. For examples see :doc:`/gallery/lines_bars_and_markers/joinstyle`.
  1118. """
  1119. mpl.rcsetup.validate_joinstyle(s)
  1120. if self._solidjoinstyle != s:
  1121. self.stale = True
  1122. self._solidjoinstyle = s
  1123. def get_dash_joinstyle(self):
  1124. """
  1125. Return the join style for dashed lines.
  1126. See also `~.Line2D.set_dash_joinstyle`.
  1127. """
  1128. return self._dashjoinstyle
  1129. def get_solid_joinstyle(self):
  1130. """
  1131. Return the join style for solid lines.
  1132. See also `~.Line2D.set_solid_joinstyle`.
  1133. """
  1134. return self._solidjoinstyle
  1135. def set_dash_capstyle(self, s):
  1136. """
  1137. Set the cap style for dashed lines.
  1138. Parameters
  1139. ----------
  1140. s : {'butt', 'round', 'projecting'}
  1141. For examples see :doc:`/gallery/lines_bars_and_markers/joinstyle`.
  1142. """
  1143. mpl.rcsetup.validate_capstyle(s)
  1144. if self._dashcapstyle != s:
  1145. self.stale = True
  1146. self._dashcapstyle = s
  1147. def set_solid_capstyle(self, s):
  1148. """
  1149. Set the cap style for solid lines.
  1150. Parameters
  1151. ----------
  1152. s : {'butt', 'round', 'projecting'}
  1153. For examples see :doc:`/gallery/lines_bars_and_markers/joinstyle`.
  1154. """
  1155. mpl.rcsetup.validate_capstyle(s)
  1156. if self._solidcapstyle != s:
  1157. self.stale = True
  1158. self._solidcapstyle = s
  1159. def get_dash_capstyle(self):
  1160. """
  1161. Return the cap style for dashed lines.
  1162. See also `~.Line2D.set_dash_capstyle`.
  1163. """
  1164. return self._dashcapstyle
  1165. def get_solid_capstyle(self):
  1166. """
  1167. Return the cap style for solid lines.
  1168. See also `~.Line2D.set_solid_capstyle`.
  1169. """
  1170. return self._solidcapstyle
  1171. def is_dashed(self):
  1172. """
  1173. Return whether line has a dashed linestyle.
  1174. See also `~.Line2D.set_linestyle`.
  1175. """
  1176. return self._linestyle in ('--', '-.', ':')
  1177. class _AxLine(Line2D):
  1178. """
  1179. A helper class that implements `~.Axes.axline`, by recomputing the artist
  1180. transform at draw time.
  1181. """
  1182. def get_transform(self):
  1183. ax = self.axes
  1184. (x1, y1), (x2, y2) = ax.transScale.transform([*zip(*self.get_data())])
  1185. dx = x2 - x1
  1186. dy = y2 - y1
  1187. if np.allclose(x1, x2):
  1188. if np.allclose(y1, y2):
  1189. raise ValueError(
  1190. f"Cannot draw a line through two identical points "
  1191. f"(x={self.get_xdata()}, y={self.get_ydata()})")
  1192. # First send y1 to 0 and y2 to 1.
  1193. return (Affine2D.from_values(1, 0, 0, 1 / dy, 0, -y1 / dy)
  1194. + ax.get_xaxis_transform(which="grid"))
  1195. if np.allclose(y1, y2):
  1196. # First send x1 to 0 and x2 to 1.
  1197. return (Affine2D.from_values(1 / dx, 0, 0, 1, -x1 / dx, 0)
  1198. + ax.get_yaxis_transform(which="grid"))
  1199. (vxlo, vylo), (vxhi, vyhi) = ax.transScale.transform(ax.viewLim)
  1200. # General case: find intersections with view limits in either
  1201. # direction, and draw between the middle two points.
  1202. _, start, stop, _ = sorted([
  1203. (vxlo, y1 + (vxlo - x1) * dy / dx),
  1204. (vxhi, y1 + (vxhi - x1) * dy / dx),
  1205. (x1 + (vylo - y1) * dx / dy, vylo),
  1206. (x1 + (vyhi - y1) * dx / dy, vyhi),
  1207. ])
  1208. return (BboxTransformFrom(Bbox([*zip(*self.get_data())]))
  1209. + BboxTransformTo(Bbox([start, stop]))
  1210. + ax.transLimits + ax.transAxes)
  1211. def draw(self, renderer):
  1212. self._transformed_path = None # Force regen.
  1213. super().draw(renderer)
  1214. class VertexSelector:
  1215. """
  1216. Manage the callbacks to maintain a list of selected vertices for
  1217. `.Line2D`. Derived classes should override
  1218. :meth:`~matplotlib.lines.VertexSelector.process_selected` to do
  1219. something with the picks.
  1220. Here is an example which highlights the selected verts with red
  1221. circles::
  1222. import numpy as np
  1223. import matplotlib.pyplot as plt
  1224. import matplotlib.lines as lines
  1225. class HighlightSelected(lines.VertexSelector):
  1226. def __init__(self, line, fmt='ro', **kwargs):
  1227. lines.VertexSelector.__init__(self, line)
  1228. self.markers, = self.axes.plot([], [], fmt, **kwargs)
  1229. def process_selected(self, ind, xs, ys):
  1230. self.markers.set_data(xs, ys)
  1231. self.canvas.draw()
  1232. fig, ax = plt.subplots()
  1233. x, y = np.random.rand(2, 30)
  1234. line, = ax.plot(x, y, 'bs-', picker=5)
  1235. selector = HighlightSelected(line)
  1236. plt.show()
  1237. """
  1238. def __init__(self, line):
  1239. """
  1240. Initialize the class with a `.Line2D` instance. The line should
  1241. already be added to some :class:`matplotlib.axes.Axes` instance and
  1242. should have the picker property set.
  1243. """
  1244. if line.axes is None:
  1245. raise RuntimeError('You must first add the line to the Axes')
  1246. if line.get_picker() is None:
  1247. raise RuntimeError('You must first set the picker property '
  1248. 'of the line')
  1249. self.axes = line.axes
  1250. self.line = line
  1251. self.canvas = self.axes.figure.canvas
  1252. self.cid = self.canvas.mpl_connect('pick_event', self.onpick)
  1253. self.ind = set()
  1254. def process_selected(self, ind, xs, ys):
  1255. """
  1256. Default "do nothing" implementation of the
  1257. :meth:`process_selected` method.
  1258. Parameters
  1259. ----------
  1260. ind : list of int
  1261. The indices of the selected vertices.
  1262. xs, ys : array-like
  1263. The coordinates of the selected vertices.
  1264. """
  1265. pass
  1266. def onpick(self, event):
  1267. """When the line is picked, update the set of selected indices."""
  1268. if event.artist is not self.line:
  1269. return
  1270. self.ind ^= set(event.ind)
  1271. ind = sorted(self.ind)
  1272. xdata, ydata = self.line.get_data()
  1273. self.process_selected(ind, xdata[ind], ydata[ind])
  1274. lineStyles = Line2D._lineStyles
  1275. lineMarkers = MarkerStyle.markers
  1276. drawStyles = Line2D.drawStyles
  1277. fillStyles = MarkerStyle.fillstyles
  1278. docstring.interpd.update(_Line2D_docstr=artist.kwdoc(Line2D))
  1279. # You can not set the docstring of an instancemethod,
  1280. # but you can on the underlying function. Go figure.
  1281. docstring.dedent_interpd(Line2D.__init__)