You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1958 lines
65 KiB

4 years ago
  1. """
  2. Classes for the efficient drawing of large collections of objects that
  3. share most properties, e.g., a large number of line segments or
  4. polygons.
  5. The classes are not meant to be as flexible as their single element
  6. counterparts (e.g., you may not be able to select all line styles) but
  7. they are meant to be fast for common use cases (e.g., a large set of solid
  8. line segemnts)
  9. """
  10. import math
  11. from numbers import Number
  12. import warnings
  13. import numpy as np
  14. import matplotlib as mpl
  15. from . import (_path, artist, cbook, cm, colors as mcolors, docstring,
  16. lines as mlines, path as mpath, transforms)
  17. CIRCLE_AREA_FACTOR = 1.0 / np.sqrt(np.pi)
  18. @cbook._define_aliases({
  19. "antialiased": ["antialiaseds"],
  20. "edgecolor": ["edgecolors"],
  21. "facecolor": ["facecolors"],
  22. "linestyle": ["linestyles", "dashes"],
  23. "linewidth": ["linewidths", "lw"],
  24. })
  25. class Collection(artist.Artist, cm.ScalarMappable):
  26. """
  27. Base class for Collections. Must be subclassed to be usable.
  28. All properties in a collection must be sequences or scalars;
  29. if scalars, they will be converted to sequences. The
  30. property of the ith element of the collection is::
  31. prop[i % len(props)]
  32. Exceptions are *capstyle* and *joinstyle* properties, these can
  33. only be set globally for the whole collection.
  34. Keyword arguments and default values:
  35. * *edgecolors*: None
  36. * *facecolors*: None
  37. * *linewidths*: None
  38. * *capstyle*: None
  39. * *joinstyle*: None
  40. * *antialiaseds*: None
  41. * *offsets*: None
  42. * *transOffset*: transforms.IdentityTransform()
  43. * *offset_position*: 'screen' (default) or 'data'
  44. * *norm*: None (optional for
  45. :class:`matplotlib.cm.ScalarMappable`)
  46. * *cmap*: None (optional for
  47. :class:`matplotlib.cm.ScalarMappable`)
  48. * *hatch*: None
  49. * *zorder*: 1
  50. *offsets* and *transOffset* are used to translate the patch after
  51. rendering (default no offsets). If offset_position is 'screen'
  52. (default) the offset is applied after the master transform has
  53. been applied, that is, the offsets are in screen coordinates. If
  54. offset_position is 'data', the offset is applied before the master
  55. transform, i.e., the offsets are in data coordinates.
  56. If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds*
  57. are None, they default to their :data:`matplotlib.rcParams` patch
  58. setting, in sequence form.
  59. The use of :class:`~matplotlib.cm.ScalarMappable` is optional. If
  60. the :class:`~matplotlib.cm.ScalarMappable` matrix _A is not None
  61. (i.e., a call to set_array has been made), at draw time a call to
  62. scalar mappable will be made to set the face colors.
  63. """
  64. _offsets = np.zeros((0, 2))
  65. _transOffset = transforms.IdentityTransform()
  66. #: Either a list of 3x3 arrays or an Nx3x3 array of transforms, suitable
  67. #: for the `all_transforms` argument to
  68. #: :meth:`~matplotlib.backend_bases.RendererBase.draw_path_collection`;
  69. #: each 3x3 array is used to initialize an
  70. #: :class:`~matplotlib.transforms.Affine2D` object.
  71. #: Each kind of collection defines this based on its arguments.
  72. _transforms = np.empty((0, 3, 3))
  73. # Whether to draw an edge by default. Set on a
  74. # subclass-by-subclass basis.
  75. _edge_default = False
  76. def __init__(self,
  77. edgecolors=None,
  78. facecolors=None,
  79. linewidths=None,
  80. linestyles='solid',
  81. capstyle=None,
  82. joinstyle=None,
  83. antialiaseds=None,
  84. offsets=None,
  85. transOffset=None,
  86. norm=None, # optional for ScalarMappable
  87. cmap=None, # ditto
  88. pickradius=5.0,
  89. hatch=None,
  90. urls=None,
  91. offset_position='screen',
  92. zorder=1,
  93. **kwargs
  94. ):
  95. """
  96. Create a Collection
  97. %(Collection)s
  98. """
  99. artist.Artist.__init__(self)
  100. cm.ScalarMappable.__init__(self, norm, cmap)
  101. # list of un-scaled dash patterns
  102. # this is needed scaling the dash pattern by linewidth
  103. self._us_linestyles = [(None, None)]
  104. # list of dash patterns
  105. self._linestyles = [(None, None)]
  106. # list of unbroadcast/scaled linewidths
  107. self._us_lw = [0]
  108. self._linewidths = [0]
  109. self._is_filled = True # May be modified by set_facecolor().
  110. self._hatch_color = mcolors.to_rgba(mpl.rcParams['hatch.color'])
  111. self.set_facecolor(facecolors)
  112. self.set_edgecolor(edgecolors)
  113. self.set_linewidth(linewidths)
  114. self.set_linestyle(linestyles)
  115. self.set_antialiased(antialiaseds)
  116. self.set_pickradius(pickradius)
  117. self.set_urls(urls)
  118. self.set_hatch(hatch)
  119. self.set_offset_position(offset_position)
  120. self.set_zorder(zorder)
  121. if capstyle:
  122. self.set_capstyle(capstyle)
  123. else:
  124. self._capstyle = None
  125. if joinstyle:
  126. self.set_joinstyle(joinstyle)
  127. else:
  128. self._joinstyle = None
  129. self._offsets = np.zeros((1, 2))
  130. self._uniform_offsets = None
  131. if offsets is not None:
  132. offsets = np.asanyarray(offsets, float)
  133. # Broadcast (2,) -> (1, 2) but nothing else.
  134. if offsets.shape == (2,):
  135. offsets = offsets[None, :]
  136. if transOffset is not None:
  137. self._offsets = offsets
  138. self._transOffset = transOffset
  139. else:
  140. self._uniform_offsets = offsets
  141. self._path_effects = None
  142. self.update(kwargs)
  143. self._paths = None
  144. def get_paths(self):
  145. return self._paths
  146. def set_paths(self):
  147. raise NotImplementedError
  148. def get_transforms(self):
  149. return self._transforms
  150. def get_offset_transform(self):
  151. t = self._transOffset
  152. if (not isinstance(t, transforms.Transform)
  153. and hasattr(t, '_as_mpl_transform')):
  154. t = t._as_mpl_transform(self.axes)
  155. return t
  156. def get_datalim(self, transData):
  157. transform = self.get_transform()
  158. transOffset = self.get_offset_transform()
  159. offsets = self._offsets
  160. paths = self.get_paths()
  161. if not transform.is_affine:
  162. paths = [transform.transform_path_non_affine(p) for p in paths]
  163. transform = transform.get_affine()
  164. if not transOffset.is_affine:
  165. offsets = transOffset.transform_non_affine(offsets)
  166. transOffset = transOffset.get_affine()
  167. if isinstance(offsets, np.ma.MaskedArray):
  168. offsets = offsets.filled(np.nan)
  169. # get_path_collection_extents handles nan but not masked arrays
  170. if len(paths) and len(offsets):
  171. result = mpath.get_path_collection_extents(
  172. transform.frozen(), paths, self.get_transforms(),
  173. offsets, transOffset.frozen())
  174. result = result.inverse_transformed(transData)
  175. else:
  176. result = transforms.Bbox.null()
  177. return result
  178. def get_window_extent(self, renderer):
  179. # TODO:check to ensure that this does not fail for
  180. # cases other than scatter plot legend
  181. return self.get_datalim(transforms.IdentityTransform())
  182. def _prepare_points(self):
  183. """Point prep for drawing and hit testing"""
  184. transform = self.get_transform()
  185. transOffset = self.get_offset_transform()
  186. offsets = self._offsets
  187. paths = self.get_paths()
  188. if self.have_units():
  189. paths = []
  190. for path in self.get_paths():
  191. vertices = path.vertices
  192. xs, ys = vertices[:, 0], vertices[:, 1]
  193. xs = self.convert_xunits(xs)
  194. ys = self.convert_yunits(ys)
  195. paths.append(mpath.Path(np.column_stack([xs, ys]), path.codes))
  196. if offsets.size > 0:
  197. xs = self.convert_xunits(offsets[:, 0])
  198. ys = self.convert_yunits(offsets[:, 1])
  199. offsets = np.column_stack([xs, ys])
  200. if not transform.is_affine:
  201. paths = [transform.transform_path_non_affine(path)
  202. for path in paths]
  203. transform = transform.get_affine()
  204. if not transOffset.is_affine:
  205. offsets = transOffset.transform_non_affine(offsets)
  206. # This might have changed an ndarray into a masked array.
  207. transOffset = transOffset.get_affine()
  208. if isinstance(offsets, np.ma.MaskedArray):
  209. offsets = offsets.filled(np.nan)
  210. # Changing from a masked array to nan-filled ndarray
  211. # is probably most efficient at this point.
  212. return transform, transOffset, offsets, paths
  213. @artist.allow_rasterization
  214. def draw(self, renderer):
  215. if not self.get_visible():
  216. return
  217. renderer.open_group(self.__class__.__name__, self.get_gid())
  218. self.update_scalarmappable()
  219. transform, transOffset, offsets, paths = self._prepare_points()
  220. gc = renderer.new_gc()
  221. self._set_gc_clip(gc)
  222. gc.set_snap(self.get_snap())
  223. if self._hatch:
  224. gc.set_hatch(self._hatch)
  225. try:
  226. gc.set_hatch_color(self._hatch_color)
  227. except AttributeError:
  228. # if we end up with a GC that does not have this method
  229. warnings.warn("Your backend does not support setting the "
  230. "hatch color.")
  231. if self.get_sketch_params() is not None:
  232. gc.set_sketch_params(*self.get_sketch_params())
  233. if self.get_path_effects():
  234. from matplotlib.patheffects import PathEffectRenderer
  235. renderer = PathEffectRenderer(self.get_path_effects(), renderer)
  236. # If the collection is made up of a single shape/color/stroke,
  237. # it can be rendered once and blitted multiple times, using
  238. # `draw_markers` rather than `draw_path_collection`. This is
  239. # *much* faster for Agg, and results in smaller file sizes in
  240. # PDF/SVG/PS.
  241. trans = self.get_transforms()
  242. facecolors = self.get_facecolor()
  243. edgecolors = self.get_edgecolor()
  244. do_single_path_optimization = False
  245. if (len(paths) == 1 and len(trans) <= 1 and
  246. len(facecolors) == 1 and len(edgecolors) == 1 and
  247. len(self._linewidths) == 1 and
  248. self._linestyles == [(None, None)] and
  249. len(self._antialiaseds) == 1 and len(self._urls) == 1 and
  250. self.get_hatch() is None):
  251. if len(trans):
  252. combined_transform = (transforms.Affine2D(trans[0]) +
  253. transform)
  254. else:
  255. combined_transform = transform
  256. extents = paths[0].get_extents(combined_transform)
  257. width, height = renderer.get_canvas_width_height()
  258. if extents.width < width and extents.height < height:
  259. do_single_path_optimization = True
  260. if self._joinstyle:
  261. gc.set_joinstyle(self._joinstyle)
  262. if self._capstyle:
  263. gc.set_capstyle(self._capstyle)
  264. if do_single_path_optimization:
  265. gc.set_foreground(tuple(edgecolors[0]))
  266. gc.set_linewidth(self._linewidths[0])
  267. gc.set_dashes(*self._linestyles[0])
  268. gc.set_antialiased(self._antialiaseds[0])
  269. gc.set_url(self._urls[0])
  270. renderer.draw_markers(
  271. gc, paths[0], combined_transform.frozen(),
  272. mpath.Path(offsets), transOffset, tuple(facecolors[0]))
  273. else:
  274. renderer.draw_path_collection(
  275. gc, transform.frozen(), paths,
  276. self.get_transforms(), offsets, transOffset,
  277. self.get_facecolor(), self.get_edgecolor(),
  278. self._linewidths, self._linestyles,
  279. self._antialiaseds, self._urls,
  280. self._offset_position)
  281. gc.restore()
  282. renderer.close_group(self.__class__.__name__)
  283. self.stale = False
  284. def set_pickradius(self, pr):
  285. """Set the pick radius used for containment tests.
  286. Parameters
  287. ----------
  288. d : float
  289. Pick radius, in points.
  290. """
  291. self._pickradius = pr
  292. def get_pickradius(self):
  293. return self._pickradius
  294. def contains(self, mouseevent):
  295. """
  296. Test whether the mouse event occurred in the collection.
  297. Returns True | False, ``dict(ind=itemlist)``, where every
  298. item in itemlist contains the event.
  299. """
  300. if callable(self._contains):
  301. return self._contains(self, mouseevent)
  302. if not self.get_visible():
  303. return False, {}
  304. pickradius = (
  305. float(self._picker)
  306. if isinstance(self._picker, Number) and
  307. self._picker is not True # the bool, not just nonzero or 1
  308. else self._pickradius)
  309. transform, transOffset, offsets, paths = self._prepare_points()
  310. ind = _path.point_in_path_collection(
  311. mouseevent.x, mouseevent.y, pickradius,
  312. transform.frozen(), paths, self.get_transforms(),
  313. offsets, transOffset, pickradius <= 0,
  314. self.get_offset_position())
  315. return len(ind) > 0, dict(ind=ind)
  316. def set_urls(self, urls):
  317. """
  318. Parameters
  319. ----------
  320. urls : List[str] or None
  321. """
  322. self._urls = urls if urls is not None else [None]
  323. self.stale = True
  324. def get_urls(self):
  325. return self._urls
  326. def set_hatch(self, hatch):
  327. r"""
  328. Set the hatching pattern
  329. *hatch* can be one of::
  330. / - diagonal hatching
  331. \ - back diagonal
  332. | - vertical
  333. - - horizontal
  334. + - crossed
  335. x - crossed diagonal
  336. o - small circle
  337. O - large circle
  338. . - dots
  339. * - stars
  340. Letters can be combined, in which case all the specified
  341. hatchings are done. If same letter repeats, it increases the
  342. density of hatching of that pattern.
  343. Hatching is supported in the PostScript, PDF, SVG and Agg
  344. backends only.
  345. Unlike other properties such as linewidth and colors, hatching
  346. can only be specified for the collection as a whole, not separately
  347. for each member.
  348. Parameters
  349. ----------
  350. hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
  351. """
  352. self._hatch = hatch
  353. self.stale = True
  354. def get_hatch(self):
  355. """Return the current hatching pattern."""
  356. return self._hatch
  357. def set_offsets(self, offsets):
  358. """
  359. Set the offsets for the collection. *offsets* can be a scalar
  360. or a sequence.
  361. Parameters
  362. ----------
  363. offsets : float or sequence of floats
  364. """
  365. offsets = np.asanyarray(offsets, float)
  366. if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else.
  367. offsets = offsets[None, :]
  368. # This decision is based on how they are initialized above in __init__.
  369. if self._uniform_offsets is None:
  370. self._offsets = offsets
  371. else:
  372. self._uniform_offsets = offsets
  373. self.stale = True
  374. def get_offsets(self):
  375. """Return the offsets for the collection."""
  376. # This decision is based on how they are initialized above in __init__.
  377. if self._uniform_offsets is None:
  378. return self._offsets
  379. else:
  380. return self._uniform_offsets
  381. def set_offset_position(self, offset_position):
  382. """
  383. Set how offsets are applied. If *offset_position* is 'screen'
  384. (default) the offset is applied after the master transform has
  385. been applied, that is, the offsets are in screen coordinates.
  386. If offset_position is 'data', the offset is applied before the
  387. master transform, i.e., the offsets are in data coordinates.
  388. Parameters
  389. ----------
  390. offset_position : {'screen', 'data'}
  391. """
  392. if offset_position not in ('screen', 'data'):
  393. raise ValueError("offset_position must be 'screen' or 'data'")
  394. self._offset_position = offset_position
  395. self.stale = True
  396. def get_offset_position(self):
  397. """
  398. Returns how offsets are applied for the collection. If
  399. *offset_position* is 'screen', the offset is applied after the
  400. master transform has been applied, that is, the offsets are in
  401. screen coordinates. If offset_position is 'data', the offset
  402. is applied before the master transform, i.e., the offsets are
  403. in data coordinates.
  404. """
  405. return self._offset_position
  406. def set_linewidth(self, lw):
  407. """
  408. Set the linewidth(s) for the collection. *lw* can be a scalar
  409. or a sequence; if it is a sequence the patches will cycle
  410. through the sequence
  411. Parameters
  412. ----------
  413. lw : float or sequence of floats
  414. """
  415. if lw is None:
  416. lw = mpl.rcParams['patch.linewidth']
  417. if lw is None:
  418. lw = mpl.rcParams['lines.linewidth']
  419. # get the un-scaled/broadcast lw
  420. self._us_lw = np.atleast_1d(np.asarray(lw))
  421. # scale all of the dash patterns.
  422. self._linewidths, self._linestyles = self._bcast_lwls(
  423. self._us_lw, self._us_linestyles)
  424. self.stale = True
  425. def set_linestyle(self, ls):
  426. """
  427. Set the linestyle(s) for the collection.
  428. =========================== =================
  429. linestyle description
  430. =========================== =================
  431. ``'-'`` or ``'solid'`` solid line
  432. ``'--'`` or ``'dashed'`` dashed line
  433. ``'-.'`` or ``'dashdot'`` dash-dotted line
  434. ``':'`` or ``'dotted'`` dotted line
  435. =========================== =================
  436. Alternatively a dash tuple of the following form can be provided::
  437. (offset, onoffseq),
  438. where ``onoffseq`` is an even length tuple of on and off ink in points.
  439. Parameters
  440. ----------
  441. ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
  442. The line style.
  443. """
  444. try:
  445. if isinstance(ls, str):
  446. ls = cbook.ls_mapper.get(ls, ls)
  447. dashes = [mlines._get_dash_pattern(ls)]
  448. else:
  449. try:
  450. dashes = [mlines._get_dash_pattern(ls)]
  451. except ValueError:
  452. dashes = [mlines._get_dash_pattern(x) for x in ls]
  453. except ValueError:
  454. raise ValueError(
  455. 'Do not know how to convert {!r} to dashes'.format(ls))
  456. # get the list of raw 'unscaled' dash patterns
  457. self._us_linestyles = dashes
  458. # broadcast and scale the lw and dash patterns
  459. self._linewidths, self._linestyles = self._bcast_lwls(
  460. self._us_lw, self._us_linestyles)
  461. def set_capstyle(self, cs):
  462. """
  463. Set the capstyle for the collection. The capstyle can
  464. only be set globally for all elements in the collection
  465. Parameters
  466. ----------
  467. cs : {'butt', 'round', 'projecting'}
  468. The capstyle
  469. """
  470. if cs in ('butt', 'round', 'projecting'):
  471. self._capstyle = cs
  472. else:
  473. raise ValueError('Unrecognized cap style. Found %s' % cs)
  474. def get_capstyle(self):
  475. return self._capstyle
  476. def set_joinstyle(self, js):
  477. """
  478. Set the joinstyle for the collection. The joinstyle can only be
  479. set globally for all elements in the collection.
  480. Parameters
  481. ----------
  482. js : {'miter', 'round', 'bevel'}
  483. The joinstyle
  484. """
  485. if js in ('miter', 'round', 'bevel'):
  486. self._joinstyle = js
  487. else:
  488. raise ValueError('Unrecognized join style. Found %s' % js)
  489. def get_joinstyle(self):
  490. return self._joinstyle
  491. @staticmethod
  492. def _bcast_lwls(linewidths, dashes):
  493. '''Internal helper function to broadcast + scale ls/lw
  494. In the collection drawing code the linewidth and linestyle are
  495. cycled through as circular buffers (via v[i % len(v)]). Thus,
  496. if we are going to scale the dash pattern at set time (not
  497. draw time) we need to do the broadcasting now and expand both
  498. lists to be the same length.
  499. Parameters
  500. ----------
  501. linewidths : list
  502. line widths of collection
  503. dashes : list
  504. dash specification (offset, (dash pattern tuple))
  505. Returns
  506. -------
  507. linewidths, dashes : list
  508. Will be the same length, dashes are scaled by paired linewidth
  509. '''
  510. if mpl.rcParams['_internal.classic_mode']:
  511. return linewidths, dashes
  512. # make sure they are the same length so we can zip them
  513. if len(dashes) != len(linewidths):
  514. l_dashes = len(dashes)
  515. l_lw = len(linewidths)
  516. gcd = math.gcd(l_dashes, l_lw)
  517. dashes = list(dashes) * (l_lw // gcd)
  518. linewidths = list(linewidths) * (l_dashes // gcd)
  519. # scale the dash patters
  520. dashes = [mlines._scale_dashes(o, d, lw)
  521. for (o, d), lw in zip(dashes, linewidths)]
  522. return linewidths, dashes
  523. def set_antialiased(self, aa):
  524. """
  525. Set the antialiasing state for rendering.
  526. Parameters
  527. ----------
  528. aa : bool or sequence of bools
  529. """
  530. if aa is None:
  531. aa = mpl.rcParams['patch.antialiased']
  532. self._antialiaseds = np.atleast_1d(np.asarray(aa, bool))
  533. self.stale = True
  534. def set_color(self, c):
  535. """
  536. Set both the edgecolor and the facecolor.
  537. .. seealso::
  538. :meth:`set_facecolor`, :meth:`set_edgecolor`
  539. For setting the edge or face color individually.
  540. Parameters
  541. ----------
  542. c : matplotlib color arg or sequence of rgba tuples
  543. """
  544. self.set_facecolor(c)
  545. self.set_edgecolor(c)
  546. def _set_facecolor(self, c):
  547. if c is None:
  548. c = mpl.rcParams['patch.facecolor']
  549. self._is_filled = True
  550. try:
  551. if c.lower() == 'none':
  552. self._is_filled = False
  553. except AttributeError:
  554. pass
  555. self._facecolors = mcolors.to_rgba_array(c, self._alpha)
  556. self.stale = True
  557. def set_facecolor(self, c):
  558. """
  559. Set the facecolor(s) of the collection. *c* can be a
  560. matplotlib color spec (all patches have same color), or a
  561. sequence of specs; if it is a sequence the patches will
  562. cycle through the sequence.
  563. If *c* is 'none', the patch will not be filled.
  564. Parameters
  565. ----------
  566. c : color or sequence of colors
  567. """
  568. self._original_facecolor = c
  569. self._set_facecolor(c)
  570. def get_facecolor(self):
  571. return self._facecolors
  572. def get_edgecolor(self):
  573. if cbook._str_equal(self._edgecolors, 'face'):
  574. return self.get_facecolors()
  575. else:
  576. return self._edgecolors
  577. def _set_edgecolor(self, c):
  578. set_hatch_color = True
  579. if c is None:
  580. if (mpl.rcParams['patch.force_edgecolor'] or
  581. not self._is_filled or self._edge_default):
  582. c = mpl.rcParams['patch.edgecolor']
  583. else:
  584. c = 'none'
  585. set_hatch_color = False
  586. self._is_stroked = True
  587. try:
  588. if c.lower() == 'none':
  589. self._is_stroked = False
  590. except AttributeError:
  591. pass
  592. try:
  593. if c.lower() == 'face': # Special case: lookup in "get" method.
  594. self._edgecolors = 'face'
  595. return
  596. except AttributeError:
  597. pass
  598. self._edgecolors = mcolors.to_rgba_array(c, self._alpha)
  599. if set_hatch_color and len(self._edgecolors):
  600. self._hatch_color = tuple(self._edgecolors[0])
  601. self.stale = True
  602. def set_edgecolor(self, c):
  603. """
  604. Set the edgecolor(s) of the collection. *c* can be a
  605. matplotlib color spec (all patches have same color), or a
  606. sequence of specs; if it is a sequence the patches will
  607. cycle through the sequence.
  608. If *c* is 'face', the edge color will always be the same as
  609. the face color. If it is 'none', the patch boundary will not
  610. be drawn.
  611. Parameters
  612. ----------
  613. c : color or sequence of colors
  614. """
  615. self._original_edgecolor = c
  616. self._set_edgecolor(c)
  617. def set_alpha(self, alpha):
  618. """
  619. Set the alpha tranparencies of the collection. *alpha* must be
  620. a float or *None*.
  621. Parameters
  622. ----------
  623. alpha : float or None
  624. """
  625. if alpha is not None:
  626. try:
  627. float(alpha)
  628. except TypeError:
  629. raise TypeError('alpha must be a float or None')
  630. self.update_dict['array'] = True
  631. artist.Artist.set_alpha(self, alpha)
  632. self._set_facecolor(self._original_facecolor)
  633. self._set_edgecolor(self._original_edgecolor)
  634. def get_linewidth(self):
  635. return self._linewidths
  636. def get_linestyle(self):
  637. return self._linestyles
  638. def update_scalarmappable(self):
  639. """
  640. If the scalar mappable array is not none, update colors
  641. from scalar data
  642. """
  643. if self._A is None:
  644. return
  645. if self._A.ndim > 1:
  646. raise ValueError('Collections can only map rank 1 arrays')
  647. if not self.check_update("array"):
  648. return
  649. if self._is_filled:
  650. self._facecolors = self.to_rgba(self._A, self._alpha)
  651. elif self._is_stroked:
  652. self._edgecolors = self.to_rgba(self._A, self._alpha)
  653. self.stale = True
  654. def get_fill(self):
  655. 'return whether fill is set'
  656. return self._is_filled
  657. def update_from(self, other):
  658. 'copy properties from other to self'
  659. artist.Artist.update_from(self, other)
  660. self._antialiaseds = other._antialiaseds
  661. self._original_edgecolor = other._original_edgecolor
  662. self._edgecolors = other._edgecolors
  663. self._original_facecolor = other._original_facecolor
  664. self._facecolors = other._facecolors
  665. self._linewidths = other._linewidths
  666. self._linestyles = other._linestyles
  667. self._us_linestyles = other._us_linestyles
  668. self._pickradius = other._pickradius
  669. self._hatch = other._hatch
  670. # update_from for scalarmappable
  671. self._A = other._A
  672. self.norm = other.norm
  673. self.cmap = other.cmap
  674. # self.update_dict = other.update_dict # do we need to copy this? -JJL
  675. self.stale = True
  676. # these are not available for the object inspector until after the
  677. # class is built so we define an initial set here for the init
  678. # function and they will be overridden after object defn
  679. docstring.interpd.update(Collection="""\
  680. Valid Collection keyword arguments:
  681. * *edgecolors*: None
  682. * *facecolors*: None
  683. * *linewidths*: None
  684. * *antialiaseds*: None
  685. * *offsets*: None
  686. * *transOffset*: transforms.IdentityTransform()
  687. * *norm*: None (optional for
  688. :class:`matplotlib.cm.ScalarMappable`)
  689. * *cmap*: None (optional for
  690. :class:`matplotlib.cm.ScalarMappable`)
  691. *offsets* and *transOffset* are used to translate the patch after
  692. rendering (default no offsets)
  693. If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds*
  694. are None, they default to their :data:`matplotlib.rcParams` patch
  695. setting, in sequence form.
  696. """)
  697. class _CollectionWithSizes(Collection):
  698. """
  699. Base class for collections that have an array of sizes.
  700. """
  701. _factor = 1.0
  702. def get_sizes(self):
  703. """
  704. Returns the sizes of the elements in the collection. The
  705. value represents the 'area' of the element.
  706. Returns
  707. -------
  708. sizes : array
  709. The 'area' of each element.
  710. """
  711. return self._sizes
  712. def set_sizes(self, sizes, dpi=72.0):
  713. """
  714. Set the sizes of each member of the collection.
  715. Parameters
  716. ----------
  717. sizes : ndarray or None
  718. The size to set for each element of the collection. The
  719. value is the 'area' of the element.
  720. dpi : float
  721. The dpi of the canvas. Defaults to 72.0.
  722. """
  723. if sizes is None:
  724. self._sizes = np.array([])
  725. self._transforms = np.empty((0, 3, 3))
  726. else:
  727. self._sizes = np.asarray(sizes)
  728. self._transforms = np.zeros((len(self._sizes), 3, 3))
  729. scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor
  730. self._transforms[:, 0, 0] = scale
  731. self._transforms[:, 1, 1] = scale
  732. self._transforms[:, 2, 2] = 1.0
  733. self.stale = True
  734. @artist.allow_rasterization
  735. def draw(self, renderer):
  736. self.set_sizes(self._sizes, self.figure.dpi)
  737. Collection.draw(self, renderer)
  738. class PathCollection(_CollectionWithSizes):
  739. """
  740. This is the most basic :class:`Collection` subclass.
  741. """
  742. @docstring.dedent_interpd
  743. def __init__(self, paths, sizes=None, **kwargs):
  744. """
  745. *paths* is a sequence of :class:`matplotlib.path.Path`
  746. instances.
  747. %(Collection)s
  748. """
  749. Collection.__init__(self, **kwargs)
  750. self.set_paths(paths)
  751. self.set_sizes(sizes)
  752. self.stale = True
  753. def set_paths(self, paths):
  754. self._paths = paths
  755. self.stale = True
  756. def get_paths(self):
  757. return self._paths
  758. class PolyCollection(_CollectionWithSizes):
  759. @docstring.dedent_interpd
  760. def __init__(self, verts, sizes=None, closed=True, **kwargs):
  761. """
  762. *verts* is a sequence of ( *verts0*, *verts1*, ...) where
  763. *verts_i* is a sequence of *xy* tuples of vertices, or an
  764. equivalent :mod:`numpy` array of shape (*nv*, 2).
  765. *sizes* is *None* (default) or a sequence of floats that
  766. scale the corresponding *verts_i*. The scaling is applied
  767. before the Artist master transform; if the latter is an identity
  768. transform, then the overall scaling is such that if
  769. *verts_i* specify a unit square, then *sizes_i* is the area
  770. of that square in points^2.
  771. If len(*sizes*) < *nv*, the additional values will be
  772. taken cyclically from the array.
  773. *closed*, when *True*, will explicitly close the polygon.
  774. %(Collection)s
  775. """
  776. Collection.__init__(self, **kwargs)
  777. self.set_sizes(sizes)
  778. self.set_verts(verts, closed)
  779. self.stale = True
  780. def set_verts(self, verts, closed=True):
  781. '''This allows one to delay initialization of the vertices.'''
  782. if isinstance(verts, np.ma.MaskedArray):
  783. verts = verts.astype(float).filled(np.nan)
  784. # This is much faster than having Path do it one at a time.
  785. if closed:
  786. self._paths = []
  787. for xy in verts:
  788. if len(xy):
  789. if isinstance(xy, np.ma.MaskedArray):
  790. xy = np.ma.concatenate([xy, xy[0:1]])
  791. else:
  792. xy = np.asarray(xy)
  793. xy = np.concatenate([xy, xy[0:1]])
  794. codes = np.empty(xy.shape[0], dtype=mpath.Path.code_type)
  795. codes[:] = mpath.Path.LINETO
  796. codes[0] = mpath.Path.MOVETO
  797. codes[-1] = mpath.Path.CLOSEPOLY
  798. self._paths.append(mpath.Path(xy, codes))
  799. else:
  800. self._paths.append(mpath.Path(xy))
  801. else:
  802. self._paths = [mpath.Path(xy) for xy in verts]
  803. self.stale = True
  804. set_paths = set_verts
  805. def set_verts_and_codes(self, verts, codes):
  806. '''This allows one to initialize vertices with path codes.'''
  807. if len(verts) != len(codes):
  808. raise ValueError("'codes' must be a 1D list or array "
  809. "with the same length of 'verts'")
  810. self._paths = []
  811. for xy, cds in zip(verts, codes):
  812. if len(xy):
  813. self._paths.append(mpath.Path(xy, cds))
  814. else:
  815. self._paths.append(mpath.Path(xy))
  816. self.stale = True
  817. class BrokenBarHCollection(PolyCollection):
  818. """
  819. A collection of horizontal bars spanning *yrange* with a sequence of
  820. *xranges*.
  821. """
  822. @docstring.dedent_interpd
  823. def __init__(self, xranges, yrange, **kwargs):
  824. """
  825. *xranges*
  826. sequence of (*xmin*, *xwidth*)
  827. *yrange*
  828. *ymin*, *ywidth*
  829. %(Collection)s
  830. """
  831. ymin, ywidth = yrange
  832. ymax = ymin + ywidth
  833. verts = [[(xmin, ymin),
  834. (xmin, ymax),
  835. (xmin + xwidth, ymax),
  836. (xmin + xwidth, ymin),
  837. (xmin, ymin)] for xmin, xwidth in xranges]
  838. PolyCollection.__init__(self, verts, **kwargs)
  839. @staticmethod
  840. def span_where(x, ymin, ymax, where, **kwargs):
  841. """
  842. Create a BrokenBarHCollection to plot horizontal bars from
  843. over the regions in *x* where *where* is True. The bars range
  844. on the y-axis from *ymin* to *ymax*
  845. A :class:`BrokenBarHCollection` is returned. *kwargs* are
  846. passed on to the collection.
  847. """
  848. xranges = []
  849. for ind0, ind1 in cbook.contiguous_regions(where):
  850. xslice = x[ind0:ind1]
  851. if not len(xslice):
  852. continue
  853. xranges.append((xslice[0], xslice[-1] - xslice[0]))
  854. collection = BrokenBarHCollection(
  855. xranges, [ymin, ymax - ymin], **kwargs)
  856. return collection
  857. class RegularPolyCollection(_CollectionWithSizes):
  858. """Draw a collection of regular polygons with *numsides*."""
  859. _path_generator = mpath.Path.unit_regular_polygon
  860. _factor = CIRCLE_AREA_FACTOR
  861. @docstring.dedent_interpd
  862. def __init__(self,
  863. numsides,
  864. rotation=0,
  865. sizes=(1,),
  866. **kwargs):
  867. """
  868. *numsides*
  869. the number of sides of the polygon
  870. *rotation*
  871. the rotation of the polygon in radians
  872. *sizes*
  873. gives the area of the circle circumscribing the
  874. regular polygon in points^2
  875. %(Collection)s
  876. Example: see :doc:`/gallery/event_handling/lasso_demo` for a
  877. complete example::
  878. offsets = np.random.rand(20,2)
  879. facecolors = [cm.jet(x) for x in np.random.rand(20)]
  880. black = (0,0,0,1)
  881. collection = RegularPolyCollection(
  882. numsides=5, # a pentagon
  883. rotation=0, sizes=(50,),
  884. facecolors=facecolors,
  885. edgecolors=(black,),
  886. linewidths=(1,),
  887. offsets=offsets,
  888. transOffset=ax.transData,
  889. )
  890. """
  891. Collection.__init__(self, **kwargs)
  892. self.set_sizes(sizes)
  893. self._numsides = numsides
  894. self._paths = [self._path_generator(numsides)]
  895. self._rotation = rotation
  896. self.set_transform(transforms.IdentityTransform())
  897. def get_numsides(self):
  898. return self._numsides
  899. def get_rotation(self):
  900. return self._rotation
  901. @artist.allow_rasterization
  902. def draw(self, renderer):
  903. self.set_sizes(self._sizes, self.figure.dpi)
  904. self._transforms = [
  905. transforms.Affine2D(x).rotate(-self._rotation).get_matrix()
  906. for x in self._transforms
  907. ]
  908. Collection.draw(self, renderer)
  909. class StarPolygonCollection(RegularPolyCollection):
  910. """
  911. Draw a collection of regular stars with *numsides* points."""
  912. _path_generator = mpath.Path.unit_regular_star
  913. class AsteriskPolygonCollection(RegularPolyCollection):
  914. """
  915. Draw a collection of regular asterisks with *numsides* points."""
  916. _path_generator = mpath.Path.unit_regular_asterisk
  917. class LineCollection(Collection):
  918. """
  919. All parameters must be sequences or scalars; if scalars, they will
  920. be converted to sequences. The property of the ith line
  921. segment is::
  922. prop[i % len(props)]
  923. i.e., the properties cycle if the ``len`` of props is less than the
  924. number of segments.
  925. """
  926. _edge_default = True
  927. def __init__(self, segments, # Can be None.
  928. linewidths=None,
  929. colors=None,
  930. antialiaseds=None,
  931. linestyles='solid',
  932. offsets=None,
  933. transOffset=None,
  934. norm=None,
  935. cmap=None,
  936. pickradius=5,
  937. zorder=2,
  938. facecolors='none',
  939. **kwargs
  940. ):
  941. """
  942. Parameters
  943. ----------
  944. segments :
  945. A sequence of (*line0*, *line1*, *line2*), where::
  946. linen = (x0, y0), (x1, y1), ... (xm, ym)
  947. or the equivalent numpy array with two columns. Each line
  948. can be a different length.
  949. colors : sequence, optional
  950. A sequence of RGBA tuples (e.g., arbitrary color
  951. strings, etc, not allowed).
  952. antialiaseds : sequence, optional
  953. A sequence of ones or zeros.
  954. linestyles : string, tuple, optional
  955. Either one of [ 'solid' | 'dashed' | 'dashdot' | 'dotted' ], or
  956. a dash tuple. The dash tuple is::
  957. (offset, onoffseq)
  958. where ``onoffseq`` is an even length tuple of on and off ink
  959. in points.
  960. norm : Normalize, optional
  961. `~.colors.Normalize` instance.
  962. cmap : string or Colormap, optional
  963. Colormap name or `~.colors.Colormap` instance.
  964. pickradius : float, optional
  965. The tolerance in points for mouse clicks picking a line.
  966. Default is 5 pt.
  967. zorder : int, optional
  968. zorder of the LineCollection. Default is 2.
  969. facecolors : optional
  970. The facecolors of the LineCollection. Default is 'none'.
  971. Setting to a value other than 'none' will lead to a filled
  972. polygon being drawn between points on each line.
  973. Notes
  974. -----
  975. If *linewidths*, *colors*, or *antialiaseds* is None, they
  976. default to their rcParams setting, in sequence form.
  977. If *offsets* and *transOffset* are not None, then
  978. *offsets* are transformed by *transOffset* and applied after
  979. the segments have been transformed to display coordinates.
  980. If *offsets* is not None but *transOffset* is None, then the
  981. *offsets* are added to the segments before any transformation.
  982. In this case, a single offset can be specified as::
  983. offsets=(xo,yo)
  984. and this value will be added cumulatively to each successive
  985. segment, so as to produce a set of successively offset curves.
  986. The use of :class:`~matplotlib.cm.ScalarMappable` is optional.
  987. If the :class:`~matplotlib.cm.ScalarMappable` array
  988. :attr:`~matplotlib.cm.ScalarMappable._A` is not None (i.e., a call to
  989. :meth:`~matplotlib.cm.ScalarMappable.set_array` has been made), at
  990. draw time a call to scalar mappable will be made to set the colors.
  991. """
  992. if colors is None:
  993. colors = mpl.rcParams['lines.color']
  994. if linewidths is None:
  995. linewidths = (mpl.rcParams['lines.linewidth'],)
  996. if antialiaseds is None:
  997. antialiaseds = (mpl.rcParams['lines.antialiased'],)
  998. colors = mcolors.to_rgba_array(colors)
  999. Collection.__init__(
  1000. self,
  1001. edgecolors=colors,
  1002. facecolors=facecolors,
  1003. linewidths=linewidths,
  1004. linestyles=linestyles,
  1005. antialiaseds=antialiaseds,
  1006. offsets=offsets,
  1007. transOffset=transOffset,
  1008. norm=norm,
  1009. cmap=cmap,
  1010. pickradius=pickradius,
  1011. zorder=zorder,
  1012. **kwargs)
  1013. self.set_segments(segments)
  1014. def set_segments(self, segments):
  1015. if segments is None:
  1016. return
  1017. _segments = []
  1018. for seg in segments:
  1019. if not isinstance(seg, np.ma.MaskedArray):
  1020. seg = np.asarray(seg, float)
  1021. _segments.append(seg)
  1022. if self._uniform_offsets is not None:
  1023. _segments = self._add_offsets(_segments)
  1024. self._paths = [mpath.Path(_seg) for _seg in _segments]
  1025. self.stale = True
  1026. set_verts = set_segments # for compatibility with PolyCollection
  1027. set_paths = set_segments
  1028. def get_segments(self):
  1029. """
  1030. Returns
  1031. -------
  1032. segments : list
  1033. List of segments in the LineCollection. Each list item contains an
  1034. array of vertices.
  1035. """
  1036. segments = []
  1037. for path in self._paths:
  1038. vertices = [vertex for vertex, _ in path.iter_segments()]
  1039. vertices = np.asarray(vertices)
  1040. segments.append(vertices)
  1041. return segments
  1042. def _add_offsets(self, segs):
  1043. offsets = self._uniform_offsets
  1044. Nsegs = len(segs)
  1045. Noffs = offsets.shape[0]
  1046. if Noffs == 1:
  1047. for i in range(Nsegs):
  1048. segs[i] = segs[i] + i * offsets
  1049. else:
  1050. for i in range(Nsegs):
  1051. io = i % Noffs
  1052. segs[i] = segs[i] + offsets[io:io + 1]
  1053. return segs
  1054. def set_color(self, c):
  1055. """
  1056. Set the color(s) of the LineCollection.
  1057. Parameters
  1058. ----------
  1059. c :
  1060. Matplotlib color argument (all patches have same color), or a
  1061. sequence or rgba tuples; if it is a sequence the patches will
  1062. cycle through the sequence.
  1063. """
  1064. self.set_edgecolor(c)
  1065. self.stale = True
  1066. def get_color(self):
  1067. return self._edgecolors
  1068. get_colors = get_color # for compatibility with old versions
  1069. class EventCollection(LineCollection):
  1070. '''
  1071. A collection of discrete events.
  1072. The events are given by a 1-dimensional array, usually the position of
  1073. something along an axis, such as time or length. They do not have an
  1074. amplitude and are displayed as vertical or horizontal parallel bars.
  1075. '''
  1076. _edge_default = True
  1077. def __init__(self,
  1078. positions, # Cannot be None.
  1079. orientation=None,
  1080. lineoffset=0,
  1081. linelength=1,
  1082. linewidth=None,
  1083. color=None,
  1084. linestyle='solid',
  1085. antialiased=None,
  1086. **kwargs
  1087. ):
  1088. """
  1089. Parameters
  1090. ----------
  1091. positions : 1D array-like object
  1092. Each value is an event.
  1093. orientation : {None, 'horizontal', 'vertical'}, optional
  1094. The orientation of the **collection** (the event bars are along
  1095. the orthogonal direction). Defaults to 'horizontal' if not
  1096. specified or None.
  1097. lineoffset : scalar, optional, default: 0
  1098. The offset of the center of the markers from the origin, in the
  1099. direction orthogonal to *orientation*.
  1100. linelength : scalar, optional, default: 1
  1101. The total height of the marker (i.e. the marker stretches from
  1102. ``lineoffset - linelength/2`` to ``lineoffset + linelength/2``).
  1103. linewidth : scalar or None, optional, default: None
  1104. If it is None, defaults to its rcParams setting, in sequence form.
  1105. color : color, sequence of colors or None, optional, default: None
  1106. If it is None, defaults to its rcParams setting, in sequence form.
  1107. linestyle : str or tuple, optional, default: 'solid'
  1108. Valid strings are ['solid', 'dashed', 'dashdot', 'dotted',
  1109. '-', '--', '-.', ':']. Dash tuples should be of the form::
  1110. (offset, onoffseq),
  1111. where *onoffseq* is an even length tuple of on and off ink
  1112. in points.
  1113. antialiased : {None, 1, 2}, optional
  1114. If it is None, defaults to its rcParams setting, in sequence form.
  1115. **kwargs : optional
  1116. Other keyword arguments are line collection properties. See
  1117. :class:`~matplotlib.collections.LineCollection` for a list of
  1118. the valid properties.
  1119. Examples
  1120. --------
  1121. .. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py
  1122. """
  1123. segment = (lineoffset + linelength / 2.,
  1124. lineoffset - linelength / 2.)
  1125. if positions is None or len(positions) == 0:
  1126. segments = []
  1127. elif hasattr(positions, 'ndim') and positions.ndim > 1:
  1128. raise ValueError('positions cannot be an array with more than '
  1129. 'one dimension.')
  1130. elif (orientation is None or orientation.lower() == 'none' or
  1131. orientation.lower() == 'horizontal'):
  1132. positions.sort()
  1133. segments = [[(coord1, coord2) for coord2 in segment] for
  1134. coord1 in positions]
  1135. self._is_horizontal = True
  1136. elif orientation.lower() == 'vertical':
  1137. positions.sort()
  1138. segments = [[(coord2, coord1) for coord2 in segment] for
  1139. coord1 in positions]
  1140. self._is_horizontal = False
  1141. else:
  1142. raise ValueError("orientation must be 'horizontal' or 'vertical'")
  1143. LineCollection.__init__(self,
  1144. segments,
  1145. linewidths=linewidth,
  1146. colors=color,
  1147. antialiaseds=antialiased,
  1148. linestyles=linestyle,
  1149. **kwargs)
  1150. self._linelength = linelength
  1151. self._lineoffset = lineoffset
  1152. def get_positions(self):
  1153. '''
  1154. return an array containing the floating-point values of the positions
  1155. '''
  1156. segments = self.get_segments()
  1157. pos = 0 if self.is_horizontal() else 1
  1158. positions = []
  1159. for segment in segments:
  1160. positions.append(segment[0, pos])
  1161. return positions
  1162. def set_positions(self, positions):
  1163. '''
  1164. set the positions of the events to the specified value
  1165. '''
  1166. if positions is None or (hasattr(positions, 'len') and
  1167. len(positions) == 0):
  1168. self.set_segments([])
  1169. return
  1170. lineoffset = self.get_lineoffset()
  1171. linelength = self.get_linelength()
  1172. segment = (lineoffset + linelength / 2.,
  1173. lineoffset - linelength / 2.)
  1174. positions = np.asanyarray(positions)
  1175. positions.sort()
  1176. if self.is_horizontal():
  1177. segments = [[(coord1, coord2) for coord2 in segment] for
  1178. coord1 in positions]
  1179. else:
  1180. segments = [[(coord2, coord1) for coord2 in segment] for
  1181. coord1 in positions]
  1182. self.set_segments(segments)
  1183. def add_positions(self, position):
  1184. '''
  1185. add one or more events at the specified positions
  1186. '''
  1187. if position is None or (hasattr(position, 'len') and
  1188. len(position) == 0):
  1189. return
  1190. positions = self.get_positions()
  1191. positions = np.hstack([positions, np.asanyarray(position)])
  1192. self.set_positions(positions)
  1193. extend_positions = append_positions = add_positions
  1194. def is_horizontal(self):
  1195. '''
  1196. True if the eventcollection is horizontal, False if vertical
  1197. '''
  1198. return self._is_horizontal
  1199. def get_orientation(self):
  1200. '''
  1201. get the orientation of the event line, may be:
  1202. [ 'horizontal' | 'vertical' ]
  1203. '''
  1204. return 'horizontal' if self.is_horizontal() else 'vertical'
  1205. def switch_orientation(self):
  1206. '''
  1207. switch the orientation of the event line, either from vertical to
  1208. horizontal or vice versus
  1209. '''
  1210. segments = self.get_segments()
  1211. for i, segment in enumerate(segments):
  1212. segments[i] = np.fliplr(segment)
  1213. self.set_segments(segments)
  1214. self._is_horizontal = not self.is_horizontal()
  1215. self.stale = True
  1216. def set_orientation(self, orientation=None):
  1217. '''
  1218. set the orientation of the event line
  1219. [ 'horizontal' | 'vertical' | None ]
  1220. defaults to 'horizontal' if not specified or None
  1221. '''
  1222. if (orientation is None or orientation.lower() == 'none' or
  1223. orientation.lower() == 'horizontal'):
  1224. is_horizontal = True
  1225. elif orientation.lower() == 'vertical':
  1226. is_horizontal = False
  1227. else:
  1228. raise ValueError("orientation must be 'horizontal' or 'vertical'")
  1229. if is_horizontal == self.is_horizontal():
  1230. return
  1231. self.switch_orientation()
  1232. def get_linelength(self):
  1233. '''
  1234. get the length of the lines used to mark each event
  1235. '''
  1236. return self._linelength
  1237. def set_linelength(self, linelength):
  1238. '''
  1239. set the length of the lines used to mark each event
  1240. '''
  1241. if linelength == self.get_linelength():
  1242. return
  1243. lineoffset = self.get_lineoffset()
  1244. segments = self.get_segments()
  1245. pos = 1 if self.is_horizontal() else 0
  1246. for segment in segments:
  1247. segment[0, pos] = lineoffset + linelength / 2.
  1248. segment[1, pos] = lineoffset - linelength / 2.
  1249. self.set_segments(segments)
  1250. self._linelength = linelength
  1251. def get_lineoffset(self):
  1252. '''
  1253. get the offset of the lines used to mark each event
  1254. '''
  1255. return self._lineoffset
  1256. def set_lineoffset(self, lineoffset):
  1257. '''
  1258. set the offset of the lines used to mark each event
  1259. '''
  1260. if lineoffset == self.get_lineoffset():
  1261. return
  1262. linelength = self.get_linelength()
  1263. segments = self.get_segments()
  1264. pos = 1 if self.is_horizontal() else 0
  1265. for segment in segments:
  1266. segment[0, pos] = lineoffset + linelength / 2.
  1267. segment[1, pos] = lineoffset - linelength / 2.
  1268. self.set_segments(segments)
  1269. self._lineoffset = lineoffset
  1270. def get_linewidth(self):
  1271. """Get the width of the lines used to mark each event."""
  1272. return super(EventCollection, self).get_linewidth()[0]
  1273. def get_linewidths(self):
  1274. return super(EventCollection, self).get_linewidth()
  1275. def get_color(self):
  1276. '''
  1277. get the color of the lines used to mark each event
  1278. '''
  1279. return self.get_colors()[0]
  1280. class CircleCollection(_CollectionWithSizes):
  1281. """
  1282. A collection of circles, drawn using splines.
  1283. """
  1284. _factor = CIRCLE_AREA_FACTOR
  1285. @docstring.dedent_interpd
  1286. def __init__(self, sizes, **kwargs):
  1287. """
  1288. *sizes*
  1289. Gives the area of the circle in points^2
  1290. %(Collection)s
  1291. """
  1292. Collection.__init__(self, **kwargs)
  1293. self.set_sizes(sizes)
  1294. self.set_transform(transforms.IdentityTransform())
  1295. self._paths = [mpath.Path.unit_circle()]
  1296. class EllipseCollection(Collection):
  1297. """
  1298. A collection of ellipses, drawn using splines.
  1299. """
  1300. @docstring.dedent_interpd
  1301. def __init__(self, widths, heights, angles, units='points', **kwargs):
  1302. """
  1303. Parameters
  1304. ----------
  1305. widths : array-like
  1306. The lengths of the first axes (e.g., major axis lengths).
  1307. heights : array-like
  1308. The lengths of second axes.
  1309. angles : array-like
  1310. The angles of the first axes, degrees CCW from the x-axis.
  1311. units : {'points', 'inches', 'dots', 'width', 'height', 'x', 'y', 'xy'}
  1312. The units in which majors and minors are given; 'width' and
  1313. 'height' refer to the dimensions of the axes, while 'x'
  1314. and 'y' refer to the *offsets* data units. 'xy' differs
  1315. from all others in that the angle as plotted varies with
  1316. the aspect ratio, and equals the specified angle only when
  1317. the aspect ratio is unity. Hence it behaves the same as
  1318. the :class:`~matplotlib.patches.Ellipse` with
  1319. ``axes.transData`` as its transform.
  1320. Other Parameters
  1321. ----------------
  1322. **kwargs
  1323. Additional kwargs inherited from the base :class:`Collection`.
  1324. %(Collection)s
  1325. """
  1326. Collection.__init__(self, **kwargs)
  1327. self._widths = 0.5 * np.asarray(widths).ravel()
  1328. self._heights = 0.5 * np.asarray(heights).ravel()
  1329. self._angles = np.deg2rad(angles).ravel()
  1330. self._units = units
  1331. self.set_transform(transforms.IdentityTransform())
  1332. self._transforms = np.empty((0, 3, 3))
  1333. self._paths = [mpath.Path.unit_circle()]
  1334. def _set_transforms(self):
  1335. """
  1336. Calculate transforms immediately before drawing.
  1337. """
  1338. ax = self.axes
  1339. fig = self.figure
  1340. if self._units == 'xy':
  1341. sc = 1
  1342. elif self._units == 'x':
  1343. sc = ax.bbox.width / ax.viewLim.width
  1344. elif self._units == 'y':
  1345. sc = ax.bbox.height / ax.viewLim.height
  1346. elif self._units == 'inches':
  1347. sc = fig.dpi
  1348. elif self._units == 'points':
  1349. sc = fig.dpi / 72.0
  1350. elif self._units == 'width':
  1351. sc = ax.bbox.width
  1352. elif self._units == 'height':
  1353. sc = ax.bbox.height
  1354. elif self._units == 'dots':
  1355. sc = 1.0
  1356. else:
  1357. raise ValueError('unrecognized units: %s' % self._units)
  1358. self._transforms = np.zeros((len(self._widths), 3, 3))
  1359. widths = self._widths * sc
  1360. heights = self._heights * sc
  1361. sin_angle = np.sin(self._angles)
  1362. cos_angle = np.cos(self._angles)
  1363. self._transforms[:, 0, 0] = widths * cos_angle
  1364. self._transforms[:, 0, 1] = heights * -sin_angle
  1365. self._transforms[:, 1, 0] = widths * sin_angle
  1366. self._transforms[:, 1, 1] = heights * cos_angle
  1367. self._transforms[:, 2, 2] = 1.0
  1368. _affine = transforms.Affine2D
  1369. if self._units == 'xy':
  1370. m = ax.transData.get_affine().get_matrix().copy()
  1371. m[:2, 2:] = 0
  1372. self.set_transform(_affine(m))
  1373. @artist.allow_rasterization
  1374. def draw(self, renderer):
  1375. self._set_transforms()
  1376. Collection.draw(self, renderer)
  1377. class PatchCollection(Collection):
  1378. """
  1379. A generic collection of patches.
  1380. This makes it easier to assign a color map to a heterogeneous
  1381. collection of patches.
  1382. This also may improve plotting speed, since PatchCollection will
  1383. draw faster than a large number of patches.
  1384. """
  1385. def __init__(self, patches, match_original=False, **kwargs):
  1386. """
  1387. *patches*
  1388. a sequence of Patch objects. This list may include
  1389. a heterogeneous assortment of different patch types.
  1390. *match_original*
  1391. If True, use the colors and linewidths of the original
  1392. patches. If False, new colors may be assigned by
  1393. providing the standard collection arguments, facecolor,
  1394. edgecolor, linewidths, norm or cmap.
  1395. If any of *edgecolors*, *facecolors*, *linewidths*,
  1396. *antialiaseds* are None, they default to their
  1397. :data:`matplotlib.rcParams` patch setting, in sequence form.
  1398. The use of :class:`~matplotlib.cm.ScalarMappable` is optional.
  1399. If the :class:`~matplotlib.cm.ScalarMappable` matrix _A is not
  1400. None (i.e., a call to set_array has been made), at draw time a
  1401. call to scalar mappable will be made to set the face colors.
  1402. """
  1403. if match_original:
  1404. def determine_facecolor(patch):
  1405. if patch.get_fill():
  1406. return patch.get_facecolor()
  1407. return [0, 0, 0, 0]
  1408. kwargs['facecolors'] = [determine_facecolor(p) for p in patches]
  1409. kwargs['edgecolors'] = [p.get_edgecolor() for p in patches]
  1410. kwargs['linewidths'] = [p.get_linewidth() for p in patches]
  1411. kwargs['linestyles'] = [p.get_linestyle() for p in patches]
  1412. kwargs['antialiaseds'] = [p.get_antialiased() for p in patches]
  1413. Collection.__init__(self, **kwargs)
  1414. self.set_paths(patches)
  1415. def set_paths(self, patches):
  1416. paths = [p.get_transform().transform_path(p.get_path())
  1417. for p in patches]
  1418. self._paths = paths
  1419. class TriMesh(Collection):
  1420. """
  1421. Class for the efficient drawing of a triangular mesh using
  1422. Gouraud shading.
  1423. A triangular mesh is a :class:`~matplotlib.tri.Triangulation`
  1424. object.
  1425. """
  1426. def __init__(self, triangulation, **kwargs):
  1427. Collection.__init__(self, **kwargs)
  1428. self._triangulation = triangulation
  1429. self._shading = 'gouraud'
  1430. self._is_filled = True
  1431. self._bbox = transforms.Bbox.unit()
  1432. # Unfortunately this requires a copy, unless Triangulation
  1433. # was rewritten.
  1434. xy = np.hstack((triangulation.x.reshape(-1, 1),
  1435. triangulation.y.reshape(-1, 1)))
  1436. self._bbox.update_from_data_xy(xy)
  1437. def get_paths(self):
  1438. if self._paths is None:
  1439. self.set_paths()
  1440. return self._paths
  1441. def set_paths(self):
  1442. self._paths = self.convert_mesh_to_paths(self._triangulation)
  1443. @staticmethod
  1444. def convert_mesh_to_paths(tri):
  1445. """
  1446. Converts a given mesh into a sequence of
  1447. :class:`matplotlib.path.Path` objects for easier rendering by
  1448. backends that do not directly support meshes.
  1449. This function is primarily of use to backend implementers.
  1450. """
  1451. triangles = tri.get_masked_triangles()
  1452. verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
  1453. return [mpath.Path(x) for x in verts]
  1454. @artist.allow_rasterization
  1455. def draw(self, renderer):
  1456. if not self.get_visible():
  1457. return
  1458. renderer.open_group(self.__class__.__name__)
  1459. transform = self.get_transform()
  1460. # Get a list of triangles and the color at each vertex.
  1461. tri = self._triangulation
  1462. triangles = tri.get_masked_triangles()
  1463. verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
  1464. self.update_scalarmappable()
  1465. colors = self._facecolors[triangles]
  1466. gc = renderer.new_gc()
  1467. self._set_gc_clip(gc)
  1468. gc.set_linewidth(self.get_linewidth()[0])
  1469. renderer.draw_gouraud_triangles(gc, verts, colors, transform.frozen())
  1470. gc.restore()
  1471. renderer.close_group(self.__class__.__name__)
  1472. class QuadMesh(Collection):
  1473. """
  1474. Class for the efficient drawing of a quadrilateral mesh.
  1475. A quadrilateral mesh consists of a grid of vertices. The
  1476. dimensions of this array are (*meshWidth* + 1, *meshHeight* +
  1477. 1). Each vertex in the mesh has a different set of "mesh
  1478. coordinates" representing its position in the topology of the
  1479. mesh. For any values (*m*, *n*) such that 0 <= *m* <= *meshWidth*
  1480. and 0 <= *n* <= *meshHeight*, the vertices at mesh coordinates
  1481. (*m*, *n*), (*m*, *n* + 1), (*m* + 1, *n* + 1), and (*m* + 1, *n*)
  1482. form one of the quadrilaterals in the mesh. There are thus
  1483. (*meshWidth* * *meshHeight*) quadrilaterals in the mesh. The mesh
  1484. need not be regular and the polygons need not be convex.
  1485. A quadrilateral mesh is represented by a (2 x ((*meshWidth* + 1) *
  1486. (*meshHeight* + 1))) numpy array *coordinates*, where each row is
  1487. the *x* and *y* coordinates of one of the vertices. To define the
  1488. function that maps from a data point to its corresponding color,
  1489. use the :meth:`set_cmap` method. Each of these arrays is indexed in
  1490. row-major order by the mesh coordinates of the vertex (or the mesh
  1491. coordinates of the lower left vertex, in the case of the
  1492. colors).
  1493. For example, the first entry in *coordinates* is the
  1494. coordinates of the vertex at mesh coordinates (0, 0), then the one
  1495. at (0, 1), then at (0, 2) .. (0, meshWidth), (1, 0), (1, 1), and
  1496. so on.
  1497. *shading* may be 'flat', or 'gouraud'
  1498. """
  1499. def __init__(self, meshWidth, meshHeight, coordinates,
  1500. antialiased=True, shading='flat', **kwargs):
  1501. Collection.__init__(self, **kwargs)
  1502. self._meshWidth = meshWidth
  1503. self._meshHeight = meshHeight
  1504. # By converting to floats now, we can avoid that on every draw.
  1505. self._coordinates = np.asarray(coordinates, float).reshape(
  1506. (meshHeight + 1, meshWidth + 1, 2))
  1507. self._antialiased = antialiased
  1508. self._shading = shading
  1509. self._bbox = transforms.Bbox.unit()
  1510. self._bbox.update_from_data_xy(coordinates.reshape(
  1511. ((meshWidth + 1) * (meshHeight + 1), 2)))
  1512. def get_paths(self):
  1513. if self._paths is None:
  1514. self.set_paths()
  1515. return self._paths
  1516. def set_paths(self):
  1517. self._paths = self.convert_mesh_to_paths(
  1518. self._meshWidth, self._meshHeight, self._coordinates)
  1519. self.stale = True
  1520. def get_datalim(self, transData):
  1521. return (self.get_transform() - transData).transform_bbox(self._bbox)
  1522. @staticmethod
  1523. def convert_mesh_to_paths(meshWidth, meshHeight, coordinates):
  1524. """
  1525. Converts a given mesh into a sequence of
  1526. :class:`matplotlib.path.Path` objects for easier rendering by
  1527. backends that do not directly support quadmeshes.
  1528. This function is primarily of use to backend implementers.
  1529. """
  1530. if isinstance(coordinates, np.ma.MaskedArray):
  1531. c = coordinates.data
  1532. else:
  1533. c = coordinates
  1534. points = np.concatenate((
  1535. c[:-1, :-1],
  1536. c[:-1, 1:],
  1537. c[1:, 1:],
  1538. c[1:, :-1],
  1539. c[:-1, :-1]
  1540. ), axis=2)
  1541. points = points.reshape((meshWidth * meshHeight, 5, 2))
  1542. return [mpath.Path(x) for x in points]
  1543. def convert_mesh_to_triangles(self, meshWidth, meshHeight, coordinates):
  1544. """
  1545. Converts a given mesh into a sequence of triangles, each point
  1546. with its own color. This is useful for experiments using
  1547. `draw_qouraud_triangle`.
  1548. """
  1549. if isinstance(coordinates, np.ma.MaskedArray):
  1550. p = coordinates.data
  1551. else:
  1552. p = coordinates
  1553. p_a = p[:-1, :-1]
  1554. p_b = p[:-1, 1:]
  1555. p_c = p[1:, 1:]
  1556. p_d = p[1:, :-1]
  1557. p_center = (p_a + p_b + p_c + p_d) / 4.0
  1558. triangles = np.concatenate((
  1559. p_a, p_b, p_center,
  1560. p_b, p_c, p_center,
  1561. p_c, p_d, p_center,
  1562. p_d, p_a, p_center,
  1563. ), axis=2)
  1564. triangles = triangles.reshape((meshWidth * meshHeight * 4, 3, 2))
  1565. c = self.get_facecolor().reshape((meshHeight + 1, meshWidth + 1, 4))
  1566. c_a = c[:-1, :-1]
  1567. c_b = c[:-1, 1:]
  1568. c_c = c[1:, 1:]
  1569. c_d = c[1:, :-1]
  1570. c_center = (c_a + c_b + c_c + c_d) / 4.0
  1571. colors = np.concatenate((
  1572. c_a, c_b, c_center,
  1573. c_b, c_c, c_center,
  1574. c_c, c_d, c_center,
  1575. c_d, c_a, c_center,
  1576. ), axis=2)
  1577. colors = colors.reshape((meshWidth * meshHeight * 4, 3, 4))
  1578. return triangles, colors
  1579. @artist.allow_rasterization
  1580. def draw(self, renderer):
  1581. if not self.get_visible():
  1582. return
  1583. renderer.open_group(self.__class__.__name__, self.get_gid())
  1584. transform = self.get_transform()
  1585. transOffset = self.get_offset_transform()
  1586. offsets = self._offsets
  1587. if self.have_units():
  1588. if len(self._offsets):
  1589. xs = self.convert_xunits(self._offsets[:, 0])
  1590. ys = self.convert_yunits(self._offsets[:, 1])
  1591. offsets = np.column_stack([xs, ys])
  1592. self.update_scalarmappable()
  1593. if not transform.is_affine:
  1594. coordinates = self._coordinates.reshape((-1, 2))
  1595. coordinates = transform.transform(coordinates)
  1596. coordinates = coordinates.reshape(self._coordinates.shape)
  1597. transform = transforms.IdentityTransform()
  1598. else:
  1599. coordinates = self._coordinates
  1600. if not transOffset.is_affine:
  1601. offsets = transOffset.transform_non_affine(offsets)
  1602. transOffset = transOffset.get_affine()
  1603. gc = renderer.new_gc()
  1604. self._set_gc_clip(gc)
  1605. gc.set_linewidth(self.get_linewidth()[0])
  1606. if self._shading == 'gouraud':
  1607. triangles, colors = self.convert_mesh_to_triangles(
  1608. self._meshWidth, self._meshHeight, coordinates)
  1609. renderer.draw_gouraud_triangles(
  1610. gc, triangles, colors, transform.frozen())
  1611. else:
  1612. renderer.draw_quad_mesh(
  1613. gc, transform.frozen(), self._meshWidth, self._meshHeight,
  1614. coordinates, offsets, transOffset, self.get_facecolor(),
  1615. self._antialiased, self.get_edgecolors())
  1616. gc.restore()
  1617. renderer.close_group(self.__class__.__name__)
  1618. self.stale = False
  1619. patchstr = artist.kwdoc(Collection)
  1620. for k in ('QuadMesh', 'TriMesh', 'PolyCollection', 'BrokenBarHCollection',
  1621. 'RegularPolyCollection', 'PathCollection',
  1622. 'StarPolygonCollection', 'PatchCollection',
  1623. 'CircleCollection', 'Collection',):
  1624. docstring.interpd.update({k: patchstr})
  1625. docstring.interpd.update(LineCollection=artist.kwdoc(LineCollection))