path.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. r"""
  2. A module for dealing with the polylines used throughout Matplotlib.
  3. The primary class for polyline handling in Matplotlib is `Path`. Almost all
  4. vector drawing makes use of `Path`\s somewhere in the drawing pipeline.
  5. Whilst a `Path` instance itself cannot be drawn, some `.Artist` subclasses,
  6. such as `.PathPatch` and `.PathCollection`, can be used for convenient `Path`
  7. visualisation.
  8. """
  9. import copy
  10. from functools import lru_cache
  11. from weakref import WeakValueDictionary
  12. import numpy as np
  13. import matplotlib as mpl
  14. from . import _api, _path
  15. from .cbook import _to_unmasked_float_array, simple_linear_interpolation
  16. from .bezier import BezierSegment
  17. class Path:
  18. """
  19. A series of possibly disconnected, possibly closed, line and curve
  20. segments.
  21. The underlying storage is made up of two parallel numpy arrays:
  22. - *vertices*: an (N, 2) float array of vertices
  23. - *codes*: an N-length `numpy.uint8` array of path codes, or None
  24. These two arrays always have the same length in the first
  25. dimension. For example, to represent a cubic curve, you must
  26. provide three vertices and three `CURVE4` codes.
  27. The code types are:
  28. - `STOP` : 1 vertex (ignored)
  29. A marker for the end of the entire path (currently not required and
  30. ignored)
  31. - `MOVETO` : 1 vertex
  32. Pick up the pen and move to the given vertex.
  33. - `LINETO` : 1 vertex
  34. Draw a line from the current position to the given vertex.
  35. - `CURVE3` : 1 control point, 1 endpoint
  36. Draw a quadratic Bézier curve from the current position, with the given
  37. control point, to the given end point.
  38. - `CURVE4` : 2 control points, 1 endpoint
  39. Draw a cubic Bézier curve from the current position, with the given
  40. control points, to the given end point.
  41. - `CLOSEPOLY` : 1 vertex (ignored)
  42. Draw a line segment to the start point of the current polyline.
  43. If *codes* is None, it is interpreted as a `MOVETO` followed by a series
  44. of `LINETO`.
  45. Users of Path objects should not access the vertices and codes arrays
  46. directly. Instead, they should use `iter_segments` or `cleaned` to get the
  47. vertex/code pairs. This helps, in particular, to consistently handle the
  48. case of *codes* being None.
  49. Some behavior of Path objects can be controlled by rcParams. See the
  50. rcParams whose keys start with 'path.'.
  51. .. note::
  52. The vertices and codes arrays should be treated as
  53. immutable -- there are a number of optimizations and assumptions
  54. made up front in the constructor that will not change when the
  55. data changes.
  56. """
  57. code_type = np.uint8
  58. # Path codes
  59. STOP = code_type(0) # 1 vertex
  60. MOVETO = code_type(1) # 1 vertex
  61. LINETO = code_type(2) # 1 vertex
  62. CURVE3 = code_type(3) # 2 vertices
  63. CURVE4 = code_type(4) # 3 vertices
  64. CLOSEPOLY = code_type(79) # 1 vertex
  65. #: A dictionary mapping Path codes to the number of vertices that the
  66. #: code expects.
  67. NUM_VERTICES_FOR_CODE = {STOP: 1,
  68. MOVETO: 1,
  69. LINETO: 1,
  70. CURVE3: 2,
  71. CURVE4: 3,
  72. CLOSEPOLY: 1}
  73. def __init__(self, vertices, codes=None, _interpolation_steps=1,
  74. closed=False, readonly=False):
  75. """
  76. Create a new path with the given vertices and codes.
  77. Parameters
  78. ----------
  79. vertices : (N, 2) array-like
  80. The path vertices, as an array, masked array or sequence of pairs.
  81. Masked values, if any, will be converted to NaNs, which are then
  82. handled correctly by the Agg PathIterator and other consumers of
  83. path data, such as :meth:`iter_segments`.
  84. codes : array-like or None, optional
  85. N-length array of integers representing the codes of the path.
  86. If not None, codes must be the same length as vertices.
  87. If None, *vertices* will be treated as a series of line segments.
  88. _interpolation_steps : int, optional
  89. Used as a hint to certain projections, such as Polar, that this
  90. path should be linearly interpolated immediately before drawing.
  91. This attribute is primarily an implementation detail and is not
  92. intended for public use.
  93. closed : bool, optional
  94. If *codes* is None and closed is True, vertices will be treated as
  95. line segments of a closed polygon. Note that the last vertex will
  96. then be ignored (as the corresponding code will be set to
  97. `CLOSEPOLY`).
  98. readonly : bool, optional
  99. Makes the path behave in an immutable way and sets the vertices
  100. and codes as read-only arrays.
  101. """
  102. vertices = _to_unmasked_float_array(vertices)
  103. _api.check_shape((None, 2), vertices=vertices)
  104. if codes is not None:
  105. codes = np.asarray(codes, self.code_type)
  106. if codes.ndim != 1 or len(codes) != len(vertices):
  107. raise ValueError("'codes' must be a 1D list or array with the "
  108. "same length of 'vertices'. "
  109. f"Your vertices have shape {vertices.shape} "
  110. f"but your codes have shape {codes.shape}")
  111. if len(codes) and codes[0] != self.MOVETO:
  112. raise ValueError("The first element of 'code' must be equal "
  113. f"to 'MOVETO' ({self.MOVETO}). "
  114. f"Your first code is {codes[0]}")
  115. elif closed and len(vertices):
  116. codes = np.empty(len(vertices), dtype=self.code_type)
  117. codes[0] = self.MOVETO
  118. codes[1:-1] = self.LINETO
  119. codes[-1] = self.CLOSEPOLY
  120. self._vertices = vertices
  121. self._codes = codes
  122. self._interpolation_steps = _interpolation_steps
  123. self._update_values()
  124. if readonly:
  125. self._vertices.flags.writeable = False
  126. if self._codes is not None:
  127. self._codes.flags.writeable = False
  128. self._readonly = True
  129. else:
  130. self._readonly = False
  131. @classmethod
  132. def _fast_from_codes_and_verts(cls, verts, codes, internals_from=None):
  133. """
  134. Create a Path instance without the expense of calling the constructor.
  135. Parameters
  136. ----------
  137. verts : array-like
  138. codes : array
  139. internals_from : Path or None
  140. If not None, another `Path` from which the attributes
  141. ``should_simplify``, ``simplify_threshold``, and
  142. ``interpolation_steps`` will be copied. Note that ``readonly`` is
  143. never copied, and always set to ``False`` by this constructor.
  144. """
  145. pth = cls.__new__(cls)
  146. pth._vertices = _to_unmasked_float_array(verts)
  147. pth._codes = codes
  148. pth._readonly = False
  149. if internals_from is not None:
  150. pth._should_simplify = internals_from._should_simplify
  151. pth._simplify_threshold = internals_from._simplify_threshold
  152. pth._interpolation_steps = internals_from._interpolation_steps
  153. else:
  154. pth._should_simplify = True
  155. pth._simplify_threshold = mpl.rcParams['path.simplify_threshold']
  156. pth._interpolation_steps = 1
  157. return pth
  158. @classmethod
  159. def _create_closed(cls, vertices):
  160. """
  161. Create a closed polygonal path going through *vertices*.
  162. Unlike ``Path(..., closed=True)``, *vertices* should **not** end with
  163. an entry for the CLOSEPATH; this entry is added by `._create_closed`.
  164. """
  165. v = _to_unmasked_float_array(vertices)
  166. return cls(np.concatenate([v, v[:1]]), closed=True)
  167. def _update_values(self):
  168. self._simplify_threshold = mpl.rcParams['path.simplify_threshold']
  169. self._should_simplify = (
  170. self._simplify_threshold > 0 and
  171. mpl.rcParams['path.simplify'] and
  172. len(self._vertices) >= 128 and
  173. (self._codes is None or np.all(self._codes <= Path.LINETO))
  174. )
  175. @property
  176. def vertices(self):
  177. """The vertices of the `Path` as an (N, 2) array."""
  178. return self._vertices
  179. @vertices.setter
  180. def vertices(self, vertices):
  181. if self._readonly:
  182. raise AttributeError("Can't set vertices on a readonly Path")
  183. self._vertices = vertices
  184. self._update_values()
  185. @property
  186. def codes(self):
  187. """
  188. The list of codes in the `Path` as a 1D array.
  189. Each code is one of `STOP`, `MOVETO`, `LINETO`, `CURVE3`, `CURVE4` or
  190. `CLOSEPOLY`. For codes that correspond to more than one vertex
  191. (`CURVE3` and `CURVE4`), that code will be repeated so that the length
  192. of `vertices` and `codes` is always the same.
  193. """
  194. return self._codes
  195. @codes.setter
  196. def codes(self, codes):
  197. if self._readonly:
  198. raise AttributeError("Can't set codes on a readonly Path")
  199. self._codes = codes
  200. self._update_values()
  201. @property
  202. def simplify_threshold(self):
  203. """
  204. The fraction of a pixel difference below which vertices will
  205. be simplified out.
  206. """
  207. return self._simplify_threshold
  208. @simplify_threshold.setter
  209. def simplify_threshold(self, threshold):
  210. self._simplify_threshold = threshold
  211. @property
  212. def should_simplify(self):
  213. """
  214. `True` if the vertices array should be simplified.
  215. """
  216. return self._should_simplify
  217. @should_simplify.setter
  218. def should_simplify(self, should_simplify):
  219. self._should_simplify = should_simplify
  220. @property
  221. def readonly(self):
  222. """
  223. `True` if the `Path` is read-only.
  224. """
  225. return self._readonly
  226. def copy(self):
  227. """
  228. Return a shallow copy of the `Path`, which will share the
  229. vertices and codes with the source `Path`.
  230. """
  231. return copy.copy(self)
  232. def __deepcopy__(self, memo=None):
  233. """
  234. Return a deepcopy of the `Path`. The `Path` will not be
  235. readonly, even if the source `Path` is.
  236. """
  237. # Deepcopying arrays (vertices, codes) strips the writeable=False flag.
  238. p = copy.deepcopy(super(), memo)
  239. p._readonly = False
  240. return p
  241. deepcopy = __deepcopy__
  242. @classmethod
  243. def make_compound_path_from_polys(cls, XY):
  244. """
  245. Make a compound `Path` object to draw a number of polygons with equal
  246. numbers of sides.
  247. .. plot:: gallery/misc/histogram_path.py
  248. Parameters
  249. ----------
  250. XY : (numpolys, numsides, 2) array
  251. """
  252. # for each poly: 1 for the MOVETO, (numsides-1) for the LINETO, 1 for
  253. # the CLOSEPOLY; the vert for the closepoly is ignored but we still
  254. # need it to keep the codes aligned with the vertices
  255. numpolys, numsides, two = XY.shape
  256. if two != 2:
  257. raise ValueError("The third dimension of 'XY' must be 2")
  258. stride = numsides + 1
  259. nverts = numpolys * stride
  260. verts = np.zeros((nverts, 2))
  261. codes = np.full(nverts, cls.LINETO, dtype=cls.code_type)
  262. codes[0::stride] = cls.MOVETO
  263. codes[numsides::stride] = cls.CLOSEPOLY
  264. for i in range(numsides):
  265. verts[i::stride] = XY[:, i]
  266. return cls(verts, codes)
  267. @classmethod
  268. def make_compound_path(cls, *args):
  269. r"""
  270. Concatenate a list of `Path`\s into a single `Path`, removing all `STOP`\s.
  271. """
  272. if not args:
  273. return Path(np.empty([0, 2], dtype=np.float32))
  274. vertices = np.concatenate([path.vertices for path in args])
  275. codes = np.empty(len(vertices), dtype=cls.code_type)
  276. i = 0
  277. for path in args:
  278. size = len(path.vertices)
  279. if path.codes is None:
  280. if size:
  281. codes[i] = cls.MOVETO
  282. codes[i+1:i+size] = cls.LINETO
  283. else:
  284. codes[i:i+size] = path.codes
  285. i += size
  286. not_stop_mask = codes != cls.STOP # Remove STOPs, as internal STOPs are a bug.
  287. return cls(vertices[not_stop_mask], codes[not_stop_mask])
  288. def __repr__(self):
  289. return f"Path({self.vertices!r}, {self.codes!r})"
  290. def __len__(self):
  291. return len(self.vertices)
  292. def iter_segments(self, transform=None, remove_nans=True, clip=None,
  293. snap=False, stroke_width=1.0, simplify=None,
  294. curves=True, sketch=None):
  295. """
  296. Iterate over all curve segments in the path.
  297. Each iteration returns a pair ``(vertices, code)``, where ``vertices``
  298. is a sequence of 1-3 coordinate pairs, and ``code`` is a `Path` code.
  299. Additionally, this method can provide a number of standard cleanups and
  300. conversions to the path.
  301. Parameters
  302. ----------
  303. transform : None or :class:`~matplotlib.transforms.Transform`
  304. If not None, the given affine transformation will be applied to the
  305. path.
  306. remove_nans : bool, optional
  307. Whether to remove all NaNs from the path and skip over them using
  308. MOVETO commands.
  309. clip : None or (float, float, float, float), optional
  310. If not None, must be a four-tuple (x1, y1, x2, y2)
  311. defining a rectangle in which to clip the path.
  312. snap : None or bool, optional
  313. If True, snap all nodes to pixels; if False, don't snap them.
  314. If None, snap if the path contains only segments
  315. parallel to the x or y axes, and no more than 1024 of them.
  316. stroke_width : float, optional
  317. The width of the stroke being drawn (used for path snapping).
  318. simplify : None or bool, optional
  319. Whether to simplify the path by removing vertices
  320. that do not affect its appearance. If None, use the
  321. :attr:`should_simplify` attribute. See also :rc:`path.simplify`
  322. and :rc:`path.simplify_threshold`.
  323. curves : bool, optional
  324. If True, curve segments will be returned as curve segments.
  325. If False, all curves will be converted to line segments.
  326. sketch : None or sequence, optional
  327. If not None, must be a 3-tuple of the form
  328. (scale, length, randomness), representing the sketch parameters.
  329. """
  330. if not len(self):
  331. return
  332. cleaned = self.cleaned(transform=transform,
  333. remove_nans=remove_nans, clip=clip,
  334. snap=snap, stroke_width=stroke_width,
  335. simplify=simplify, curves=curves,
  336. sketch=sketch)
  337. # Cache these object lookups for performance in the loop.
  338. NUM_VERTICES_FOR_CODE = self.NUM_VERTICES_FOR_CODE
  339. STOP = self.STOP
  340. vertices = iter(cleaned.vertices)
  341. codes = iter(cleaned.codes)
  342. for curr_vertices, code in zip(vertices, codes):
  343. if code == STOP:
  344. break
  345. extra_vertices = NUM_VERTICES_FOR_CODE[code] - 1
  346. if extra_vertices:
  347. for i in range(extra_vertices):
  348. next(codes)
  349. curr_vertices = np.append(curr_vertices, next(vertices))
  350. yield curr_vertices, code
  351. def iter_bezier(self, **kwargs):
  352. """
  353. Iterate over each Bézier curve (lines included) in a `Path`.
  354. Parameters
  355. ----------
  356. **kwargs
  357. Forwarded to `.iter_segments`.
  358. Yields
  359. ------
  360. B : `~matplotlib.bezier.BezierSegment`
  361. The Bézier curves that make up the current path. Note in particular
  362. that freestanding points are Bézier curves of order 0, and lines
  363. are Bézier curves of order 1 (with two control points).
  364. code : `~matplotlib.path.Path.code_type`
  365. The code describing what kind of curve is being returned.
  366. `MOVETO`, `LINETO`, `CURVE3`, and `CURVE4` correspond to
  367. Bézier curves with 1, 2, 3, and 4 control points (respectively).
  368. `CLOSEPOLY` is a `LINETO` with the control points correctly
  369. chosen based on the start/end points of the current stroke.
  370. """
  371. first_vert = None
  372. prev_vert = None
  373. for verts, code in self.iter_segments(**kwargs):
  374. if first_vert is None:
  375. if code != Path.MOVETO:
  376. raise ValueError("Malformed path, must start with MOVETO.")
  377. if code == Path.MOVETO: # a point is like "CURVE1"
  378. first_vert = verts
  379. yield BezierSegment(np.array([first_vert])), code
  380. elif code == Path.LINETO: # "CURVE2"
  381. yield BezierSegment(np.array([prev_vert, verts])), code
  382. elif code == Path.CURVE3:
  383. yield BezierSegment(np.array([prev_vert, verts[:2],
  384. verts[2:]])), code
  385. elif code == Path.CURVE4:
  386. yield BezierSegment(np.array([prev_vert, verts[:2],
  387. verts[2:4], verts[4:]])), code
  388. elif code == Path.CLOSEPOLY:
  389. yield BezierSegment(np.array([prev_vert, first_vert])), code
  390. elif code == Path.STOP:
  391. return
  392. else:
  393. raise ValueError(f"Invalid Path.code_type: {code}")
  394. prev_vert = verts[-2:]
  395. def _iter_connected_components(self):
  396. """Return subpaths split at MOVETOs."""
  397. if self.codes is None:
  398. yield self
  399. else:
  400. idxs = np.append((self.codes == Path.MOVETO).nonzero()[0], len(self.codes))
  401. for sl in map(slice, idxs, idxs[1:]):
  402. yield Path._fast_from_codes_and_verts(
  403. self.vertices[sl], self.codes[sl], self)
  404. def cleaned(self, transform=None, remove_nans=False, clip=None,
  405. *, simplify=False, curves=False,
  406. stroke_width=1.0, snap=False, sketch=None):
  407. """
  408. Return a new `Path` with vertices and codes cleaned according to the
  409. parameters.
  410. See Also
  411. --------
  412. Path.iter_segments : for details of the keyword arguments.
  413. """
  414. vertices, codes = _path.cleanup_path(
  415. self, transform, remove_nans, clip, snap, stroke_width, simplify,
  416. curves, sketch)
  417. pth = Path._fast_from_codes_and_verts(vertices, codes, self)
  418. if not simplify:
  419. pth._should_simplify = False
  420. return pth
  421. def transformed(self, transform):
  422. """
  423. Return a transformed copy of the path.
  424. See Also
  425. --------
  426. matplotlib.transforms.TransformedPath
  427. A specialized path class that will cache the transformed result and
  428. automatically update when the transform changes.
  429. """
  430. return Path(transform.transform(self.vertices), self.codes,
  431. self._interpolation_steps)
  432. def contains_point(self, point, transform=None, radius=0.0):
  433. """
  434. Return whether the area enclosed by the path contains the given point.
  435. The path is always treated as closed; i.e. if the last code is not
  436. `CLOSEPOLY` an implicit segment connecting the last vertex to the first
  437. vertex is assumed.
  438. Parameters
  439. ----------
  440. point : (float, float)
  441. The point (x, y) to check.
  442. transform : `~matplotlib.transforms.Transform`, optional
  443. If not ``None``, *point* will be compared to ``self`` transformed
  444. by *transform*; i.e. for a correct check, *transform* should
  445. transform the path into the coordinate system of *point*.
  446. radius : float, default: 0
  447. Additional margin on the path in coordinates of *point*.
  448. The path is extended tangentially by *radius/2*; i.e. if you would
  449. draw the path with a linewidth of *radius*, all points on the line
  450. would still be considered to be contained in the area. Conversely,
  451. negative values shrink the area: Points on the imaginary line
  452. will be considered outside the area.
  453. Returns
  454. -------
  455. bool
  456. Notes
  457. -----
  458. The current algorithm has some limitations:
  459. - The result is undefined for points exactly at the boundary
  460. (i.e. at the path shifted by *radius/2*).
  461. - The result is undefined if there is no enclosed area, i.e. all
  462. vertices are on a straight line.
  463. - If bounding lines start to cross each other due to *radius* shift,
  464. the result is not guaranteed to be correct.
  465. """
  466. if transform is not None:
  467. transform = transform.frozen()
  468. # `point_in_path` does not handle nonlinear transforms, so we
  469. # transform the path ourselves. If *transform* is affine, letting
  470. # `point_in_path` handle the transform avoids allocating an extra
  471. # buffer.
  472. if transform and not transform.is_affine:
  473. self = transform.transform_path(self)
  474. transform = None
  475. return _path.point_in_path(point[0], point[1], radius, self, transform)
  476. def contains_points(self, points, transform=None, radius=0.0):
  477. """
  478. Return whether the area enclosed by the path contains the given points.
  479. The path is always treated as closed; i.e. if the last code is not
  480. `CLOSEPOLY` an implicit segment connecting the last vertex to the first
  481. vertex is assumed.
  482. Parameters
  483. ----------
  484. points : (N, 2) array
  485. The points to check. Columns contain x and y values.
  486. transform : `~matplotlib.transforms.Transform`, optional
  487. If not ``None``, *points* will be compared to ``self`` transformed
  488. by *transform*; i.e. for a correct check, *transform* should
  489. transform the path into the coordinate system of *points*.
  490. radius : float, default: 0
  491. Additional margin on the path in coordinates of *points*.
  492. The path is extended tangentially by *radius/2*; i.e. if you would
  493. draw the path with a linewidth of *radius*, all points on the line
  494. would still be considered to be contained in the area. Conversely,
  495. negative values shrink the area: Points on the imaginary line
  496. will be considered outside the area.
  497. Returns
  498. -------
  499. length-N bool array
  500. Notes
  501. -----
  502. The current algorithm has some limitations:
  503. - The result is undefined for points exactly at the boundary
  504. (i.e. at the path shifted by *radius/2*).
  505. - The result is undefined if there is no enclosed area, i.e. all
  506. vertices are on a straight line.
  507. - If bounding lines start to cross each other due to *radius* shift,
  508. the result is not guaranteed to be correct.
  509. """
  510. if transform is not None:
  511. transform = transform.frozen()
  512. result = _path.points_in_path(points, radius, self, transform)
  513. return result.astype('bool')
  514. def contains_path(self, path, transform=None):
  515. """
  516. Return whether this (closed) path completely contains the given path.
  517. If *transform* is not ``None``, the path will be transformed before
  518. checking for containment.
  519. """
  520. if transform is not None:
  521. transform = transform.frozen()
  522. return _path.path_in_path(self, None, path, transform)
  523. def get_extents(self, transform=None, **kwargs):
  524. """
  525. Get Bbox of the path.
  526. Parameters
  527. ----------
  528. transform : `~matplotlib.transforms.Transform`, optional
  529. Transform to apply to path before computing extents, if any.
  530. **kwargs
  531. Forwarded to `.iter_bezier`.
  532. Returns
  533. -------
  534. matplotlib.transforms.Bbox
  535. The extents of the path Bbox([[xmin, ymin], [xmax, ymax]])
  536. """
  537. from .transforms import Bbox
  538. if transform is not None:
  539. self = transform.transform_path(self)
  540. if self.codes is None:
  541. xys = self.vertices
  542. elif len(np.intersect1d(self.codes, [Path.CURVE3, Path.CURVE4])) == 0:
  543. # Optimization for the straight line case.
  544. # Instead of iterating through each curve, consider
  545. # each line segment's end-points
  546. # (recall that STOP and CLOSEPOLY vertices are ignored)
  547. xys = self.vertices[np.isin(self.codes,
  548. [Path.MOVETO, Path.LINETO])]
  549. else:
  550. xys = []
  551. for curve, code in self.iter_bezier(**kwargs):
  552. # places where the derivative is zero can be extrema
  553. _, dzeros = curve.axis_aligned_extrema()
  554. # as can the ends of the curve
  555. xys.append(curve([0, *dzeros, 1]))
  556. xys = np.concatenate(xys)
  557. if len(xys):
  558. return Bbox([xys.min(axis=0), xys.max(axis=0)])
  559. else:
  560. return Bbox.null()
  561. def intersects_path(self, other, filled=True):
  562. """
  563. Return whether if this path intersects another given path.
  564. If *filled* is True, then this also returns True if one path completely
  565. encloses the other (i.e., the paths are treated as filled).
  566. """
  567. return _path.path_intersects_path(self, other, filled)
  568. def intersects_bbox(self, bbox, filled=True):
  569. """
  570. Return whether this path intersects a given `~.transforms.Bbox`.
  571. If *filled* is True, then this also returns True if the path completely
  572. encloses the `.Bbox` (i.e., the path is treated as filled).
  573. The bounding box is always considered filled.
  574. """
  575. return _path.path_intersects_rectangle(
  576. self, bbox.x0, bbox.y0, bbox.x1, bbox.y1, filled)
  577. def interpolated(self, steps):
  578. """
  579. Return a new path resampled to length N x *steps*.
  580. Codes other than `LINETO` are not handled correctly.
  581. """
  582. if steps == 1:
  583. return self
  584. vertices = simple_linear_interpolation(self.vertices, steps)
  585. codes = self.codes
  586. if codes is not None:
  587. new_codes = np.full((len(codes) - 1) * steps + 1, Path.LINETO,
  588. dtype=self.code_type)
  589. new_codes[0::steps] = codes
  590. else:
  591. new_codes = None
  592. return Path(vertices, new_codes)
  593. def to_polygons(self, transform=None, width=0, height=0, closed_only=True):
  594. """
  595. Convert this path to a list of polygons or polylines. Each
  596. polygon/polyline is an (N, 2) array of vertices. In other words,
  597. each polygon has no `MOVETO` instructions or curves. This
  598. is useful for displaying in backends that do not support
  599. compound paths or Bézier curves.
  600. If *width* and *height* are both non-zero then the lines will
  601. be simplified so that vertices outside of (0, 0), (width,
  602. height) will be clipped.
  603. If *closed_only* is `True` (default), only closed polygons,
  604. with the last point being the same as the first point, will be
  605. returned. Any unclosed polylines in the path will be
  606. explicitly closed. If *closed_only* is `False`, any unclosed
  607. polygons in the path will be returned as unclosed polygons,
  608. and the closed polygons will be returned explicitly closed by
  609. setting the last point to the same as the first point.
  610. """
  611. if len(self.vertices) == 0:
  612. return []
  613. if transform is not None:
  614. transform = transform.frozen()
  615. if self.codes is None and (width == 0 or height == 0):
  616. vertices = self.vertices
  617. if closed_only:
  618. if len(vertices) < 3:
  619. return []
  620. elif np.any(vertices[0] != vertices[-1]):
  621. vertices = [*vertices, vertices[0]]
  622. if transform is None:
  623. return [vertices]
  624. else:
  625. return [transform.transform(vertices)]
  626. # Deal with the case where there are curves and/or multiple
  627. # subpaths (using extension code)
  628. return _path.convert_path_to_polygons(
  629. self, transform, width, height, closed_only)
  630. _unit_rectangle = None
  631. @classmethod
  632. def unit_rectangle(cls):
  633. """
  634. Return a `Path` instance of the unit rectangle from (0, 0) to (1, 1).
  635. """
  636. if cls._unit_rectangle is None:
  637. cls._unit_rectangle = cls([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]],
  638. closed=True, readonly=True)
  639. return cls._unit_rectangle
  640. _unit_regular_polygons = WeakValueDictionary()
  641. @classmethod
  642. def unit_regular_polygon(cls, numVertices):
  643. """
  644. Return a :class:`Path` instance for a unit regular polygon with the
  645. given *numVertices* such that the circumscribing circle has radius 1.0,
  646. centered at (0, 0).
  647. """
  648. if numVertices <= 16:
  649. path = cls._unit_regular_polygons.get(numVertices)
  650. else:
  651. path = None
  652. if path is None:
  653. theta = ((2 * np.pi / numVertices) * np.arange(numVertices + 1)
  654. # This initial rotation is to make sure the polygon always
  655. # "points-up".
  656. + np.pi / 2)
  657. verts = np.column_stack((np.cos(theta), np.sin(theta)))
  658. path = cls(verts, closed=True, readonly=True)
  659. if numVertices <= 16:
  660. cls._unit_regular_polygons[numVertices] = path
  661. return path
  662. _unit_regular_stars = WeakValueDictionary()
  663. @classmethod
  664. def unit_regular_star(cls, numVertices, innerCircle=0.5):
  665. """
  666. Return a :class:`Path` for a unit regular star with the given
  667. numVertices and radius of 1.0, centered at (0, 0).
  668. """
  669. if numVertices <= 16:
  670. path = cls._unit_regular_stars.get((numVertices, innerCircle))
  671. else:
  672. path = None
  673. if path is None:
  674. ns2 = numVertices * 2
  675. theta = (2*np.pi/ns2 * np.arange(ns2 + 1))
  676. # This initial rotation is to make sure the polygon always
  677. # "points-up"
  678. theta += np.pi / 2.0
  679. r = np.ones(ns2 + 1)
  680. r[1::2] = innerCircle
  681. verts = (r * np.vstack((np.cos(theta), np.sin(theta)))).T
  682. path = cls(verts, closed=True, readonly=True)
  683. if numVertices <= 16:
  684. cls._unit_regular_stars[(numVertices, innerCircle)] = path
  685. return path
  686. @classmethod
  687. def unit_regular_asterisk(cls, numVertices):
  688. """
  689. Return a :class:`Path` for a unit regular asterisk with the given
  690. numVertices and radius of 1.0, centered at (0, 0).
  691. """
  692. return cls.unit_regular_star(numVertices, 0.0)
  693. _unit_circle = None
  694. @classmethod
  695. def unit_circle(cls):
  696. """
  697. Return the readonly :class:`Path` of the unit circle.
  698. For most cases, :func:`Path.circle` will be what you want.
  699. """
  700. if cls._unit_circle is None:
  701. cls._unit_circle = cls.circle(center=(0, 0), radius=1,
  702. readonly=True)
  703. return cls._unit_circle
  704. @classmethod
  705. def circle(cls, center=(0., 0.), radius=1., readonly=False):
  706. """
  707. Return a `Path` representing a circle of a given radius and center.
  708. Parameters
  709. ----------
  710. center : (float, float), default: (0, 0)
  711. The center of the circle.
  712. radius : float, default: 1
  713. The radius of the circle.
  714. readonly : bool
  715. Whether the created path should have the "readonly" argument
  716. set when creating the Path instance.
  717. Notes
  718. -----
  719. The circle is approximated using 8 cubic Bézier curves, as described in
  720. Lancaster, Don. `Approximating a Circle or an Ellipse Using Four
  721. Bezier Cubic Splines <https://www.tinaja.com/glib/ellipse4.pdf>`_.
  722. """
  723. MAGIC = 0.2652031
  724. SQRTHALF = np.sqrt(0.5)
  725. MAGIC45 = SQRTHALF * MAGIC
  726. vertices = np.array([[0.0, -1.0],
  727. [MAGIC, -1.0],
  728. [SQRTHALF-MAGIC45, -SQRTHALF-MAGIC45],
  729. [SQRTHALF, -SQRTHALF],
  730. [SQRTHALF+MAGIC45, -SQRTHALF+MAGIC45],
  731. [1.0, -MAGIC],
  732. [1.0, 0.0],
  733. [1.0, MAGIC],
  734. [SQRTHALF+MAGIC45, SQRTHALF-MAGIC45],
  735. [SQRTHALF, SQRTHALF],
  736. [SQRTHALF-MAGIC45, SQRTHALF+MAGIC45],
  737. [MAGIC, 1.0],
  738. [0.0, 1.0],
  739. [-MAGIC, 1.0],
  740. [-SQRTHALF+MAGIC45, SQRTHALF+MAGIC45],
  741. [-SQRTHALF, SQRTHALF],
  742. [-SQRTHALF-MAGIC45, SQRTHALF-MAGIC45],
  743. [-1.0, MAGIC],
  744. [-1.0, 0.0],
  745. [-1.0, -MAGIC],
  746. [-SQRTHALF-MAGIC45, -SQRTHALF+MAGIC45],
  747. [-SQRTHALF, -SQRTHALF],
  748. [-SQRTHALF+MAGIC45, -SQRTHALF-MAGIC45],
  749. [-MAGIC, -1.0],
  750. [0.0, -1.0],
  751. [0.0, -1.0]],
  752. dtype=float)
  753. codes = [cls.CURVE4] * 26
  754. codes[0] = cls.MOVETO
  755. codes[-1] = cls.CLOSEPOLY
  756. return Path(vertices * radius + center, codes, readonly=readonly)
  757. _unit_circle_righthalf = None
  758. @classmethod
  759. def unit_circle_righthalf(cls):
  760. """
  761. Return a `Path` of the right half of a unit circle.
  762. See `Path.circle` for the reference on the approximation used.
  763. """
  764. if cls._unit_circle_righthalf is None:
  765. MAGIC = 0.2652031
  766. SQRTHALF = np.sqrt(0.5)
  767. MAGIC45 = SQRTHALF * MAGIC
  768. vertices = np.array(
  769. [[0.0, -1.0],
  770. [MAGIC, -1.0],
  771. [SQRTHALF-MAGIC45, -SQRTHALF-MAGIC45],
  772. [SQRTHALF, -SQRTHALF],
  773. [SQRTHALF+MAGIC45, -SQRTHALF+MAGIC45],
  774. [1.0, -MAGIC],
  775. [1.0, 0.0],
  776. [1.0, MAGIC],
  777. [SQRTHALF+MAGIC45, SQRTHALF-MAGIC45],
  778. [SQRTHALF, SQRTHALF],
  779. [SQRTHALF-MAGIC45, SQRTHALF+MAGIC45],
  780. [MAGIC, 1.0],
  781. [0.0, 1.0],
  782. [0.0, -1.0]],
  783. float)
  784. codes = np.full(14, cls.CURVE4, dtype=cls.code_type)
  785. codes[0] = cls.MOVETO
  786. codes[-1] = cls.CLOSEPOLY
  787. cls._unit_circle_righthalf = cls(vertices, codes, readonly=True)
  788. return cls._unit_circle_righthalf
  789. @classmethod
  790. def arc(cls, theta1, theta2, n=None, is_wedge=False):
  791. """
  792. Return a `Path` for the unit circle arc from angles *theta1* to
  793. *theta2* (in degrees).
  794. *theta2* is unwrapped to produce the shortest arc within 360 degrees.
  795. That is, if *theta2* > *theta1* + 360, the arc will be from *theta1* to
  796. *theta2* - 360 and not a full circle plus some extra overlap.
  797. If *n* is provided, it is the number of spline segments to make.
  798. If *n* is not provided, the number of spline segments is
  799. determined based on the delta between *theta1* and *theta2*.
  800. Masionobe, L. 2003. `Drawing an elliptical arc using
  801. polylines, quadratic or cubic Bezier curves
  802. <https://web.archive.org/web/20190318044212/http://www.spaceroots.org/documents/ellipse/index.html>`_.
  803. """
  804. halfpi = np.pi * 0.5
  805. eta1 = theta1
  806. eta2 = theta2 - 360 * np.floor((theta2 - theta1) / 360)
  807. # Ensure 2pi range is not flattened to 0 due to floating-point errors,
  808. # but don't try to expand existing 0 range.
  809. if theta2 != theta1 and eta2 <= eta1:
  810. eta2 += 360
  811. eta1, eta2 = np.deg2rad([eta1, eta2])
  812. # number of curve segments to make
  813. if n is None:
  814. n = int(2 ** np.ceil((eta2 - eta1) / halfpi))
  815. if n < 1:
  816. raise ValueError("n must be >= 1 or None")
  817. deta = (eta2 - eta1) / n
  818. t = np.tan(0.5 * deta)
  819. alpha = np.sin(deta) * (np.sqrt(4.0 + 3.0 * t * t) - 1) / 3.0
  820. steps = np.linspace(eta1, eta2, n + 1, True)
  821. cos_eta = np.cos(steps)
  822. sin_eta = np.sin(steps)
  823. xA = cos_eta[:-1]
  824. yA = sin_eta[:-1]
  825. xA_dot = -yA
  826. yA_dot = xA
  827. xB = cos_eta[1:]
  828. yB = sin_eta[1:]
  829. xB_dot = -yB
  830. yB_dot = xB
  831. if is_wedge:
  832. length = n * 3 + 4
  833. vertices = np.zeros((length, 2), float)
  834. codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
  835. vertices[1] = [xA[0], yA[0]]
  836. codes[0:2] = [cls.MOVETO, cls.LINETO]
  837. codes[-2:] = [cls.LINETO, cls.CLOSEPOLY]
  838. vertex_offset = 2
  839. end = length - 2
  840. else:
  841. length = n * 3 + 1
  842. vertices = np.empty((length, 2), float)
  843. codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
  844. vertices[0] = [xA[0], yA[0]]
  845. codes[0] = cls.MOVETO
  846. vertex_offset = 1
  847. end = length
  848. vertices[vertex_offset:end:3, 0] = xA + alpha * xA_dot
  849. vertices[vertex_offset:end:3, 1] = yA + alpha * yA_dot
  850. vertices[vertex_offset+1:end:3, 0] = xB - alpha * xB_dot
  851. vertices[vertex_offset+1:end:3, 1] = yB - alpha * yB_dot
  852. vertices[vertex_offset+2:end:3, 0] = xB
  853. vertices[vertex_offset+2:end:3, 1] = yB
  854. return cls(vertices, codes, readonly=True)
  855. @classmethod
  856. def wedge(cls, theta1, theta2, n=None):
  857. """
  858. Return a `Path` for the unit circle wedge from angles *theta1* to
  859. *theta2* (in degrees).
  860. *theta2* is unwrapped to produce the shortest wedge within 360 degrees.
  861. That is, if *theta2* > *theta1* + 360, the wedge will be from *theta1*
  862. to *theta2* - 360 and not a full circle plus some extra overlap.
  863. If *n* is provided, it is the number of spline segments to make.
  864. If *n* is not provided, the number of spline segments is
  865. determined based on the delta between *theta1* and *theta2*.
  866. See `Path.arc` for the reference on the approximation used.
  867. """
  868. return cls.arc(theta1, theta2, n, True)
  869. @staticmethod
  870. @lru_cache(8)
  871. def hatch(hatchpattern, density=6):
  872. """
  873. Given a hatch specifier, *hatchpattern*, generates a `Path` that
  874. can be used in a repeated hatching pattern. *density* is the
  875. number of lines per unit square.
  876. """
  877. from matplotlib.hatch import get_path
  878. return (get_path(hatchpattern, density)
  879. if hatchpattern is not None else None)
  880. def clip_to_bbox(self, bbox, inside=True):
  881. """
  882. Clip the path to the given bounding box.
  883. The path must be made up of one or more closed polygons. This
  884. algorithm will not behave correctly for unclosed paths.
  885. If *inside* is `True`, clip to the inside of the box, otherwise
  886. to the outside of the box.
  887. """
  888. verts = _path.clip_path_to_rect(self, bbox, inside)
  889. paths = [Path(poly) for poly in verts]
  890. return self.make_compound_path(*paths)
  891. def get_path_collection_extents(
  892. master_transform, paths, transforms, offsets, offset_transform):
  893. r"""
  894. Get bounding box of a `.PathCollection`\s internal objects.
  895. That is, given a sequence of `Path`\s, `.Transform`\s objects, and offsets, as found
  896. in a `.PathCollection`, return the bounding box that encapsulates all of them.
  897. Parameters
  898. ----------
  899. master_transform : `~matplotlib.transforms.Transform`
  900. Global transformation applied to all paths.
  901. paths : list of `Path`
  902. transforms : list of `~matplotlib.transforms.Affine2DBase`
  903. If non-empty, this overrides *master_transform*.
  904. offsets : (N, 2) array-like
  905. offset_transform : `~matplotlib.transforms.Affine2DBase`
  906. Transform applied to the offsets before offsetting the path.
  907. Notes
  908. -----
  909. The way that *paths*, *transforms* and *offsets* are combined follows the same
  910. method as for collections: each is iterated over independently, so if you have 3
  911. paths (A, B, C), 2 transforms (α, β) and 1 offset (O), their combinations are as
  912. follows:
  913. - (A, α, O)
  914. - (B, β, O)
  915. - (C, α, O)
  916. """
  917. from .transforms import Bbox
  918. if len(paths) == 0:
  919. raise ValueError("No paths provided")
  920. if len(offsets) == 0:
  921. _api.warn_deprecated(
  922. "3.8", message="Calling get_path_collection_extents() with an"
  923. " empty offsets list is deprecated since %(since)s. Support will"
  924. " be removed %(removal)s.")
  925. extents, minpos = _path.get_path_collection_extents(
  926. master_transform, paths, np.atleast_3d(transforms),
  927. offsets, offset_transform)
  928. return Bbox.from_extents(*extents, minpos=minpos)