lines.py 57 KB

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