path.py 39 KB

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