lines.py 50 KB

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