path.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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 and len(vertices):
  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):
  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. cls = type(self)
  239. memo[id(self)] = p = cls.__new__(cls)
  240. for k, v in self.__dict__.items():
  241. setattr(p, k, copy.deepcopy(v, memo))
  242. p._readonly = False
  243. return p
  244. def deepcopy(self, memo=None):
  245. """
  246. Return a deep copy of the `Path`. The `Path` will not be readonly,
  247. even if the source `Path` is.
  248. Parameters
  249. ----------
  250. memo : dict, optional
  251. A dictionary to use for memoizing, passed to `copy.deepcopy`.
  252. Returns
  253. -------
  254. Path
  255. A deep copy of the `Path`, but not readonly.
  256. """
  257. return copy.deepcopy(self, memo)
  258. @classmethod
  259. def make_compound_path_from_polys(cls, XY):
  260. """
  261. Make a compound `Path` object to draw a number of polygons with equal
  262. numbers of sides.
  263. .. plot:: gallery/misc/histogram_path.py
  264. Parameters
  265. ----------
  266. XY : (numpolys, numsides, 2) array
  267. """
  268. # for each poly: 1 for the MOVETO, (numsides-1) for the LINETO, 1 for
  269. # the CLOSEPOLY; the vert for the closepoly is ignored but we still
  270. # need it to keep the codes aligned with the vertices
  271. numpolys, numsides, two = XY.shape
  272. if two != 2:
  273. raise ValueError("The third dimension of 'XY' must be 2")
  274. stride = numsides + 1
  275. nverts = numpolys * stride
  276. verts = np.zeros((nverts, 2))
  277. codes = np.full(nverts, cls.LINETO, dtype=cls.code_type)
  278. codes[0::stride] = cls.MOVETO
  279. codes[numsides::stride] = cls.CLOSEPOLY
  280. for i in range(numsides):
  281. verts[i::stride] = XY[:, i]
  282. return cls(verts, codes)
  283. @classmethod
  284. def make_compound_path(cls, *args):
  285. r"""
  286. Concatenate a list of `Path`\s into a single `Path`, removing all `STOP`\s.
  287. """
  288. if not args:
  289. return Path(np.empty([0, 2], dtype=np.float32))
  290. vertices = np.concatenate([path.vertices for path in args])
  291. codes = np.empty(len(vertices), dtype=cls.code_type)
  292. i = 0
  293. for path in args:
  294. size = len(path.vertices)
  295. if path.codes is None:
  296. if size:
  297. codes[i] = cls.MOVETO
  298. codes[i+1:i+size] = cls.LINETO
  299. else:
  300. codes[i:i+size] = path.codes
  301. i += size
  302. not_stop_mask = codes != cls.STOP # Remove STOPs, as internal STOPs are a bug.
  303. return cls(vertices[not_stop_mask], codes[not_stop_mask])
  304. def __repr__(self):
  305. return f"Path({self.vertices!r}, {self.codes!r})"
  306. def __len__(self):
  307. return len(self.vertices)
  308. def iter_segments(self, transform=None, remove_nans=True, clip=None,
  309. snap=False, stroke_width=1.0, simplify=None,
  310. curves=True, sketch=None):
  311. """
  312. Iterate over all curve segments in the path.
  313. Each iteration returns a pair ``(vertices, code)``, where ``vertices``
  314. is a sequence of 1-3 coordinate pairs, and ``code`` is a `Path` code.
  315. Additionally, this method can provide a number of standard cleanups and
  316. conversions to the path.
  317. Parameters
  318. ----------
  319. transform : None or :class:`~matplotlib.transforms.Transform`
  320. If not None, the given affine transformation will be applied to the
  321. path.
  322. remove_nans : bool, optional
  323. Whether to remove all NaNs from the path and skip over them using
  324. MOVETO commands.
  325. clip : None or (float, float, float, float), optional
  326. If not None, must be a four-tuple (x1, y1, x2, y2)
  327. defining a rectangle in which to clip the path.
  328. snap : None or bool, optional
  329. If True, snap all nodes to pixels; if False, don't snap them.
  330. If None, snap if the path contains only segments
  331. parallel to the x or y axes, and no more than 1024 of them.
  332. stroke_width : float, optional
  333. The width of the stroke being drawn (used for path snapping).
  334. simplify : None or bool, optional
  335. Whether to simplify the path by removing vertices
  336. that do not affect its appearance. If None, use the
  337. :attr:`should_simplify` attribute. See also :rc:`path.simplify`
  338. and :rc:`path.simplify_threshold`.
  339. curves : bool, optional
  340. If True, curve segments will be returned as curve segments.
  341. If False, all curves will be converted to line segments.
  342. sketch : None or sequence, optional
  343. If not None, must be a 3-tuple of the form
  344. (scale, length, randomness), representing the sketch parameters.
  345. """
  346. if not len(self):
  347. return
  348. cleaned = self.cleaned(transform=transform,
  349. remove_nans=remove_nans, clip=clip,
  350. snap=snap, stroke_width=stroke_width,
  351. simplify=simplify, curves=curves,
  352. sketch=sketch)
  353. # Cache these object lookups for performance in the loop.
  354. NUM_VERTICES_FOR_CODE = self.NUM_VERTICES_FOR_CODE
  355. STOP = self.STOP
  356. vertices = iter(cleaned.vertices)
  357. codes = iter(cleaned.codes)
  358. for curr_vertices, code in zip(vertices, codes):
  359. if code == STOP:
  360. break
  361. extra_vertices = NUM_VERTICES_FOR_CODE[code] - 1
  362. if extra_vertices:
  363. for i in range(extra_vertices):
  364. next(codes)
  365. curr_vertices = np.append(curr_vertices, next(vertices))
  366. yield curr_vertices, code
  367. def iter_bezier(self, **kwargs):
  368. """
  369. Iterate over each Bézier curve (lines included) in a `Path`.
  370. Parameters
  371. ----------
  372. **kwargs
  373. Forwarded to `.iter_segments`.
  374. Yields
  375. ------
  376. B : `~matplotlib.bezier.BezierSegment`
  377. The Bézier curves that make up the current path. Note in particular
  378. that freestanding points are Bézier curves of order 0, and lines
  379. are Bézier curves of order 1 (with two control points).
  380. code : `~matplotlib.path.Path.code_type`
  381. The code describing what kind of curve is being returned.
  382. `MOVETO`, `LINETO`, `CURVE3`, and `CURVE4` correspond to
  383. Bézier curves with 1, 2, 3, and 4 control points (respectively).
  384. `CLOSEPOLY` is a `LINETO` with the control points correctly
  385. chosen based on the start/end points of the current stroke.
  386. """
  387. first_vert = None
  388. prev_vert = None
  389. for verts, code in self.iter_segments(**kwargs):
  390. if first_vert is None:
  391. if code != Path.MOVETO:
  392. raise ValueError("Malformed path, must start with MOVETO.")
  393. if code == Path.MOVETO: # a point is like "CURVE1"
  394. first_vert = verts
  395. yield BezierSegment(np.array([first_vert])), code
  396. elif code == Path.LINETO: # "CURVE2"
  397. yield BezierSegment(np.array([prev_vert, verts])), code
  398. elif code == Path.CURVE3:
  399. yield BezierSegment(np.array([prev_vert, verts[:2],
  400. verts[2:]])), code
  401. elif code == Path.CURVE4:
  402. yield BezierSegment(np.array([prev_vert, verts[:2],
  403. verts[2:4], verts[4:]])), code
  404. elif code == Path.CLOSEPOLY:
  405. yield BezierSegment(np.array([prev_vert, first_vert])), code
  406. elif code == Path.STOP:
  407. return
  408. else:
  409. raise ValueError(f"Invalid Path.code_type: {code}")
  410. prev_vert = verts[-2:]
  411. def _iter_connected_components(self):
  412. """Return subpaths split at MOVETOs."""
  413. if self.codes is None:
  414. yield self
  415. else:
  416. idxs = np.append((self.codes == Path.MOVETO).nonzero()[0], len(self.codes))
  417. for sl in map(slice, idxs, idxs[1:]):
  418. yield Path._fast_from_codes_and_verts(
  419. self.vertices[sl], self.codes[sl], self)
  420. def cleaned(self, transform=None, remove_nans=False, clip=None,
  421. *, simplify=False, curves=False,
  422. stroke_width=1.0, snap=False, sketch=None):
  423. """
  424. Return a new `Path` with vertices and codes cleaned according to the
  425. parameters.
  426. See Also
  427. --------
  428. Path.iter_segments : for details of the keyword arguments.
  429. """
  430. vertices, codes = _path.cleanup_path(
  431. self, transform, remove_nans, clip, snap, stroke_width, simplify,
  432. curves, sketch)
  433. pth = Path._fast_from_codes_and_verts(vertices, codes, self)
  434. if not simplify:
  435. pth._should_simplify = False
  436. return pth
  437. def transformed(self, transform):
  438. """
  439. Return a transformed copy of the path.
  440. See Also
  441. --------
  442. matplotlib.transforms.TransformedPath
  443. A specialized path class that will cache the transformed result and
  444. automatically update when the transform changes.
  445. """
  446. return Path(transform.transform(self.vertices), self.codes,
  447. self._interpolation_steps)
  448. def contains_point(self, point, transform=None, radius=0.0):
  449. """
  450. Return whether the area enclosed by the path contains the given point.
  451. The path is always treated as closed; i.e. if the last code is not
  452. `CLOSEPOLY` an implicit segment connecting the last vertex to the first
  453. vertex is assumed.
  454. Parameters
  455. ----------
  456. point : (float, float)
  457. The point (x, y) to check.
  458. transform : `~matplotlib.transforms.Transform`, optional
  459. If not ``None``, *point* will be compared to ``self`` transformed
  460. by *transform*; i.e. for a correct check, *transform* should
  461. transform the path into the coordinate system of *point*.
  462. radius : float, default: 0
  463. Additional margin on the path in coordinates of *point*.
  464. The path is extended tangentially by *radius/2*; i.e. if you would
  465. draw the path with a linewidth of *radius*, all points on the line
  466. would still be considered to be contained in the area. Conversely,
  467. negative values shrink the area: Points on the imaginary line
  468. will be considered outside the area.
  469. Returns
  470. -------
  471. bool
  472. Notes
  473. -----
  474. The current algorithm has some limitations:
  475. - The result is undefined for points exactly at the boundary
  476. (i.e. at the path shifted by *radius/2*).
  477. - The result is undefined if there is no enclosed area, i.e. all
  478. vertices are on a straight line.
  479. - If bounding lines start to cross each other due to *radius* shift,
  480. the result is not guaranteed to be correct.
  481. """
  482. if transform is not None:
  483. transform = transform.frozen()
  484. # `point_in_path` does not handle nonlinear transforms, so we
  485. # transform the path ourselves. If *transform* is affine, letting
  486. # `point_in_path` handle the transform avoids allocating an extra
  487. # buffer.
  488. if transform and not transform.is_affine:
  489. self = transform.transform_path(self)
  490. transform = None
  491. return _path.point_in_path(point[0], point[1], radius, self, transform)
  492. def contains_points(self, points, transform=None, radius=0.0):
  493. """
  494. Return whether the area enclosed by the path contains the given points.
  495. The path is always treated as closed; i.e. if the last code is not
  496. `CLOSEPOLY` an implicit segment connecting the last vertex to the first
  497. vertex is assumed.
  498. Parameters
  499. ----------
  500. points : (N, 2) array
  501. The points to check. Columns contain x and y values.
  502. transform : `~matplotlib.transforms.Transform`, optional
  503. If not ``None``, *points* will be compared to ``self`` transformed
  504. by *transform*; i.e. for a correct check, *transform* should
  505. transform the path into the coordinate system of *points*.
  506. radius : float, default: 0
  507. Additional margin on the path in coordinates of *points*.
  508. The path is extended tangentially by *radius/2*; i.e. if you would
  509. draw the path with a linewidth of *radius*, all points on the line
  510. would still be considered to be contained in the area. Conversely,
  511. negative values shrink the area: Points on the imaginary line
  512. will be considered outside the area.
  513. Returns
  514. -------
  515. length-N bool array
  516. Notes
  517. -----
  518. The current algorithm has some limitations:
  519. - The result is undefined for points exactly at the boundary
  520. (i.e. at the path shifted by *radius/2*).
  521. - The result is undefined if there is no enclosed area, i.e. all
  522. vertices are on a straight line.
  523. - If bounding lines start to cross each other due to *radius* shift,
  524. the result is not guaranteed to be correct.
  525. """
  526. if transform is not None:
  527. transform = transform.frozen()
  528. result = _path.points_in_path(points, radius, self, transform)
  529. return result.astype('bool')
  530. def contains_path(self, path, transform=None):
  531. """
  532. Return whether this (closed) path completely contains the given path.
  533. If *transform* is not ``None``, the path will be transformed before
  534. checking for containment.
  535. """
  536. if transform is not None:
  537. transform = transform.frozen()
  538. return _path.path_in_path(self, None, path, transform)
  539. def get_extents(self, transform=None, **kwargs):
  540. """
  541. Get Bbox of the path.
  542. Parameters
  543. ----------
  544. transform : `~matplotlib.transforms.Transform`, optional
  545. Transform to apply to path before computing extents, if any.
  546. **kwargs
  547. Forwarded to `.iter_bezier`.
  548. Returns
  549. -------
  550. matplotlib.transforms.Bbox
  551. The extents of the path Bbox([[xmin, ymin], [xmax, ymax]])
  552. """
  553. from .transforms import Bbox
  554. if transform is not None:
  555. self = transform.transform_path(self)
  556. if self.codes is None:
  557. xys = self.vertices
  558. elif len(np.intersect1d(self.codes, [Path.CURVE3, Path.CURVE4])) == 0:
  559. # Optimization for the straight line case.
  560. # Instead of iterating through each curve, consider
  561. # each line segment's end-points
  562. # (recall that STOP and CLOSEPOLY vertices are ignored)
  563. xys = self.vertices[np.isin(self.codes,
  564. [Path.MOVETO, Path.LINETO])]
  565. else:
  566. xys = []
  567. for curve, code in self.iter_bezier(**kwargs):
  568. # places where the derivative is zero can be extrema
  569. _, dzeros = curve.axis_aligned_extrema()
  570. # as can the ends of the curve
  571. xys.append(curve([0, *dzeros, 1]))
  572. xys = np.concatenate(xys)
  573. if len(xys):
  574. return Bbox([xys.min(axis=0), xys.max(axis=0)])
  575. else:
  576. return Bbox.null()
  577. def intersects_path(self, other, filled=True):
  578. """
  579. Return whether if this path intersects another given path.
  580. If *filled* is True, then this also returns True if one path completely
  581. encloses the other (i.e., the paths are treated as filled).
  582. """
  583. return _path.path_intersects_path(self, other, filled)
  584. def intersects_bbox(self, bbox, filled=True):
  585. """
  586. Return whether this path intersects a given `~.transforms.Bbox`.
  587. If *filled* is True, then this also returns True if the path completely
  588. encloses the `.Bbox` (i.e., the path is treated as filled).
  589. The bounding box is always considered filled.
  590. """
  591. return _path.path_intersects_rectangle(
  592. self, bbox.x0, bbox.y0, bbox.x1, bbox.y1, filled)
  593. def interpolated(self, steps):
  594. """
  595. Return a new path with each segment divided into *steps* parts.
  596. Codes other than `LINETO`, `MOVETO`, and `CLOSEPOLY` are not handled correctly.
  597. Parameters
  598. ----------
  599. steps : int
  600. The number of segments in the new path for each in the original.
  601. Returns
  602. -------
  603. Path
  604. The interpolated path.
  605. """
  606. if steps == 1 or len(self) == 0:
  607. return self
  608. if self.codes is not None and self.MOVETO in self.codes[1:]:
  609. return self.make_compound_path(
  610. *(p.interpolated(steps) for p in self._iter_connected_components()))
  611. if self.codes is not None and self.CLOSEPOLY in self.codes and not np.all(
  612. self.vertices[self.codes == self.CLOSEPOLY] == self.vertices[0]):
  613. vertices = self.vertices.copy()
  614. vertices[self.codes == self.CLOSEPOLY] = vertices[0]
  615. else:
  616. vertices = self.vertices
  617. vertices = simple_linear_interpolation(vertices, steps)
  618. codes = self.codes
  619. if codes is not None:
  620. new_codes = np.full((len(codes) - 1) * steps + 1, Path.LINETO,
  621. dtype=self.code_type)
  622. new_codes[0::steps] = codes
  623. else:
  624. new_codes = None
  625. return Path(vertices, new_codes)
  626. def to_polygons(self, transform=None, width=0, height=0, closed_only=True):
  627. """
  628. Convert this path to a list of polygons or polylines. Each
  629. polygon/polyline is an (N, 2) array of vertices. In other words,
  630. each polygon has no `MOVETO` instructions or curves. This
  631. is useful for displaying in backends that do not support
  632. compound paths or Bézier curves.
  633. If *width* and *height* are both non-zero then the lines will
  634. be simplified so that vertices outside of (0, 0), (width,
  635. height) will be clipped.
  636. The resulting polygons will be simplified if the
  637. :attr:`Path.should_simplify` attribute of the path is `True`.
  638. If *closed_only* is `True` (default), only closed polygons,
  639. with the last point being the same as the first point, will be
  640. returned. Any unclosed polylines in the path will be
  641. explicitly closed. If *closed_only* is `False`, any unclosed
  642. polygons in the path will be returned as unclosed polygons,
  643. and the closed polygons will be returned explicitly closed by
  644. setting the last point to the same as the first point.
  645. """
  646. if len(self.vertices) == 0:
  647. return []
  648. if transform is not None:
  649. transform = transform.frozen()
  650. if self.codes is None and (width == 0 or height == 0):
  651. vertices = self.vertices
  652. if closed_only:
  653. if len(vertices) < 3:
  654. return []
  655. elif np.any(vertices[0] != vertices[-1]):
  656. vertices = [*vertices, vertices[0]]
  657. if transform is None:
  658. return [vertices]
  659. else:
  660. return [transform.transform(vertices)]
  661. # Deal with the case where there are curves and/or multiple
  662. # subpaths (using extension code)
  663. return _path.convert_path_to_polygons(
  664. self, transform, width, height, closed_only)
  665. _unit_rectangle = None
  666. @classmethod
  667. def unit_rectangle(cls):
  668. """
  669. Return a `Path` instance of the unit rectangle from (0, 0) to (1, 1).
  670. """
  671. if cls._unit_rectangle is None:
  672. cls._unit_rectangle = cls([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]],
  673. closed=True, readonly=True)
  674. return cls._unit_rectangle
  675. _unit_regular_polygons = WeakValueDictionary()
  676. @classmethod
  677. def unit_regular_polygon(cls, numVertices):
  678. """
  679. Return a :class:`Path` instance for a unit regular polygon with the
  680. given *numVertices* such that the circumscribing circle has radius 1.0,
  681. centered at (0, 0).
  682. """
  683. if numVertices <= 16:
  684. path = cls._unit_regular_polygons.get(numVertices)
  685. else:
  686. path = None
  687. if path is None:
  688. theta = ((2 * np.pi / numVertices) * np.arange(numVertices + 1)
  689. # This initial rotation is to make sure the polygon always
  690. # "points-up".
  691. + np.pi / 2)
  692. verts = np.column_stack((np.cos(theta), np.sin(theta)))
  693. path = cls(verts, closed=True, readonly=True)
  694. if numVertices <= 16:
  695. cls._unit_regular_polygons[numVertices] = path
  696. return path
  697. _unit_regular_stars = WeakValueDictionary()
  698. @classmethod
  699. def unit_regular_star(cls, numVertices, innerCircle=0.5):
  700. """
  701. Return a :class:`Path` for a unit regular star with the given
  702. numVertices and radius of 1.0, centered at (0, 0).
  703. """
  704. if numVertices <= 16:
  705. path = cls._unit_regular_stars.get((numVertices, innerCircle))
  706. else:
  707. path = None
  708. if path is None:
  709. ns2 = numVertices * 2
  710. theta = (2*np.pi/ns2 * np.arange(ns2 + 1))
  711. # This initial rotation is to make sure the polygon always
  712. # "points-up"
  713. theta += np.pi / 2.0
  714. r = np.ones(ns2 + 1)
  715. r[1::2] = innerCircle
  716. verts = (r * np.vstack((np.cos(theta), np.sin(theta)))).T
  717. path = cls(verts, closed=True, readonly=True)
  718. if numVertices <= 16:
  719. cls._unit_regular_stars[(numVertices, innerCircle)] = path
  720. return path
  721. @classmethod
  722. def unit_regular_asterisk(cls, numVertices):
  723. """
  724. Return a :class:`Path` for a unit regular asterisk with the given
  725. numVertices and radius of 1.0, centered at (0, 0).
  726. """
  727. return cls.unit_regular_star(numVertices, 0.0)
  728. _unit_circle = None
  729. @classmethod
  730. def unit_circle(cls):
  731. """
  732. Return the readonly :class:`Path` of the unit circle.
  733. For most cases, :func:`Path.circle` will be what you want.
  734. """
  735. if cls._unit_circle is None:
  736. cls._unit_circle = cls.circle(center=(0, 0), radius=1,
  737. readonly=True)
  738. return cls._unit_circle
  739. @classmethod
  740. def circle(cls, center=(0., 0.), radius=1., readonly=False):
  741. """
  742. Return a `Path` representing a circle of a given radius and center.
  743. Parameters
  744. ----------
  745. center : (float, float), default: (0, 0)
  746. The center of the circle.
  747. radius : float, default: 1
  748. The radius of the circle.
  749. readonly : bool
  750. Whether the created path should have the "readonly" argument
  751. set when creating the Path instance.
  752. Notes
  753. -----
  754. The circle is approximated using 8 cubic Bézier curves, as described in
  755. Lancaster, Don. `Approximating a Circle or an Ellipse Using Four
  756. Bezier Cubic Splines <https://www.tinaja.com/glib/ellipse4.pdf>`_.
  757. """
  758. MAGIC = 0.2652031
  759. SQRTHALF = np.sqrt(0.5)
  760. MAGIC45 = SQRTHALF * MAGIC
  761. vertices = np.array([[0.0, -1.0],
  762. [MAGIC, -1.0],
  763. [SQRTHALF-MAGIC45, -SQRTHALF-MAGIC45],
  764. [SQRTHALF, -SQRTHALF],
  765. [SQRTHALF+MAGIC45, -SQRTHALF+MAGIC45],
  766. [1.0, -MAGIC],
  767. [1.0, 0.0],
  768. [1.0, MAGIC],
  769. [SQRTHALF+MAGIC45, SQRTHALF-MAGIC45],
  770. [SQRTHALF, SQRTHALF],
  771. [SQRTHALF-MAGIC45, SQRTHALF+MAGIC45],
  772. [MAGIC, 1.0],
  773. [0.0, 1.0],
  774. [-MAGIC, 1.0],
  775. [-SQRTHALF+MAGIC45, SQRTHALF+MAGIC45],
  776. [-SQRTHALF, SQRTHALF],
  777. [-SQRTHALF-MAGIC45, SQRTHALF-MAGIC45],
  778. [-1.0, MAGIC],
  779. [-1.0, 0.0],
  780. [-1.0, -MAGIC],
  781. [-SQRTHALF-MAGIC45, -SQRTHALF+MAGIC45],
  782. [-SQRTHALF, -SQRTHALF],
  783. [-SQRTHALF+MAGIC45, -SQRTHALF-MAGIC45],
  784. [-MAGIC, -1.0],
  785. [0.0, -1.0],
  786. [0.0, -1.0]],
  787. dtype=float)
  788. codes = [cls.CURVE4] * 26
  789. codes[0] = cls.MOVETO
  790. codes[-1] = cls.CLOSEPOLY
  791. return Path(vertices * radius + center, codes, readonly=readonly)
  792. _unit_circle_righthalf = None
  793. @classmethod
  794. def unit_circle_righthalf(cls):
  795. """
  796. Return a `Path` of the right half of a unit circle.
  797. See `Path.circle` for the reference on the approximation used.
  798. """
  799. if cls._unit_circle_righthalf is None:
  800. MAGIC = 0.2652031
  801. SQRTHALF = np.sqrt(0.5)
  802. MAGIC45 = SQRTHALF * MAGIC
  803. vertices = np.array(
  804. [[0.0, -1.0],
  805. [MAGIC, -1.0],
  806. [SQRTHALF-MAGIC45, -SQRTHALF-MAGIC45],
  807. [SQRTHALF, -SQRTHALF],
  808. [SQRTHALF+MAGIC45, -SQRTHALF+MAGIC45],
  809. [1.0, -MAGIC],
  810. [1.0, 0.0],
  811. [1.0, MAGIC],
  812. [SQRTHALF+MAGIC45, SQRTHALF-MAGIC45],
  813. [SQRTHALF, SQRTHALF],
  814. [SQRTHALF-MAGIC45, SQRTHALF+MAGIC45],
  815. [MAGIC, 1.0],
  816. [0.0, 1.0],
  817. [0.0, -1.0]],
  818. float)
  819. codes = np.full(14, cls.CURVE4, dtype=cls.code_type)
  820. codes[0] = cls.MOVETO
  821. codes[-1] = cls.CLOSEPOLY
  822. cls._unit_circle_righthalf = cls(vertices, codes, readonly=True)
  823. return cls._unit_circle_righthalf
  824. @classmethod
  825. def arc(cls, theta1, theta2, n=None, is_wedge=False):
  826. """
  827. Return a `Path` for the unit circle arc from angles *theta1* to
  828. *theta2* (in degrees).
  829. *theta2* is unwrapped to produce the shortest arc within 360 degrees.
  830. That is, if *theta2* > *theta1* + 360, the arc will be from *theta1* to
  831. *theta2* - 360 and not a full circle plus some extra overlap.
  832. If *n* is provided, it is the number of spline segments to make.
  833. If *n* is not provided, the number of spline segments is
  834. determined based on the delta between *theta1* and *theta2*.
  835. Masionobe, L. 2003. `Drawing an elliptical arc using
  836. polylines, quadratic or cubic Bezier curves
  837. <https://web.archive.org/web/20190318044212/http://www.spaceroots.org/documents/ellipse/index.html>`_.
  838. """
  839. halfpi = np.pi * 0.5
  840. eta1 = theta1
  841. eta2 = theta2 - 360 * np.floor((theta2 - theta1) / 360)
  842. # Ensure 2pi range is not flattened to 0 due to floating-point errors,
  843. # but don't try to expand existing 0 range.
  844. if theta2 != theta1 and eta2 <= eta1:
  845. eta2 += 360
  846. eta1, eta2 = np.deg2rad([eta1, eta2])
  847. # number of curve segments to make
  848. if n is None:
  849. n = int(2 ** np.ceil((eta2 - eta1) / halfpi))
  850. if n < 1:
  851. raise ValueError("n must be >= 1 or None")
  852. deta = (eta2 - eta1) / n
  853. t = np.tan(0.5 * deta)
  854. alpha = np.sin(deta) * (np.sqrt(4.0 + 3.0 * t * t) - 1) / 3.0
  855. steps = np.linspace(eta1, eta2, n + 1, True)
  856. cos_eta = np.cos(steps)
  857. sin_eta = np.sin(steps)
  858. xA = cos_eta[:-1]
  859. yA = sin_eta[:-1]
  860. xA_dot = -yA
  861. yA_dot = xA
  862. xB = cos_eta[1:]
  863. yB = sin_eta[1:]
  864. xB_dot = -yB
  865. yB_dot = xB
  866. if is_wedge:
  867. length = n * 3 + 4
  868. vertices = np.zeros((length, 2), float)
  869. codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
  870. vertices[1] = [xA[0], yA[0]]
  871. codes[0:2] = [cls.MOVETO, cls.LINETO]
  872. codes[-2:] = [cls.LINETO, cls.CLOSEPOLY]
  873. vertex_offset = 2
  874. end = length - 2
  875. else:
  876. length = n * 3 + 1
  877. vertices = np.empty((length, 2), float)
  878. codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
  879. vertices[0] = [xA[0], yA[0]]
  880. codes[0] = cls.MOVETO
  881. vertex_offset = 1
  882. end = length
  883. vertices[vertex_offset:end:3, 0] = xA + alpha * xA_dot
  884. vertices[vertex_offset:end:3, 1] = yA + alpha * yA_dot
  885. vertices[vertex_offset+1:end:3, 0] = xB - alpha * xB_dot
  886. vertices[vertex_offset+1:end:3, 1] = yB - alpha * yB_dot
  887. vertices[vertex_offset+2:end:3, 0] = xB
  888. vertices[vertex_offset+2:end:3, 1] = yB
  889. return cls(vertices, codes, readonly=True)
  890. @classmethod
  891. def wedge(cls, theta1, theta2, n=None):
  892. """
  893. Return a `Path` for the unit circle wedge from angles *theta1* to
  894. *theta2* (in degrees).
  895. *theta2* is unwrapped to produce the shortest wedge within 360 degrees.
  896. That is, if *theta2* > *theta1* + 360, the wedge will be from *theta1*
  897. to *theta2* - 360 and not a full circle plus some extra overlap.
  898. If *n* is provided, it is the number of spline segments to make.
  899. If *n* is not provided, the number of spline segments is
  900. determined based on the delta between *theta1* and *theta2*.
  901. See `Path.arc` for the reference on the approximation used.
  902. """
  903. return cls.arc(theta1, theta2, n, True)
  904. @staticmethod
  905. @lru_cache(8)
  906. def hatch(hatchpattern, density=6):
  907. """
  908. Given a hatch specifier, *hatchpattern*, generates a `Path` that
  909. can be used in a repeated hatching pattern. *density* is the
  910. number of lines per unit square.
  911. """
  912. from matplotlib.hatch import get_path
  913. return (get_path(hatchpattern, density)
  914. if hatchpattern is not None else None)
  915. def clip_to_bbox(self, bbox, inside=True):
  916. """
  917. Clip the path to the given bounding box.
  918. The path must be made up of one or more closed polygons. This
  919. algorithm will not behave correctly for unclosed paths.
  920. If *inside* is `True`, clip to the inside of the box, otherwise
  921. to the outside of the box.
  922. """
  923. verts = _path.clip_path_to_rect(self, bbox, inside)
  924. paths = [Path(poly) for poly in verts]
  925. return self.make_compound_path(*paths)
  926. def get_path_collection_extents(
  927. master_transform, paths, transforms, offsets, offset_transform):
  928. r"""
  929. Get bounding box of a `.PathCollection`\s internal objects.
  930. That is, given a sequence of `Path`\s, `.Transform`\s objects, and offsets, as found
  931. in a `.PathCollection`, return the bounding box that encapsulates all of them.
  932. Parameters
  933. ----------
  934. master_transform : `~matplotlib.transforms.Transform`
  935. Global transformation applied to all paths.
  936. paths : list of `Path`
  937. transforms : list of `~matplotlib.transforms.Affine2DBase`
  938. If non-empty, this overrides *master_transform*.
  939. offsets : (N, 2) array-like
  940. offset_transform : `~matplotlib.transforms.Affine2DBase`
  941. Transform applied to the offsets before offsetting the path.
  942. Notes
  943. -----
  944. The way that *paths*, *transforms* and *offsets* are combined follows the same
  945. method as for collections: each is iterated over independently, so if you have 3
  946. paths (A, B, C), 2 transforms (α, β) and 1 offset (O), their combinations are as
  947. follows:
  948. - (A, α, O)
  949. - (B, β, O)
  950. - (C, α, O)
  951. """
  952. from .transforms import Bbox
  953. if len(paths) == 0:
  954. raise ValueError("No paths provided")
  955. if len(offsets) == 0:
  956. raise ValueError("No offsets provided")
  957. extents, minpos = _path.get_path_collection_extents(
  958. master_transform, paths, np.atleast_3d(transforms),
  959. offsets, offset_transform)
  960. return Bbox.from_extents(*extents, minpos=minpos)