path.py 37 KB

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