collections.py 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573
  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 segments).
  9. """
  10. import itertools
  11. import functools
  12. import math
  13. from numbers import Number, Real
  14. import warnings
  15. import numpy as np
  16. import matplotlib as mpl
  17. from . import (_api, _path, artist, cbook, colorizer as mcolorizer, colors as mcolors,
  18. _docstring, hatch as mhatch, lines as mlines, path as mpath, transforms)
  19. from ._enums import JoinStyle, CapStyle
  20. # "color" is excluded; it is a compound setter, and its docstring differs
  21. # in LineCollection.
  22. @_api.define_aliases({
  23. "antialiased": ["antialiaseds", "aa"],
  24. "edgecolor": ["edgecolors", "ec"],
  25. "facecolor": ["facecolors", "fc"],
  26. "linestyle": ["linestyles", "dashes", "ls"],
  27. "linewidth": ["linewidths", "lw"],
  28. "offset_transform": ["transOffset"],
  29. })
  30. class Collection(mcolorizer.ColorizingArtist):
  31. r"""
  32. Base class for Collections. Must be subclassed to be usable.
  33. A Collection represents a sequence of `.Patch`\es that can be drawn
  34. more efficiently together than individually. For example, when a single
  35. path is being drawn repeatedly at different offsets, the renderer can
  36. typically execute a ``draw_marker()`` call much more efficiently than a
  37. series of repeated calls to ``draw_path()`` with the offsets put in
  38. one-by-one.
  39. Most properties of a collection can be configured per-element. Therefore,
  40. Collections have "plural" versions of many of the properties of a `.Patch`
  41. (e.g. `.Collection.get_paths` instead of `.Patch.get_path`). Exceptions are
  42. the *zorder*, *hatch*, *pickradius*, *capstyle* and *joinstyle* properties,
  43. which can only be set globally for the whole collection.
  44. Besides these exceptions, all properties can be specified as single values
  45. (applying to all elements) or sequences of values. The property of the
  46. ``i``\th element of the collection is::
  47. prop[i % len(prop)]
  48. Each Collection can optionally be used as its own `.ScalarMappable` by
  49. passing the *norm* and *cmap* parameters to its constructor. If the
  50. Collection's `.ScalarMappable` matrix ``_A`` has been set (via a call
  51. to `.Collection.set_array`), then at draw time this internal scalar
  52. mappable will be used to set the ``facecolors`` and ``edgecolors``,
  53. ignoring those that were manually passed in.
  54. """
  55. #: Either a list of 3x3 arrays or an Nx3x3 array (representing N
  56. #: transforms), suitable for the `all_transforms` argument to
  57. #: `~matplotlib.backend_bases.RendererBase.draw_path_collection`;
  58. #: each 3x3 array is used to initialize an
  59. #: `~matplotlib.transforms.Affine2D` object.
  60. #: Each kind of collection defines this based on its arguments.
  61. _transforms = np.empty((0, 3, 3))
  62. # Whether to draw an edge by default. Set on a
  63. # subclass-by-subclass basis.
  64. _edge_default = False
  65. @_docstring.interpd
  66. def __init__(self, *,
  67. edgecolors=None,
  68. facecolors=None,
  69. linewidths=None,
  70. linestyles='solid',
  71. capstyle=None,
  72. joinstyle=None,
  73. antialiaseds=None,
  74. offsets=None,
  75. offset_transform=None,
  76. norm=None, # optional for ScalarMappable
  77. cmap=None, # ditto
  78. colorizer=None,
  79. pickradius=5.0,
  80. hatch=None,
  81. urls=None,
  82. zorder=1,
  83. **kwargs
  84. ):
  85. """
  86. Parameters
  87. ----------
  88. edgecolors : :mpltype:`color` or list of colors, default: :rc:`patch.edgecolor`
  89. Edge color for each patch making up the collection. The special
  90. value 'face' can be passed to make the edgecolor match the
  91. facecolor.
  92. facecolors : :mpltype:`color` or list of colors, default: :rc:`patch.facecolor`
  93. Face color for each patch making up the collection.
  94. linewidths : float or list of floats, default: :rc:`patch.linewidth`
  95. Line width for each patch making up the collection.
  96. linestyles : str or tuple or list thereof, default: 'solid'
  97. Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', '-',
  98. '--', '-.', ':']. Dash tuples should be of the form::
  99. (offset, onoffseq),
  100. where *onoffseq* is an even length tuple of on and off ink lengths
  101. in points. For examples, see
  102. :doc:`/gallery/lines_bars_and_markers/linestyles`.
  103. capstyle : `.CapStyle`-like, default: 'butt'
  104. Style to use for capping lines for all paths in the collection.
  105. Allowed values are %(CapStyle)s.
  106. joinstyle : `.JoinStyle`-like, default: 'round'
  107. Style to use for joining lines for all paths in the collection.
  108. Allowed values are %(JoinStyle)s.
  109. antialiaseds : bool or list of bool, default: :rc:`patch.antialiased`
  110. Whether each patch in the collection should be drawn with
  111. antialiasing.
  112. offsets : (float, float) or list thereof, default: (0, 0)
  113. A vector by which to translate each patch after rendering (default
  114. is no translation). The translation is performed in screen (pixel)
  115. coordinates (i.e. after the Artist's transform is applied).
  116. offset_transform : `~.Transform`, default: `.IdentityTransform`
  117. A single transform which will be applied to each *offsets* vector
  118. before it is used.
  119. cmap, norm
  120. Data normalization and colormapping parameters. See
  121. `.ScalarMappable` for a detailed description.
  122. hatch : str, optional
  123. Hatching pattern to use in filled paths, if any. Valid strings are
  124. ['/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*']. See
  125. :doc:`/gallery/shapes_and_collections/hatch_style_reference` for
  126. the meaning of each hatch type.
  127. pickradius : float, default: 5.0
  128. If ``pickradius <= 0``, then `.Collection.contains` will return
  129. ``True`` whenever the test point is inside of one of the polygons
  130. formed by the control points of a Path in the Collection. On the
  131. other hand, if it is greater than 0, then we instead check if the
  132. test point is contained in a stroke of width ``2*pickradius``
  133. following any of the Paths in the Collection.
  134. urls : list of str, default: None
  135. A URL for each patch to link to once drawn. Currently only works
  136. for the SVG backend. See :doc:`/gallery/misc/hyperlinks_sgskip` for
  137. examples.
  138. zorder : float, default: 1
  139. The drawing order, shared by all Patches in the Collection. See
  140. :doc:`/gallery/misc/zorder_demo` for all defaults and examples.
  141. **kwargs
  142. Remaining keyword arguments will be used to set properties as
  143. ``Collection.set_{key}(val)`` for each key-value pair in *kwargs*.
  144. """
  145. super().__init__(self._get_colorizer(cmap, norm, colorizer))
  146. # list of un-scaled dash patterns
  147. # this is needed scaling the dash pattern by linewidth
  148. self._us_linestyles = [(0, None)]
  149. # list of dash patterns
  150. self._linestyles = [(0, None)]
  151. # list of unbroadcast/scaled linewidths
  152. self._us_lw = [0]
  153. self._linewidths = [0]
  154. self._gapcolor = None # Currently only used by LineCollection.
  155. # Flags set by _set_mappable_flags: are colors from mapping an array?
  156. self._face_is_mapped = None
  157. self._edge_is_mapped = None
  158. self._mapped_colors = None # calculated in update_scalarmappable
  159. self._hatch_color = mcolors.to_rgba(mpl.rcParams['hatch.color'])
  160. self._hatch_linewidth = mpl.rcParams['hatch.linewidth']
  161. self.set_facecolor(facecolors)
  162. self.set_edgecolor(edgecolors)
  163. self.set_linewidth(linewidths)
  164. self.set_linestyle(linestyles)
  165. self.set_antialiased(antialiaseds)
  166. self.set_pickradius(pickradius)
  167. self.set_urls(urls)
  168. self.set_hatch(hatch)
  169. self.set_zorder(zorder)
  170. if capstyle:
  171. self.set_capstyle(capstyle)
  172. else:
  173. self._capstyle = None
  174. if joinstyle:
  175. self.set_joinstyle(joinstyle)
  176. else:
  177. self._joinstyle = None
  178. if offsets is not None:
  179. offsets = np.asanyarray(offsets, float)
  180. # Broadcast (2,) -> (1, 2) but nothing else.
  181. if offsets.shape == (2,):
  182. offsets = offsets[None, :]
  183. self._offsets = offsets
  184. self._offset_transform = offset_transform
  185. self._path_effects = None
  186. self._internal_update(kwargs)
  187. self._paths = None
  188. def get_paths(self):
  189. return self._paths
  190. def set_paths(self, paths):
  191. self._paths = paths
  192. self.stale = True
  193. def get_transforms(self):
  194. return self._transforms
  195. def get_offset_transform(self):
  196. """Return the `.Transform` instance used by this artist offset."""
  197. if self._offset_transform is None:
  198. self._offset_transform = transforms.IdentityTransform()
  199. elif (not isinstance(self._offset_transform, transforms.Transform)
  200. and hasattr(self._offset_transform, '_as_mpl_transform')):
  201. self._offset_transform = \
  202. self._offset_transform._as_mpl_transform(self.axes)
  203. return self._offset_transform
  204. def set_offset_transform(self, offset_transform):
  205. """
  206. Set the artist offset transform.
  207. Parameters
  208. ----------
  209. offset_transform : `.Transform`
  210. """
  211. self._offset_transform = offset_transform
  212. def get_datalim(self, transData):
  213. # Calculate the data limits and return them as a `.Bbox`.
  214. #
  215. # This operation depends on the transforms for the data in the
  216. # collection and whether the collection has offsets:
  217. #
  218. # 1. offsets = None, transform child of transData: use the paths for
  219. # the automatic limits (i.e. for LineCollection in streamline).
  220. # 2. offsets != None: offset_transform is child of transData:
  221. #
  222. # a. transform is child of transData: use the path + offset for
  223. # limits (i.e for bar).
  224. # b. transform is not a child of transData: just use the offsets
  225. # for the limits (i.e. for scatter)
  226. #
  227. # 3. otherwise return a null Bbox.
  228. transform = self.get_transform()
  229. offset_trf = self.get_offset_transform()
  230. if not (isinstance(offset_trf, transforms.IdentityTransform)
  231. or offset_trf.contains_branch(transData)):
  232. # if the offsets are in some coords other than data,
  233. # then don't use them for autoscaling.
  234. return transforms.Bbox.null()
  235. paths = self.get_paths()
  236. if not len(paths):
  237. # No paths to transform
  238. return transforms.Bbox.null()
  239. if not transform.is_affine:
  240. paths = [transform.transform_path_non_affine(p) for p in paths]
  241. # Don't convert transform to transform.get_affine() here because
  242. # we may have transform.contains_branch(transData) but not
  243. # transforms.get_affine().contains_branch(transData). But later,
  244. # be careful to only apply the affine part that remains.
  245. offsets = self.get_offsets()
  246. if any(transform.contains_branch_seperately(transData)):
  247. # collections that are just in data units (like quiver)
  248. # can properly have the axes limits set by their shape +
  249. # offset. LineCollections that have no offsets can
  250. # also use this algorithm (like streamplot).
  251. if isinstance(offsets, np.ma.MaskedArray):
  252. offsets = offsets.filled(np.nan)
  253. # get_path_collection_extents handles nan but not masked arrays
  254. return mpath.get_path_collection_extents(
  255. transform.get_affine() - transData, paths,
  256. self.get_transforms(),
  257. offset_trf.transform_non_affine(offsets),
  258. offset_trf.get_affine().frozen())
  259. # NOTE: None is the default case where no offsets were passed in
  260. if self._offsets is not None:
  261. # this is for collections that have their paths (shapes)
  262. # in physical, axes-relative, or figure-relative units
  263. # (i.e. like scatter). We can't uniquely set limits based on
  264. # those shapes, so we just set the limits based on their
  265. # location.
  266. offsets = (offset_trf - transData).transform(offsets)
  267. # note A-B means A B^{-1}
  268. offsets = np.ma.masked_invalid(offsets)
  269. if not offsets.mask.all():
  270. bbox = transforms.Bbox.null()
  271. bbox.update_from_data_xy(offsets)
  272. return bbox
  273. return transforms.Bbox.null()
  274. def get_window_extent(self, renderer=None):
  275. # TODO: check to ensure that this does not fail for
  276. # cases other than scatter plot legend
  277. return self.get_datalim(transforms.IdentityTransform())
  278. def _prepare_points(self):
  279. # Helper for drawing and hit testing.
  280. transform = self.get_transform()
  281. offset_trf = self.get_offset_transform()
  282. offsets = self.get_offsets()
  283. paths = self.get_paths()
  284. if self.have_units():
  285. paths = []
  286. for path in self.get_paths():
  287. vertices = path.vertices
  288. xs, ys = vertices[:, 0], vertices[:, 1]
  289. xs = self.convert_xunits(xs)
  290. ys = self.convert_yunits(ys)
  291. paths.append(mpath.Path(np.column_stack([xs, ys]), path.codes))
  292. xs = self.convert_xunits(offsets[:, 0])
  293. ys = self.convert_yunits(offsets[:, 1])
  294. offsets = np.ma.column_stack([xs, ys])
  295. if not transform.is_affine:
  296. paths = [transform.transform_path_non_affine(path)
  297. for path in paths]
  298. transform = transform.get_affine()
  299. if not offset_trf.is_affine:
  300. offsets = offset_trf.transform_non_affine(offsets)
  301. # This might have changed an ndarray into a masked array.
  302. offset_trf = offset_trf.get_affine()
  303. if isinstance(offsets, np.ma.MaskedArray):
  304. offsets = offsets.filled(np.nan)
  305. # Changing from a masked array to nan-filled ndarray
  306. # is probably most efficient at this point.
  307. return transform, offset_trf, offsets, paths
  308. @artist.allow_rasterization
  309. def draw(self, renderer):
  310. if not self.get_visible():
  311. return
  312. renderer.open_group(self.__class__.__name__, self.get_gid())
  313. self.update_scalarmappable()
  314. transform, offset_trf, offsets, paths = self._prepare_points()
  315. gc = renderer.new_gc()
  316. self._set_gc_clip(gc)
  317. gc.set_snap(self.get_snap())
  318. if self._hatch:
  319. gc.set_hatch(self._hatch)
  320. gc.set_hatch_color(self._hatch_color)
  321. gc.set_hatch_linewidth(self._hatch_linewidth)
  322. if self.get_sketch_params() is not None:
  323. gc.set_sketch_params(*self.get_sketch_params())
  324. if self.get_path_effects():
  325. from matplotlib.patheffects import PathEffectRenderer
  326. renderer = PathEffectRenderer(self.get_path_effects(), renderer)
  327. # If the collection is made up of a single shape/color/stroke,
  328. # it can be rendered once and blitted multiple times, using
  329. # `draw_markers` rather than `draw_path_collection`. This is
  330. # *much* faster for Agg, and results in smaller file sizes in
  331. # PDF/SVG/PS.
  332. trans = self.get_transforms()
  333. facecolors = self.get_facecolor()
  334. edgecolors = self.get_edgecolor()
  335. do_single_path_optimization = False
  336. if (len(paths) == 1 and len(trans) <= 1 and
  337. len(facecolors) == 1 and len(edgecolors) == 1 and
  338. len(self._linewidths) == 1 and
  339. all(ls[1] is None for ls in self._linestyles) and
  340. len(self._antialiaseds) == 1 and len(self._urls) == 1 and
  341. self.get_hatch() is None):
  342. if len(trans):
  343. combined_transform = transforms.Affine2D(trans[0]) + transform
  344. else:
  345. combined_transform = transform
  346. extents = paths[0].get_extents(combined_transform)
  347. if (extents.width < self.get_figure(root=True).bbox.width
  348. and extents.height < self.get_figure(root=True).bbox.height):
  349. do_single_path_optimization = True
  350. if self._joinstyle:
  351. gc.set_joinstyle(self._joinstyle)
  352. if self._capstyle:
  353. gc.set_capstyle(self._capstyle)
  354. if do_single_path_optimization:
  355. gc.set_foreground(tuple(edgecolors[0]))
  356. gc.set_linewidth(self._linewidths[0])
  357. gc.set_dashes(*self._linestyles[0])
  358. gc.set_antialiased(self._antialiaseds[0])
  359. gc.set_url(self._urls[0])
  360. renderer.draw_markers(
  361. gc, paths[0], combined_transform.frozen(),
  362. mpath.Path(offsets), offset_trf, tuple(facecolors[0]))
  363. else:
  364. if self._gapcolor is not None:
  365. # First draw paths within the gaps.
  366. ipaths, ilinestyles = self._get_inverse_paths_linestyles()
  367. renderer.draw_path_collection(
  368. gc, transform.frozen(), ipaths,
  369. self.get_transforms(), offsets, offset_trf,
  370. [mcolors.to_rgba("none")], self._gapcolor,
  371. self._linewidths, ilinestyles,
  372. self._antialiaseds, self._urls,
  373. "screen")
  374. renderer.draw_path_collection(
  375. gc, transform.frozen(), paths,
  376. self.get_transforms(), offsets, offset_trf,
  377. self.get_facecolor(), self.get_edgecolor(),
  378. self._linewidths, self._linestyles,
  379. self._antialiaseds, self._urls,
  380. "screen") # offset_position, kept for backcompat.
  381. gc.restore()
  382. renderer.close_group(self.__class__.__name__)
  383. self.stale = False
  384. def set_pickradius(self, pickradius):
  385. """
  386. Set the pick radius used for containment tests.
  387. Parameters
  388. ----------
  389. pickradius : float
  390. Pick radius, in points.
  391. """
  392. if not isinstance(pickradius, Real):
  393. raise ValueError(
  394. f"pickradius must be a real-valued number, not {pickradius!r}")
  395. self._pickradius = pickradius
  396. def get_pickradius(self):
  397. return self._pickradius
  398. def contains(self, mouseevent):
  399. """
  400. Test whether the mouse event occurred in the collection.
  401. Returns ``bool, dict(ind=itemlist)``, where every item in itemlist
  402. contains the event.
  403. """
  404. if self._different_canvas(mouseevent) or not self.get_visible():
  405. return False, {}
  406. pickradius = (
  407. float(self._picker)
  408. if isinstance(self._picker, Number) and
  409. self._picker is not True # the bool, not just nonzero or 1
  410. else self._pickradius)
  411. if self.axes:
  412. self.axes._unstale_viewLim()
  413. transform, offset_trf, offsets, paths = self._prepare_points()
  414. # Tests if the point is contained on one of the polygons formed
  415. # by the control points of each of the paths. A point is considered
  416. # "on" a path if it would lie within a stroke of width 2*pickradius
  417. # following the path. If pickradius <= 0, then we instead simply check
  418. # if the point is *inside* of the path instead.
  419. ind = _path.point_in_path_collection(
  420. mouseevent.x, mouseevent.y, pickradius,
  421. transform.frozen(), paths, self.get_transforms(),
  422. offsets, offset_trf, pickradius <= 0)
  423. return len(ind) > 0, dict(ind=ind)
  424. def set_urls(self, urls):
  425. """
  426. Parameters
  427. ----------
  428. urls : list of str or None
  429. Notes
  430. -----
  431. URLs are currently only implemented by the SVG backend. They are
  432. ignored by all other backends.
  433. """
  434. self._urls = urls if urls is not None else [None]
  435. self.stale = True
  436. def get_urls(self):
  437. """
  438. Return a list of URLs, one for each element of the collection.
  439. The list contains *None* for elements without a URL. See
  440. :doc:`/gallery/misc/hyperlinks_sgskip` for an example.
  441. """
  442. return self._urls
  443. def set_hatch(self, hatch):
  444. r"""
  445. Set the hatching pattern
  446. *hatch* can be one of::
  447. / - diagonal hatching
  448. \ - back diagonal
  449. | - vertical
  450. - - horizontal
  451. + - crossed
  452. x - crossed diagonal
  453. o - small circle
  454. O - large circle
  455. . - dots
  456. * - stars
  457. Letters can be combined, in which case all the specified
  458. hatchings are done. If same letter repeats, it increases the
  459. density of hatching of that pattern.
  460. Unlike other properties such as linewidth and colors, hatching
  461. can only be specified for the collection as a whole, not separately
  462. for each member.
  463. Parameters
  464. ----------
  465. hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
  466. """
  467. # Use validate_hatch(list) after deprecation.
  468. mhatch._validate_hatch_pattern(hatch)
  469. self._hatch = hatch
  470. self.stale = True
  471. def get_hatch(self):
  472. """Return the current hatching pattern."""
  473. return self._hatch
  474. def set_hatch_linewidth(self, lw):
  475. """Set the hatch linewidth."""
  476. self._hatch_linewidth = lw
  477. def get_hatch_linewidth(self):
  478. """Return the hatch linewidth."""
  479. return self._hatch_linewidth
  480. def set_offsets(self, offsets):
  481. """
  482. Set the offsets for the collection.
  483. Parameters
  484. ----------
  485. offsets : (N, 2) or (2,) array-like
  486. """
  487. offsets = np.asanyarray(offsets)
  488. if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else.
  489. offsets = offsets[None, :]
  490. cstack = (np.ma.column_stack if isinstance(offsets, np.ma.MaskedArray)
  491. else np.column_stack)
  492. self._offsets = cstack(
  493. (np.asanyarray(self.convert_xunits(offsets[:, 0]), float),
  494. np.asanyarray(self.convert_yunits(offsets[:, 1]), float)))
  495. self.stale = True
  496. def get_offsets(self):
  497. """Return the offsets for the collection."""
  498. # Default to zeros in the no-offset (None) case
  499. return np.zeros((1, 2)) if self._offsets is None else self._offsets
  500. def _get_default_linewidth(self):
  501. # This may be overridden in a subclass.
  502. return mpl.rcParams['patch.linewidth'] # validated as float
  503. def set_linewidth(self, lw):
  504. """
  505. Set the linewidth(s) for the collection. *lw* can be a scalar
  506. or a sequence; if it is a sequence the patches will cycle
  507. through the sequence
  508. Parameters
  509. ----------
  510. lw : float or list of floats
  511. """
  512. if lw is None:
  513. lw = self._get_default_linewidth()
  514. # get the un-scaled/broadcast lw
  515. self._us_lw = np.atleast_1d(lw)
  516. # scale all of the dash patterns.
  517. self._linewidths, self._linestyles = self._bcast_lwls(
  518. self._us_lw, self._us_linestyles)
  519. self.stale = True
  520. def set_linestyle(self, ls):
  521. """
  522. Set the linestyle(s) for the collection.
  523. =========================== =================
  524. linestyle description
  525. =========================== =================
  526. ``'-'`` or ``'solid'`` solid line
  527. ``'--'`` or ``'dashed'`` dashed line
  528. ``'-.'`` or ``'dashdot'`` dash-dotted line
  529. ``':'`` or ``'dotted'`` dotted line
  530. =========================== =================
  531. Alternatively a dash tuple of the following form can be provided::
  532. (offset, onoffseq),
  533. where ``onoffseq`` is an even length tuple of on and off ink in points.
  534. Parameters
  535. ----------
  536. ls : str or tuple or list thereof
  537. Valid values for individual linestyles include {'-', '--', '-.',
  538. ':', '', (offset, on-off-seq)}. See `.Line2D.set_linestyle` for a
  539. complete description.
  540. """
  541. # get the list of raw 'unscaled' dash patterns
  542. self._us_linestyles = mlines._get_dash_patterns(ls)
  543. # broadcast and scale the lw and dash patterns
  544. self._linewidths, self._linestyles = self._bcast_lwls(
  545. self._us_lw, self._us_linestyles)
  546. @_docstring.interpd
  547. def set_capstyle(self, cs):
  548. """
  549. Set the `.CapStyle` for the collection (for all its elements).
  550. Parameters
  551. ----------
  552. cs : `.CapStyle` or %(CapStyle)s
  553. """
  554. self._capstyle = CapStyle(cs)
  555. @_docstring.interpd
  556. def get_capstyle(self):
  557. """
  558. Return the cap style for the collection (for all its elements).
  559. Returns
  560. -------
  561. %(CapStyle)s or None
  562. """
  563. return self._capstyle.name if self._capstyle else None
  564. @_docstring.interpd
  565. def set_joinstyle(self, js):
  566. """
  567. Set the `.JoinStyle` for the collection (for all its elements).
  568. Parameters
  569. ----------
  570. js : `.JoinStyle` or %(JoinStyle)s
  571. """
  572. self._joinstyle = JoinStyle(js)
  573. @_docstring.interpd
  574. def get_joinstyle(self):
  575. """
  576. Return the join style for the collection (for all its elements).
  577. Returns
  578. -------
  579. %(JoinStyle)s or None
  580. """
  581. return self._joinstyle.name if self._joinstyle else None
  582. @staticmethod
  583. def _bcast_lwls(linewidths, dashes):
  584. """
  585. Internal helper function to broadcast + scale ls/lw
  586. In the collection drawing code, the linewidth and linestyle are cycled
  587. through as circular buffers (via ``v[i % len(v)]``). Thus, if we are
  588. going to scale the dash pattern at set time (not draw time) we need to
  589. do the broadcasting now and expand both lists to be the same length.
  590. Parameters
  591. ----------
  592. linewidths : list
  593. line widths of collection
  594. dashes : list
  595. dash specification (offset, (dash pattern tuple))
  596. Returns
  597. -------
  598. linewidths, dashes : list
  599. Will be the same length, dashes are scaled by paired linewidth
  600. """
  601. if mpl.rcParams['_internal.classic_mode']:
  602. return linewidths, dashes
  603. # make sure they are the same length so we can zip them
  604. if len(dashes) != len(linewidths):
  605. l_dashes = len(dashes)
  606. l_lw = len(linewidths)
  607. gcd = math.gcd(l_dashes, l_lw)
  608. dashes = list(dashes) * (l_lw // gcd)
  609. linewidths = list(linewidths) * (l_dashes // gcd)
  610. # scale the dash patterns
  611. dashes = [mlines._scale_dashes(o, d, lw)
  612. for (o, d), lw in zip(dashes, linewidths)]
  613. return linewidths, dashes
  614. def get_antialiased(self):
  615. """
  616. Get the antialiasing state for rendering.
  617. Returns
  618. -------
  619. array of bools
  620. """
  621. return self._antialiaseds
  622. def set_antialiased(self, aa):
  623. """
  624. Set the antialiasing state for rendering.
  625. Parameters
  626. ----------
  627. aa : bool or list of bools
  628. """
  629. if aa is None:
  630. aa = self._get_default_antialiased()
  631. self._antialiaseds = np.atleast_1d(np.asarray(aa, bool))
  632. self.stale = True
  633. def _get_default_antialiased(self):
  634. # This may be overridden in a subclass.
  635. return mpl.rcParams['patch.antialiased']
  636. def set_color(self, c):
  637. """
  638. Set both the edgecolor and the facecolor.
  639. Parameters
  640. ----------
  641. c : :mpltype:`color` or list of RGBA tuples
  642. See Also
  643. --------
  644. Collection.set_facecolor, Collection.set_edgecolor
  645. For setting the edge or face color individually.
  646. """
  647. self.set_facecolor(c)
  648. self.set_edgecolor(c)
  649. def _get_default_facecolor(self):
  650. # This may be overridden in a subclass.
  651. return mpl.rcParams['patch.facecolor']
  652. def _set_facecolor(self, c):
  653. if c is None:
  654. c = self._get_default_facecolor()
  655. self._facecolors = mcolors.to_rgba_array(c, self._alpha)
  656. self.stale = True
  657. def set_facecolor(self, c):
  658. """
  659. Set the facecolor(s) of the collection. *c* can be a color (all patches
  660. have same color), or a sequence of colors; if it is a sequence the
  661. patches will cycle through the sequence.
  662. If *c* is 'none', the patch will not be filled.
  663. Parameters
  664. ----------
  665. c : :mpltype:`color` or list of :mpltype:`color`
  666. """
  667. if isinstance(c, str) and c.lower() in ("none", "face"):
  668. c = c.lower()
  669. self._original_facecolor = c
  670. self._set_facecolor(c)
  671. def get_facecolor(self):
  672. return self._facecolors
  673. def get_edgecolor(self):
  674. if cbook._str_equal(self._edgecolors, 'face'):
  675. return self.get_facecolor()
  676. else:
  677. return self._edgecolors
  678. def _get_default_edgecolor(self):
  679. # This may be overridden in a subclass.
  680. return mpl.rcParams['patch.edgecolor']
  681. def _set_edgecolor(self, c):
  682. set_hatch_color = True
  683. if c is None:
  684. if (mpl.rcParams['patch.force_edgecolor']
  685. or self._edge_default
  686. or cbook._str_equal(self._original_facecolor, 'none')):
  687. c = self._get_default_edgecolor()
  688. else:
  689. c = 'none'
  690. set_hatch_color = False
  691. if cbook._str_lower_equal(c, 'face'):
  692. self._edgecolors = 'face'
  693. self.stale = True
  694. return
  695. self._edgecolors = mcolors.to_rgba_array(c, self._alpha)
  696. if set_hatch_color and len(self._edgecolors):
  697. self._hatch_color = tuple(self._edgecolors[0])
  698. self.stale = True
  699. def set_edgecolor(self, c):
  700. """
  701. Set the edgecolor(s) of the collection.
  702. Parameters
  703. ----------
  704. c : :mpltype:`color` or list of :mpltype:`color` or 'face'
  705. The collection edgecolor(s). If a sequence, the patches cycle
  706. through it. If 'face', match the facecolor.
  707. """
  708. # We pass through a default value for use in LineCollection.
  709. # This allows us to maintain None as the default indicator in
  710. # _original_edgecolor.
  711. if isinstance(c, str) and c.lower() in ("none", "face"):
  712. c = c.lower()
  713. self._original_edgecolor = c
  714. self._set_edgecolor(c)
  715. def set_alpha(self, alpha):
  716. """
  717. Set the transparency of the collection.
  718. Parameters
  719. ----------
  720. alpha : float or array of float or None
  721. If not None, *alpha* values must be between 0 and 1, inclusive.
  722. If an array is provided, its length must match the number of
  723. elements in the collection. Masked values and nans are not
  724. supported.
  725. """
  726. artist.Artist._set_alpha_for_array(self, alpha)
  727. self._set_facecolor(self._original_facecolor)
  728. self._set_edgecolor(self._original_edgecolor)
  729. set_alpha.__doc__ = artist.Artist._set_alpha_for_array.__doc__
  730. def get_linewidth(self):
  731. return self._linewidths
  732. def get_linestyle(self):
  733. return self._linestyles
  734. def _set_mappable_flags(self):
  735. """
  736. Determine whether edges and/or faces are color-mapped.
  737. This is a helper for update_scalarmappable.
  738. It sets Boolean flags '_edge_is_mapped' and '_face_is_mapped'.
  739. Returns
  740. -------
  741. mapping_change : bool
  742. True if either flag is True, or if a flag has changed.
  743. """
  744. # The flags are initialized to None to ensure this returns True
  745. # the first time it is called.
  746. edge0 = self._edge_is_mapped
  747. face0 = self._face_is_mapped
  748. # After returning, the flags must be Booleans, not None.
  749. self._edge_is_mapped = False
  750. self._face_is_mapped = False
  751. if self._A is not None:
  752. if not cbook._str_equal(self._original_facecolor, 'none'):
  753. self._face_is_mapped = True
  754. if cbook._str_equal(self._original_edgecolor, 'face'):
  755. self._edge_is_mapped = True
  756. else:
  757. if self._original_edgecolor is None:
  758. self._edge_is_mapped = True
  759. mapped = self._face_is_mapped or self._edge_is_mapped
  760. changed = (edge0 is None or face0 is None
  761. or self._edge_is_mapped != edge0
  762. or self._face_is_mapped != face0)
  763. return mapped or changed
  764. def update_scalarmappable(self):
  765. """
  766. Update colors from the scalar mappable array, if any.
  767. Assign colors to edges and faces based on the array and/or
  768. colors that were directly set, as appropriate.
  769. """
  770. if not self._set_mappable_flags():
  771. return
  772. # Allow possibility to call 'self.set_array(None)'.
  773. if self._A is not None:
  774. # QuadMesh can map 2d arrays (but pcolormesh supplies 1d array)
  775. if self._A.ndim > 1 and not isinstance(self, _MeshData):
  776. raise ValueError('Collections can only map rank 1 arrays')
  777. if np.iterable(self._alpha):
  778. if self._alpha.size != self._A.size:
  779. raise ValueError(
  780. f'Data array shape, {self._A.shape} '
  781. 'is incompatible with alpha array shape, '
  782. f'{self._alpha.shape}. '
  783. 'This can occur with the deprecated '
  784. 'behavior of the "flat" shading option, '
  785. 'in which a row and/or column of the data '
  786. 'array is dropped.')
  787. # pcolormesh, scatter, maybe others flatten their _A
  788. self._alpha = self._alpha.reshape(self._A.shape)
  789. self._mapped_colors = self.to_rgba(self._A, self._alpha)
  790. if self._face_is_mapped:
  791. self._facecolors = self._mapped_colors
  792. else:
  793. self._set_facecolor(self._original_facecolor)
  794. if self._edge_is_mapped:
  795. self._edgecolors = self._mapped_colors
  796. else:
  797. self._set_edgecolor(self._original_edgecolor)
  798. self.stale = True
  799. def get_fill(self):
  800. """Return whether face is colored."""
  801. return not cbook._str_lower_equal(self._original_facecolor, "none")
  802. def update_from(self, other):
  803. """Copy properties from other to self."""
  804. artist.Artist.update_from(self, other)
  805. self._antialiaseds = other._antialiaseds
  806. self._mapped_colors = other._mapped_colors
  807. self._edge_is_mapped = other._edge_is_mapped
  808. self._original_edgecolor = other._original_edgecolor
  809. self._edgecolors = other._edgecolors
  810. self._face_is_mapped = other._face_is_mapped
  811. self._original_facecolor = other._original_facecolor
  812. self._facecolors = other._facecolors
  813. self._linewidths = other._linewidths
  814. self._linestyles = other._linestyles
  815. self._us_linestyles = other._us_linestyles
  816. self._pickradius = other._pickradius
  817. self._hatch = other._hatch
  818. # update_from for scalarmappable
  819. self._A = other._A
  820. self.norm = other.norm
  821. self.cmap = other.cmap
  822. self.stale = True
  823. class _CollectionWithSizes(Collection):
  824. """
  825. Base class for collections that have an array of sizes.
  826. """
  827. _factor = 1.0
  828. def get_sizes(self):
  829. """
  830. Return the sizes ('areas') of the elements in the collection.
  831. Returns
  832. -------
  833. array
  834. The 'area' of each element.
  835. """
  836. return self._sizes
  837. def set_sizes(self, sizes, dpi=72.0):
  838. """
  839. Set the sizes of each member of the collection.
  840. Parameters
  841. ----------
  842. sizes : `numpy.ndarray` or None
  843. The size to set for each element of the collection. The
  844. value is the 'area' of the element.
  845. dpi : float, default: 72
  846. The dpi of the canvas.
  847. """
  848. if sizes is None:
  849. self._sizes = np.array([])
  850. self._transforms = np.empty((0, 3, 3))
  851. else:
  852. self._sizes = np.asarray(sizes)
  853. self._transforms = np.zeros((len(self._sizes), 3, 3))
  854. scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor
  855. self._transforms[:, 0, 0] = scale
  856. self._transforms[:, 1, 1] = scale
  857. self._transforms[:, 2, 2] = 1.0
  858. self.stale = True
  859. @artist.allow_rasterization
  860. def draw(self, renderer):
  861. self.set_sizes(self._sizes, self.get_figure(root=True).dpi)
  862. super().draw(renderer)
  863. class PathCollection(_CollectionWithSizes):
  864. r"""
  865. A collection of `~.path.Path`\s, as created by e.g. `~.Axes.scatter`.
  866. """
  867. def __init__(self, paths, sizes=None, **kwargs):
  868. """
  869. Parameters
  870. ----------
  871. paths : list of `.path.Path`
  872. The paths that will make up the `.Collection`.
  873. sizes : array-like
  874. The factor by which to scale each drawn `~.path.Path`. One unit
  875. squared in the Path's data space is scaled to be ``sizes**2``
  876. points when rendered.
  877. **kwargs
  878. Forwarded to `.Collection`.
  879. """
  880. super().__init__(**kwargs)
  881. self.set_paths(paths)
  882. self.set_sizes(sizes)
  883. self.stale = True
  884. def get_paths(self):
  885. return self._paths
  886. def legend_elements(self, prop="colors", num="auto",
  887. fmt=None, func=lambda x: x, **kwargs):
  888. """
  889. Create legend handles and labels for a PathCollection.
  890. Each legend handle is a `.Line2D` representing the Path that was drawn,
  891. and each label is a string that represents the Path.
  892. This is useful for obtaining a legend for a `~.Axes.scatter` plot;
  893. e.g.::
  894. scatter = plt.scatter([1, 2, 3], [4, 5, 6], c=[7, 2, 3], num=None)
  895. plt.legend(*scatter.legend_elements())
  896. creates three legend elements, one for each color with the numerical
  897. values passed to *c* as the labels.
  898. Also see the :ref:`automatedlegendcreation` example.
  899. Parameters
  900. ----------
  901. prop : {"colors", "sizes"}, default: "colors"
  902. If "colors", the legend handles will show the different colors of
  903. the collection. If "sizes", the legend will show the different
  904. sizes. To set both, use *kwargs* to directly edit the `.Line2D`
  905. properties.
  906. num : int, None, "auto" (default), array-like, or `~.ticker.Locator`
  907. Target number of elements to create.
  908. If None, use all unique elements of the mappable array. If an
  909. integer, target to use *num* elements in the normed range.
  910. If *"auto"*, try to determine which option better suits the nature
  911. of the data.
  912. The number of created elements may slightly deviate from *num* due
  913. to a `~.ticker.Locator` being used to find useful locations.
  914. If a list or array, use exactly those elements for the legend.
  915. Finally, a `~.ticker.Locator` can be provided.
  916. fmt : str, `~matplotlib.ticker.Formatter`, or None (default)
  917. The format or formatter to use for the labels. If a string must be
  918. a valid input for a `.StrMethodFormatter`. If None (the default),
  919. use a `.ScalarFormatter`.
  920. func : function, default: ``lambda x: x``
  921. Function to calculate the labels. Often the size (or color)
  922. argument to `~.Axes.scatter` will have been pre-processed by the
  923. user using a function ``s = f(x)`` to make the markers visible;
  924. e.g. ``size = np.log10(x)``. Providing the inverse of this
  925. function here allows that pre-processing to be inverted, so that
  926. the legend labels have the correct values; e.g. ``func = lambda
  927. x: 10**x``.
  928. **kwargs
  929. Allowed keyword arguments are *color* and *size*. E.g. it may be
  930. useful to set the color of the markers if *prop="sizes"* is used;
  931. similarly to set the size of the markers if *prop="colors"* is
  932. used. Any further parameters are passed onto the `.Line2D`
  933. instance. This may be useful to e.g. specify a different
  934. *markeredgecolor* or *alpha* for the legend handles.
  935. Returns
  936. -------
  937. handles : list of `.Line2D`
  938. Visual representation of each element of the legend.
  939. labels : list of str
  940. The string labels for elements of the legend.
  941. """
  942. handles = []
  943. labels = []
  944. hasarray = self.get_array() is not None
  945. if fmt is None:
  946. fmt = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=True)
  947. elif isinstance(fmt, str):
  948. fmt = mpl.ticker.StrMethodFormatter(fmt)
  949. fmt.create_dummy_axis()
  950. if prop == "colors":
  951. if not hasarray:
  952. warnings.warn("Collection without array used. Make sure to "
  953. "specify the values to be colormapped via the "
  954. "`c` argument.")
  955. return handles, labels
  956. u = np.unique(self.get_array())
  957. size = kwargs.pop("size", mpl.rcParams["lines.markersize"])
  958. elif prop == "sizes":
  959. u = np.unique(self.get_sizes())
  960. color = kwargs.pop("color", "k")
  961. else:
  962. raise ValueError("Valid values for `prop` are 'colors' or "
  963. f"'sizes'. You supplied '{prop}' instead.")
  964. fu = func(u)
  965. fmt.axis.set_view_interval(fu.min(), fu.max())
  966. fmt.axis.set_data_interval(fu.min(), fu.max())
  967. if num == "auto":
  968. num = 9
  969. if len(u) <= num:
  970. num = None
  971. if num is None:
  972. values = u
  973. label_values = func(values)
  974. else:
  975. if prop == "colors":
  976. arr = self.get_array()
  977. elif prop == "sizes":
  978. arr = self.get_sizes()
  979. if isinstance(num, mpl.ticker.Locator):
  980. loc = num
  981. elif np.iterable(num):
  982. loc = mpl.ticker.FixedLocator(num)
  983. else:
  984. num = int(num)
  985. loc = mpl.ticker.MaxNLocator(nbins=num, min_n_ticks=num-1,
  986. steps=[1, 2, 2.5, 3, 5, 6, 8, 10])
  987. label_values = loc.tick_values(func(arr).min(), func(arr).max())
  988. cond = ((label_values >= func(arr).min()) &
  989. (label_values <= func(arr).max()))
  990. label_values = label_values[cond]
  991. yarr = np.linspace(arr.min(), arr.max(), 256)
  992. xarr = func(yarr)
  993. ix = np.argsort(xarr)
  994. values = np.interp(label_values, xarr[ix], yarr[ix])
  995. kw = {"markeredgewidth": self.get_linewidths()[0],
  996. "alpha": self.get_alpha(),
  997. **kwargs}
  998. for val, lab in zip(values, label_values):
  999. if prop == "colors":
  1000. color = self.cmap(self.norm(val))
  1001. elif prop == "sizes":
  1002. size = np.sqrt(val)
  1003. if np.isclose(size, 0.0):
  1004. continue
  1005. h = mlines.Line2D([0], [0], ls="", color=color, ms=size,
  1006. marker=self.get_paths()[0], **kw)
  1007. handles.append(h)
  1008. if hasattr(fmt, "set_locs"):
  1009. fmt.set_locs(label_values)
  1010. l = fmt(lab)
  1011. labels.append(l)
  1012. return handles, labels
  1013. class PolyCollection(_CollectionWithSizes):
  1014. def __init__(self, verts, sizes=None, *, closed=True, **kwargs):
  1015. """
  1016. Parameters
  1017. ----------
  1018. verts : list of array-like
  1019. The sequence of polygons [*verts0*, *verts1*, ...] where each
  1020. element *verts_i* defines the vertices of polygon *i* as a 2D
  1021. array-like of shape (M, 2).
  1022. sizes : array-like, default: None
  1023. Squared scaling factors for the polygons. The coordinates of each
  1024. polygon *verts_i* are multiplied by the square-root of the
  1025. corresponding entry in *sizes* (i.e., *sizes* specify the scaling
  1026. of areas). The scaling is applied before the Artist master
  1027. transform.
  1028. closed : bool, default: True
  1029. Whether the polygon should be closed by adding a CLOSEPOLY
  1030. connection at the end.
  1031. **kwargs
  1032. Forwarded to `.Collection`.
  1033. """
  1034. super().__init__(**kwargs)
  1035. self.set_sizes(sizes)
  1036. self.set_verts(verts, closed)
  1037. self.stale = True
  1038. def set_verts(self, verts, closed=True):
  1039. """
  1040. Set the vertices of the polygons.
  1041. Parameters
  1042. ----------
  1043. verts : list of array-like
  1044. The sequence of polygons [*verts0*, *verts1*, ...] where each
  1045. element *verts_i* defines the vertices of polygon *i* as a 2D
  1046. array-like of shape (M, 2).
  1047. closed : bool, default: True
  1048. Whether the polygon should be closed by adding a CLOSEPOLY
  1049. connection at the end.
  1050. """
  1051. self.stale = True
  1052. if isinstance(verts, np.ma.MaskedArray):
  1053. verts = verts.astype(float).filled(np.nan)
  1054. # No need to do anything fancy if the path isn't closed.
  1055. if not closed:
  1056. self._paths = [mpath.Path(xy) for xy in verts]
  1057. return
  1058. # Fast path for arrays
  1059. if isinstance(verts, np.ndarray) and len(verts.shape) == 3:
  1060. verts_pad = np.concatenate((verts, verts[:, :1]), axis=1)
  1061. # Creating the codes once is much faster than having Path do it
  1062. # separately each time by passing closed=True.
  1063. codes = np.empty(verts_pad.shape[1], dtype=mpath.Path.code_type)
  1064. codes[:] = mpath.Path.LINETO
  1065. codes[0] = mpath.Path.MOVETO
  1066. codes[-1] = mpath.Path.CLOSEPOLY
  1067. self._paths = [mpath.Path(xy, codes) for xy in verts_pad]
  1068. return
  1069. self._paths = []
  1070. for xy in verts:
  1071. if len(xy):
  1072. self._paths.append(mpath.Path._create_closed(xy))
  1073. else:
  1074. self._paths.append(mpath.Path(xy))
  1075. set_paths = set_verts
  1076. def set_verts_and_codes(self, verts, codes):
  1077. """Initialize vertices with path codes."""
  1078. if len(verts) != len(codes):
  1079. raise ValueError("'codes' must be a 1D list or array "
  1080. "with the same length of 'verts'")
  1081. self._paths = [mpath.Path(xy, cds) if len(xy) else mpath.Path(xy)
  1082. for xy, cds in zip(verts, codes)]
  1083. self.stale = True
  1084. class FillBetweenPolyCollection(PolyCollection):
  1085. """
  1086. `.PolyCollection` that fills the area between two x- or y-curves.
  1087. """
  1088. def __init__(
  1089. self, t_direction, t, f1, f2, *,
  1090. where=None, interpolate=False, step=None, **kwargs):
  1091. """
  1092. Parameters
  1093. ----------
  1094. t_direction : {{'x', 'y'}}
  1095. The axes on which the variable lies.
  1096. - 'x': the curves are ``(t, f1)`` and ``(t, f2)``.
  1097. - 'y': the curves are ``(f1, t)`` and ``(f2, t)``.
  1098. t : array-like
  1099. The ``t_direction`` coordinates of the nodes defining the curves.
  1100. f1 : array-like or float
  1101. The other coordinates of the nodes defining the first curve.
  1102. f2 : array-like or float
  1103. The other coordinates of the nodes defining the second curve.
  1104. where : array-like of bool, optional
  1105. Define *where* to exclude some {dir} regions from being filled.
  1106. The filled regions are defined by the coordinates ``t[where]``.
  1107. More precisely, fill between ``t[i]`` and ``t[i+1]`` if
  1108. ``where[i] and where[i+1]``. Note that this definition implies
  1109. that an isolated *True* value between two *False* values in *where*
  1110. will not result in filling. Both sides of the *True* position
  1111. remain unfilled due to the adjacent *False* values.
  1112. interpolate : bool, default: False
  1113. This option is only relevant if *where* is used and the two curves
  1114. are crossing each other.
  1115. Semantically, *where* is often used for *f1* > *f2* or
  1116. similar. By default, the nodes of the polygon defining the filled
  1117. region will only be placed at the positions in the *t* array.
  1118. Such a polygon cannot describe the above semantics close to the
  1119. intersection. The t-sections containing the intersection are
  1120. simply clipped.
  1121. Setting *interpolate* to *True* will calculate the actual
  1122. intersection point and extend the filled region up to this point.
  1123. step : {{'pre', 'post', 'mid'}}, optional
  1124. Define *step* if the filling should be a step function,
  1125. i.e. constant in between *t*. The value determines where the
  1126. step will occur:
  1127. - 'pre': The f value is continued constantly to the left from
  1128. every *t* position, i.e. the interval ``(t[i-1], t[i]]`` has the
  1129. value ``f[i]``.
  1130. - 'post': The y value is continued constantly to the right from
  1131. every *x* position, i.e. the interval ``[t[i], t[i+1])`` has the
  1132. value ``f[i]``.
  1133. - 'mid': Steps occur half-way between the *t* positions.
  1134. **kwargs
  1135. Forwarded to `.PolyCollection`.
  1136. See Also
  1137. --------
  1138. .Axes.fill_between, .Axes.fill_betweenx
  1139. """
  1140. self.t_direction = t_direction
  1141. self._interpolate = interpolate
  1142. self._step = step
  1143. verts = self._make_verts(t, f1, f2, where)
  1144. super().__init__(verts, **kwargs)
  1145. @staticmethod
  1146. def _f_dir_from_t(t_direction):
  1147. """The direction that is other than `t_direction`."""
  1148. if t_direction == "x":
  1149. return "y"
  1150. elif t_direction == "y":
  1151. return "x"
  1152. else:
  1153. msg = f"t_direction must be 'x' or 'y', got {t_direction!r}"
  1154. raise ValueError(msg)
  1155. @property
  1156. def _f_direction(self):
  1157. """The direction that is other than `self.t_direction`."""
  1158. return self._f_dir_from_t(self.t_direction)
  1159. def set_data(self, t, f1, f2, *, where=None):
  1160. """
  1161. Set new values for the two bounding curves.
  1162. Parameters
  1163. ----------
  1164. t : array-like
  1165. The ``self.t_direction`` coordinates of the nodes defining the curves.
  1166. f1 : array-like or float
  1167. The other coordinates of the nodes defining the first curve.
  1168. f2 : array-like or float
  1169. The other coordinates of the nodes defining the second curve.
  1170. where : array-like of bool, optional
  1171. Define *where* to exclude some {dir} regions from being filled.
  1172. The filled regions are defined by the coordinates ``t[where]``.
  1173. More precisely, fill between ``t[i]`` and ``t[i+1]`` if
  1174. ``where[i] and where[i+1]``. Note that this definition implies
  1175. that an isolated *True* value between two *False* values in *where*
  1176. will not result in filling. Both sides of the *True* position
  1177. remain unfilled due to the adjacent *False* values.
  1178. See Also
  1179. --------
  1180. .PolyCollection.set_verts, .Line2D.set_data
  1181. """
  1182. t, f1, f2 = self.axes._fill_between_process_units(
  1183. self.t_direction, self._f_direction, t, f1, f2)
  1184. verts = self._make_verts(t, f1, f2, where)
  1185. self.set_verts(verts)
  1186. def get_datalim(self, transData):
  1187. """Calculate the data limits and return them as a `.Bbox`."""
  1188. datalim = transforms.Bbox.null()
  1189. datalim.update_from_data_xy((self.get_transform() - transData).transform(
  1190. np.concatenate([self._bbox, [self._bbox.minpos]])))
  1191. return datalim
  1192. def _make_verts(self, t, f1, f2, where):
  1193. """
  1194. Make verts that can be forwarded to `.PolyCollection`.
  1195. """
  1196. self._validate_shapes(self.t_direction, self._f_direction, t, f1, f2)
  1197. where = self._get_data_mask(t, f1, f2, where)
  1198. t, f1, f2 = np.broadcast_arrays(np.atleast_1d(t), f1, f2, subok=True)
  1199. self._bbox = transforms.Bbox.null()
  1200. self._bbox.update_from_data_xy(self._fix_pts_xy_order(np.concatenate([
  1201. np.stack((t[where], f[where]), axis=-1) for f in (f1, f2)])))
  1202. return [
  1203. self._make_verts_for_region(t, f1, f2, idx0, idx1)
  1204. for idx0, idx1 in cbook.contiguous_regions(where)
  1205. ]
  1206. def _get_data_mask(self, t, f1, f2, where):
  1207. """
  1208. Return a bool array, with True at all points that should eventually be rendered.
  1209. The array is True at a point if none of the data inputs
  1210. *t*, *f1*, *f2* is masked and if the input *where* is true at that point.
  1211. """
  1212. if where is None:
  1213. where = True
  1214. else:
  1215. where = np.asarray(where, dtype=bool)
  1216. if where.size != t.size:
  1217. msg = "where size ({}) does not match {!r} size ({})".format(
  1218. where.size, self.t_direction, t.size)
  1219. raise ValueError(msg)
  1220. return where & ~functools.reduce(
  1221. np.logical_or, map(np.ma.getmaskarray, [t, f1, f2]))
  1222. @staticmethod
  1223. def _validate_shapes(t_dir, f_dir, t, f1, f2):
  1224. """Validate that t, f1 and f2 are 1-dimensional and have the same length."""
  1225. names = (d + s for d, s in zip((t_dir, f_dir, f_dir), ("", "1", "2")))
  1226. for name, array in zip(names, [t, f1, f2]):
  1227. if array.ndim > 1:
  1228. raise ValueError(f"{name!r} is not 1-dimensional")
  1229. if t.size > 1 and array.size > 1 and t.size != array.size:
  1230. msg = "{!r} has size {}, but {!r} has an unequal size of {}".format(
  1231. t_dir, t.size, name, array.size)
  1232. raise ValueError(msg)
  1233. def _make_verts_for_region(self, t, f1, f2, idx0, idx1):
  1234. """
  1235. Make ``verts`` for a contiguous region between ``idx0`` and ``idx1``, taking
  1236. into account ``step`` and ``interpolate``.
  1237. """
  1238. t_slice = t[idx0:idx1]
  1239. f1_slice = f1[idx0:idx1]
  1240. f2_slice = f2[idx0:idx1]
  1241. if self._step is not None:
  1242. step_func = cbook.STEP_LOOKUP_MAP["steps-" + self._step]
  1243. t_slice, f1_slice, f2_slice = step_func(t_slice, f1_slice, f2_slice)
  1244. if self._interpolate:
  1245. start = self._get_interpolating_points(t, f1, f2, idx0)
  1246. end = self._get_interpolating_points(t, f1, f2, idx1)
  1247. else:
  1248. # Handle scalar f2 (e.g. 0): the fill should go all
  1249. # the way down to 0 even if none of the dep1 sample points do.
  1250. start = t_slice[0], f2_slice[0]
  1251. end = t_slice[-1], f2_slice[-1]
  1252. pts = np.concatenate((
  1253. np.asarray([start]),
  1254. np.stack((t_slice, f1_slice), axis=-1),
  1255. np.asarray([end]),
  1256. np.stack((t_slice, f2_slice), axis=-1)[::-1]))
  1257. return self._fix_pts_xy_order(pts)
  1258. @classmethod
  1259. def _get_interpolating_points(cls, t, f1, f2, idx):
  1260. """Calculate interpolating points."""
  1261. im1 = max(idx - 1, 0)
  1262. t_values = t[im1:idx+1]
  1263. diff_values = f1[im1:idx+1] - f2[im1:idx+1]
  1264. f1_values = f1[im1:idx+1]
  1265. if len(diff_values) == 2:
  1266. if np.ma.is_masked(diff_values[1]):
  1267. return t[im1], f1[im1]
  1268. elif np.ma.is_masked(diff_values[0]):
  1269. return t[idx], f1[idx]
  1270. diff_root_t = cls._get_diff_root(0, diff_values, t_values)
  1271. diff_root_f = cls._get_diff_root(diff_root_t, t_values, f1_values)
  1272. return diff_root_t, diff_root_f
  1273. @staticmethod
  1274. def _get_diff_root(x, xp, fp):
  1275. """Calculate diff root."""
  1276. order = xp.argsort()
  1277. return np.interp(x, xp[order], fp[order])
  1278. def _fix_pts_xy_order(self, pts):
  1279. """
  1280. Fix pts calculation results with `self.t_direction`.
  1281. In the workflow, it is assumed that `self.t_direction` is 'x'. If this
  1282. is not true, we need to exchange the coordinates.
  1283. """
  1284. return pts[:, ::-1] if self.t_direction == "y" else pts
  1285. class RegularPolyCollection(_CollectionWithSizes):
  1286. """A collection of n-sided regular polygons."""
  1287. _path_generator = mpath.Path.unit_regular_polygon
  1288. _factor = np.pi ** (-1/2)
  1289. def __init__(self,
  1290. numsides,
  1291. *,
  1292. rotation=0,
  1293. sizes=(1,),
  1294. **kwargs):
  1295. """
  1296. Parameters
  1297. ----------
  1298. numsides : int
  1299. The number of sides of the polygon.
  1300. rotation : float
  1301. The rotation of the polygon in radians.
  1302. sizes : tuple of float
  1303. The area of the circle circumscribing the polygon in points^2.
  1304. **kwargs
  1305. Forwarded to `.Collection`.
  1306. Examples
  1307. --------
  1308. See :doc:`/gallery/event_handling/lasso_demo` for a complete example::
  1309. offsets = np.random.rand(20, 2)
  1310. facecolors = [cm.jet(x) for x in np.random.rand(20)]
  1311. collection = RegularPolyCollection(
  1312. numsides=5, # a pentagon
  1313. rotation=0, sizes=(50,),
  1314. facecolors=facecolors,
  1315. edgecolors=("black",),
  1316. linewidths=(1,),
  1317. offsets=offsets,
  1318. offset_transform=ax.transData,
  1319. )
  1320. """
  1321. super().__init__(**kwargs)
  1322. self.set_sizes(sizes)
  1323. self._numsides = numsides
  1324. self._paths = [self._path_generator(numsides)]
  1325. self._rotation = rotation
  1326. self.set_transform(transforms.IdentityTransform())
  1327. def get_numsides(self):
  1328. return self._numsides
  1329. def get_rotation(self):
  1330. return self._rotation
  1331. @artist.allow_rasterization
  1332. def draw(self, renderer):
  1333. self.set_sizes(self._sizes, self.get_figure(root=True).dpi)
  1334. self._transforms = [
  1335. transforms.Affine2D(x).rotate(-self._rotation).get_matrix()
  1336. for x in self._transforms
  1337. ]
  1338. # Explicitly not super().draw, because set_sizes must be called before
  1339. # updating self._transforms.
  1340. Collection.draw(self, renderer)
  1341. class StarPolygonCollection(RegularPolyCollection):
  1342. """Draw a collection of regular stars with *numsides* points."""
  1343. _path_generator = mpath.Path.unit_regular_star
  1344. class AsteriskPolygonCollection(RegularPolyCollection):
  1345. """Draw a collection of regular asterisks with *numsides* points."""
  1346. _path_generator = mpath.Path.unit_regular_asterisk
  1347. class LineCollection(Collection):
  1348. r"""
  1349. Represents a sequence of `.Line2D`\s that should be drawn together.
  1350. This class extends `.Collection` to represent a sequence of
  1351. `.Line2D`\s instead of just a sequence of `.Patch`\s.
  1352. Just as in `.Collection`, each property of a *LineCollection* may be either
  1353. a single value or a list of values. This list is then used cyclically for
  1354. each element of the LineCollection, so the property of the ``i``\th element
  1355. of the collection is::
  1356. prop[i % len(prop)]
  1357. The properties of each member of a *LineCollection* default to their values
  1358. in :rc:`lines.*` instead of :rc:`patch.*`, and the property *colors* is
  1359. added in place of *edgecolors*.
  1360. """
  1361. _edge_default = True
  1362. def __init__(self, segments, # Can be None.
  1363. *,
  1364. zorder=2, # Collection.zorder is 1
  1365. **kwargs
  1366. ):
  1367. """
  1368. Parameters
  1369. ----------
  1370. segments : list of (N, 2) array-like
  1371. A sequence ``[line0, line1, ...]`` where each line is a (N, 2)-shape
  1372. array-like containing points::
  1373. line0 = [(x0, y0), (x1, y1), ...]
  1374. Each line can contain a different number of points.
  1375. linewidths : float or list of float, default: :rc:`lines.linewidth`
  1376. The width of each line in points.
  1377. colors : :mpltype:`color` or list of color, default: :rc:`lines.color`
  1378. A sequence of RGBA tuples (e.g., arbitrary color strings, etc, not
  1379. allowed).
  1380. antialiaseds : bool or list of bool, default: :rc:`lines.antialiased`
  1381. Whether to use antialiasing for each line.
  1382. zorder : float, default: 2
  1383. zorder of the lines once drawn.
  1384. facecolors : :mpltype:`color` or list of :mpltype:`color`, default: 'none'
  1385. When setting *facecolors*, each line is interpreted as a boundary
  1386. for an area, implicitly closing the path from the last point to the
  1387. first point. The enclosed area is filled with *facecolor*.
  1388. In order to manually specify what should count as the "interior" of
  1389. each line, please use `.PathCollection` instead, where the
  1390. "interior" can be specified by appropriate usage of
  1391. `~.path.Path.CLOSEPOLY`.
  1392. **kwargs
  1393. Forwarded to `.Collection`.
  1394. """
  1395. # Unfortunately, mplot3d needs this explicit setting of 'facecolors'.
  1396. kwargs.setdefault('facecolors', 'none')
  1397. super().__init__(
  1398. zorder=zorder,
  1399. **kwargs)
  1400. self.set_segments(segments)
  1401. def set_segments(self, segments):
  1402. if segments is None:
  1403. return
  1404. self._paths = [mpath.Path(seg) if isinstance(seg, np.ma.MaskedArray)
  1405. else mpath.Path(np.asarray(seg, float))
  1406. for seg in segments]
  1407. self.stale = True
  1408. set_verts = set_segments # for compatibility with PolyCollection
  1409. set_paths = set_segments
  1410. def get_segments(self):
  1411. """
  1412. Returns
  1413. -------
  1414. list
  1415. List of segments in the LineCollection. Each list item contains an
  1416. array of vertices.
  1417. """
  1418. segments = []
  1419. for path in self._paths:
  1420. vertices = [
  1421. vertex
  1422. for vertex, _
  1423. # Never simplify here, we want to get the data-space values
  1424. # back and there in no way to know the "right" simplification
  1425. # threshold so never try.
  1426. in path.iter_segments(simplify=False)
  1427. ]
  1428. vertices = np.asarray(vertices)
  1429. segments.append(vertices)
  1430. return segments
  1431. def _get_default_linewidth(self):
  1432. return mpl.rcParams['lines.linewidth']
  1433. def _get_default_antialiased(self):
  1434. return mpl.rcParams['lines.antialiased']
  1435. def _get_default_edgecolor(self):
  1436. return mpl.rcParams['lines.color']
  1437. def _get_default_facecolor(self):
  1438. return 'none'
  1439. def set_alpha(self, alpha):
  1440. # docstring inherited
  1441. super().set_alpha(alpha)
  1442. if self._gapcolor is not None:
  1443. self.set_gapcolor(self._original_gapcolor)
  1444. def set_color(self, c):
  1445. """
  1446. Set the edgecolor(s) of the LineCollection.
  1447. Parameters
  1448. ----------
  1449. c : :mpltype:`color` or list of :mpltype:`color`
  1450. Single color (all lines have same color), or a
  1451. sequence of RGBA tuples; if it is a sequence the lines will
  1452. cycle through the sequence.
  1453. """
  1454. self.set_edgecolor(c)
  1455. set_colors = set_color
  1456. def get_color(self):
  1457. return self._edgecolors
  1458. get_colors = get_color # for compatibility with old versions
  1459. def set_gapcolor(self, gapcolor):
  1460. """
  1461. Set a color to fill the gaps in the dashed line style.
  1462. .. note::
  1463. Striped lines are created by drawing two interleaved dashed lines.
  1464. There can be overlaps between those two, which may result in
  1465. artifacts when using transparency.
  1466. This functionality is experimental and may change.
  1467. Parameters
  1468. ----------
  1469. gapcolor : :mpltype:`color` or list of :mpltype:`color` or None
  1470. The color with which to fill the gaps. If None, the gaps are
  1471. unfilled.
  1472. """
  1473. self._original_gapcolor = gapcolor
  1474. self._set_gapcolor(gapcolor)
  1475. def _set_gapcolor(self, gapcolor):
  1476. if gapcolor is not None:
  1477. gapcolor = mcolors.to_rgba_array(gapcolor, self._alpha)
  1478. self._gapcolor = gapcolor
  1479. self.stale = True
  1480. def get_gapcolor(self):
  1481. return self._gapcolor
  1482. def _get_inverse_paths_linestyles(self):
  1483. """
  1484. Returns the path and pattern for the gaps in the non-solid lines.
  1485. This path and pattern is the inverse of the path and pattern used to
  1486. construct the non-solid lines. For solid lines, we set the inverse path
  1487. to nans to prevent drawing an inverse line.
  1488. """
  1489. path_patterns = [
  1490. (mpath.Path(np.full((1, 2), np.nan)), ls)
  1491. if ls == (0, None) else
  1492. (path, mlines._get_inverse_dash_pattern(*ls))
  1493. for (path, ls) in
  1494. zip(self._paths, itertools.cycle(self._linestyles))]
  1495. return zip(*path_patterns)
  1496. class EventCollection(LineCollection):
  1497. """
  1498. A collection of locations along a single axis at which an "event" occurred.
  1499. The events are given by a 1-dimensional array. They do not have an
  1500. amplitude and are displayed as parallel lines.
  1501. """
  1502. _edge_default = True
  1503. def __init__(self,
  1504. positions, # Cannot be None.
  1505. orientation='horizontal',
  1506. *,
  1507. lineoffset=0,
  1508. linelength=1,
  1509. linewidth=None,
  1510. color=None,
  1511. linestyle='solid',
  1512. antialiased=None,
  1513. **kwargs
  1514. ):
  1515. """
  1516. Parameters
  1517. ----------
  1518. positions : 1D array-like
  1519. Each value is an event.
  1520. orientation : {'horizontal', 'vertical'}, default: 'horizontal'
  1521. The sequence of events is plotted along this direction.
  1522. The marker lines of the single events are along the orthogonal
  1523. direction.
  1524. lineoffset : float, default: 0
  1525. The offset of the center of the markers from the origin, in the
  1526. direction orthogonal to *orientation*.
  1527. linelength : float, default: 1
  1528. The total height of the marker (i.e. the marker stretches from
  1529. ``lineoffset - linelength/2`` to ``lineoffset + linelength/2``).
  1530. linewidth : float or list thereof, default: :rc:`lines.linewidth`
  1531. The line width of the event lines, in points.
  1532. color : :mpltype:`color` or list of :mpltype:`color`, default: :rc:`lines.color`
  1533. The color of the event lines.
  1534. linestyle : str or tuple or list thereof, default: 'solid'
  1535. Valid strings are ['solid', 'dashed', 'dashdot', 'dotted',
  1536. '-', '--', '-.', ':']. Dash tuples should be of the form::
  1537. (offset, onoffseq),
  1538. where *onoffseq* is an even length tuple of on and off ink
  1539. in points.
  1540. antialiased : bool or list thereof, default: :rc:`lines.antialiased`
  1541. Whether to use antialiasing for drawing the lines.
  1542. **kwargs
  1543. Forwarded to `.LineCollection`.
  1544. Examples
  1545. --------
  1546. .. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py
  1547. """
  1548. super().__init__([],
  1549. linewidths=linewidth, linestyles=linestyle,
  1550. colors=color, antialiaseds=antialiased,
  1551. **kwargs)
  1552. self._is_horizontal = True # Initial value, may be switched below.
  1553. self._linelength = linelength
  1554. self._lineoffset = lineoffset
  1555. self.set_orientation(orientation)
  1556. self.set_positions(positions)
  1557. def get_positions(self):
  1558. """
  1559. Return an array containing the floating-point values of the positions.
  1560. """
  1561. pos = 0 if self.is_horizontal() else 1
  1562. return [segment[0, pos] for segment in self.get_segments()]
  1563. def set_positions(self, positions):
  1564. """Set the positions of the events."""
  1565. if positions is None:
  1566. positions = []
  1567. if np.ndim(positions) != 1:
  1568. raise ValueError('positions must be one-dimensional')
  1569. lineoffset = self.get_lineoffset()
  1570. linelength = self.get_linelength()
  1571. pos_idx = 0 if self.is_horizontal() else 1
  1572. segments = np.empty((len(positions), 2, 2))
  1573. segments[:, :, pos_idx] = np.sort(positions)[:, None]
  1574. segments[:, 0, 1 - pos_idx] = lineoffset + linelength / 2
  1575. segments[:, 1, 1 - pos_idx] = lineoffset - linelength / 2
  1576. self.set_segments(segments)
  1577. def add_positions(self, position):
  1578. """Add one or more events at the specified positions."""
  1579. if position is None or (hasattr(position, 'len') and
  1580. len(position) == 0):
  1581. return
  1582. positions = self.get_positions()
  1583. positions = np.hstack([positions, np.asanyarray(position)])
  1584. self.set_positions(positions)
  1585. extend_positions = append_positions = add_positions
  1586. def is_horizontal(self):
  1587. """True if the eventcollection is horizontal, False if vertical."""
  1588. return self._is_horizontal
  1589. def get_orientation(self):
  1590. """
  1591. Return the orientation of the event line ('horizontal' or 'vertical').
  1592. """
  1593. return 'horizontal' if self.is_horizontal() else 'vertical'
  1594. def switch_orientation(self):
  1595. """
  1596. Switch the orientation of the event line, either from vertical to
  1597. horizontal or vice versus.
  1598. """
  1599. segments = self.get_segments()
  1600. for i, segment in enumerate(segments):
  1601. segments[i] = np.fliplr(segment)
  1602. self.set_segments(segments)
  1603. self._is_horizontal = not self.is_horizontal()
  1604. self.stale = True
  1605. def set_orientation(self, orientation):
  1606. """
  1607. Set the orientation of the event line.
  1608. Parameters
  1609. ----------
  1610. orientation : {'horizontal', 'vertical'}
  1611. """
  1612. is_horizontal = _api.check_getitem(
  1613. {"horizontal": True, "vertical": False},
  1614. orientation=orientation)
  1615. if is_horizontal == self.is_horizontal():
  1616. return
  1617. self.switch_orientation()
  1618. def get_linelength(self):
  1619. """Return the length of the lines used to mark each event."""
  1620. return self._linelength
  1621. def set_linelength(self, linelength):
  1622. """Set the length of the lines used to mark each event."""
  1623. if linelength == self.get_linelength():
  1624. return
  1625. lineoffset = self.get_lineoffset()
  1626. segments = self.get_segments()
  1627. pos = 1 if self.is_horizontal() else 0
  1628. for segment in segments:
  1629. segment[0, pos] = lineoffset + linelength / 2.
  1630. segment[1, pos] = lineoffset - linelength / 2.
  1631. self.set_segments(segments)
  1632. self._linelength = linelength
  1633. def get_lineoffset(self):
  1634. """Return the offset of the lines used to mark each event."""
  1635. return self._lineoffset
  1636. def set_lineoffset(self, lineoffset):
  1637. """Set the offset of the lines used to mark each event."""
  1638. if lineoffset == self.get_lineoffset():
  1639. return
  1640. linelength = self.get_linelength()
  1641. segments = self.get_segments()
  1642. pos = 1 if self.is_horizontal() else 0
  1643. for segment in segments:
  1644. segment[0, pos] = lineoffset + linelength / 2.
  1645. segment[1, pos] = lineoffset - linelength / 2.
  1646. self.set_segments(segments)
  1647. self._lineoffset = lineoffset
  1648. def get_linewidth(self):
  1649. """Get the width of the lines used to mark each event."""
  1650. return super().get_linewidth()[0]
  1651. def get_linewidths(self):
  1652. return super().get_linewidth()
  1653. def get_color(self):
  1654. """Return the color of the lines used to mark each event."""
  1655. return self.get_colors()[0]
  1656. class CircleCollection(_CollectionWithSizes):
  1657. """A collection of circles, drawn using splines."""
  1658. _factor = np.pi ** (-1/2)
  1659. def __init__(self, sizes, **kwargs):
  1660. """
  1661. Parameters
  1662. ----------
  1663. sizes : float or array-like
  1664. The area of each circle in points^2.
  1665. **kwargs
  1666. Forwarded to `.Collection`.
  1667. """
  1668. super().__init__(**kwargs)
  1669. self.set_sizes(sizes)
  1670. self.set_transform(transforms.IdentityTransform())
  1671. self._paths = [mpath.Path.unit_circle()]
  1672. class EllipseCollection(Collection):
  1673. """A collection of ellipses, drawn using splines."""
  1674. def __init__(self, widths, heights, angles, *, units='points', **kwargs):
  1675. """
  1676. Parameters
  1677. ----------
  1678. widths : array-like
  1679. The lengths of the first axes (e.g., major axis lengths).
  1680. heights : array-like
  1681. The lengths of second axes.
  1682. angles : array-like
  1683. The angles of the first axes, degrees CCW from the x-axis.
  1684. units : {'points', 'inches', 'dots', 'width', 'height', 'x', 'y', 'xy'}
  1685. The units in which majors and minors are given; 'width' and
  1686. 'height' refer to the dimensions of the axes, while 'x' and 'y'
  1687. refer to the *offsets* data units. 'xy' differs from all others in
  1688. that the angle as plotted varies with the aspect ratio, and equals
  1689. the specified angle only when the aspect ratio is unity. Hence
  1690. it behaves the same as the `~.patches.Ellipse` with
  1691. ``axes.transData`` as its transform.
  1692. **kwargs
  1693. Forwarded to `Collection`.
  1694. """
  1695. super().__init__(**kwargs)
  1696. self.set_widths(widths)
  1697. self.set_heights(heights)
  1698. self.set_angles(angles)
  1699. self._units = units
  1700. self.set_transform(transforms.IdentityTransform())
  1701. self._transforms = np.empty((0, 3, 3))
  1702. self._paths = [mpath.Path.unit_circle()]
  1703. def _set_transforms(self):
  1704. """Calculate transforms immediately before drawing."""
  1705. ax = self.axes
  1706. fig = self.get_figure(root=False)
  1707. if self._units == 'xy':
  1708. sc = 1
  1709. elif self._units == 'x':
  1710. sc = ax.bbox.width / ax.viewLim.width
  1711. elif self._units == 'y':
  1712. sc = ax.bbox.height / ax.viewLim.height
  1713. elif self._units == 'inches':
  1714. sc = fig.dpi
  1715. elif self._units == 'points':
  1716. sc = fig.dpi / 72.0
  1717. elif self._units == 'width':
  1718. sc = ax.bbox.width
  1719. elif self._units == 'height':
  1720. sc = ax.bbox.height
  1721. elif self._units == 'dots':
  1722. sc = 1.0
  1723. else:
  1724. raise ValueError(f'Unrecognized units: {self._units!r}')
  1725. self._transforms = np.zeros((len(self._widths), 3, 3))
  1726. widths = self._widths * sc
  1727. heights = self._heights * sc
  1728. sin_angle = np.sin(self._angles)
  1729. cos_angle = np.cos(self._angles)
  1730. self._transforms[:, 0, 0] = widths * cos_angle
  1731. self._transforms[:, 0, 1] = heights * -sin_angle
  1732. self._transforms[:, 1, 0] = widths * sin_angle
  1733. self._transforms[:, 1, 1] = heights * cos_angle
  1734. self._transforms[:, 2, 2] = 1.0
  1735. _affine = transforms.Affine2D
  1736. if self._units == 'xy':
  1737. m = ax.transData.get_affine().get_matrix().copy()
  1738. m[:2, 2:] = 0
  1739. self.set_transform(_affine(m))
  1740. def set_widths(self, widths):
  1741. """Set the lengths of the first axes (e.g., major axis)."""
  1742. self._widths = 0.5 * np.asarray(widths).ravel()
  1743. self.stale = True
  1744. def set_heights(self, heights):
  1745. """Set the lengths of second axes (e.g., minor axes)."""
  1746. self._heights = 0.5 * np.asarray(heights).ravel()
  1747. self.stale = True
  1748. def set_angles(self, angles):
  1749. """Set the angles of the first axes, degrees CCW from the x-axis."""
  1750. self._angles = np.deg2rad(angles).ravel()
  1751. self.stale = True
  1752. def get_widths(self):
  1753. """Get the lengths of the first axes (e.g., major axis)."""
  1754. return self._widths * 2
  1755. def get_heights(self):
  1756. """Set the lengths of second axes (e.g., minor axes)."""
  1757. return self._heights * 2
  1758. def get_angles(self):
  1759. """Get the angles of the first axes, degrees CCW from the x-axis."""
  1760. return np.rad2deg(self._angles)
  1761. @artist.allow_rasterization
  1762. def draw(self, renderer):
  1763. self._set_transforms()
  1764. super().draw(renderer)
  1765. class PatchCollection(Collection):
  1766. """
  1767. A generic collection of patches.
  1768. PatchCollection draws faster than a large number of equivalent individual
  1769. Patches. It also makes it easier to assign a colormap to a heterogeneous
  1770. collection of patches.
  1771. """
  1772. def __init__(self, patches, *, match_original=False, **kwargs):
  1773. """
  1774. Parameters
  1775. ----------
  1776. patches : list of `.Patch`
  1777. A sequence of Patch objects. This list may include
  1778. a heterogeneous assortment of different patch types.
  1779. match_original : bool, default: False
  1780. If True, use the colors and linewidths of the original
  1781. patches. If False, new colors may be assigned by
  1782. providing the standard collection arguments, facecolor,
  1783. edgecolor, linewidths, norm or cmap.
  1784. **kwargs
  1785. All other parameters are forwarded to `.Collection`.
  1786. If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds*
  1787. are None, they default to their `.rcParams` patch setting, in
  1788. sequence form.
  1789. Notes
  1790. -----
  1791. The use of `~matplotlib.cm.ScalarMappable` functionality is optional.
  1792. If the `~matplotlib.cm.ScalarMappable` matrix ``_A`` has been set (via
  1793. a call to `~.ScalarMappable.set_array`), at draw time a call to scalar
  1794. mappable will be made to set the face colors.
  1795. """
  1796. if match_original:
  1797. def determine_facecolor(patch):
  1798. if patch.get_fill():
  1799. return patch.get_facecolor()
  1800. return [0, 0, 0, 0]
  1801. kwargs['facecolors'] = [determine_facecolor(p) for p in patches]
  1802. kwargs['edgecolors'] = [p.get_edgecolor() for p in patches]
  1803. kwargs['linewidths'] = [p.get_linewidth() for p in patches]
  1804. kwargs['linestyles'] = [p.get_linestyle() for p in patches]
  1805. kwargs['antialiaseds'] = [p.get_antialiased() for p in patches]
  1806. super().__init__(**kwargs)
  1807. self.set_paths(patches)
  1808. def set_paths(self, patches):
  1809. paths = [p.get_transform().transform_path(p.get_path())
  1810. for p in patches]
  1811. self._paths = paths
  1812. class TriMesh(Collection):
  1813. """
  1814. Class for the efficient drawing of a triangular mesh using Gouraud shading.
  1815. A triangular mesh is a `~matplotlib.tri.Triangulation` object.
  1816. """
  1817. def __init__(self, triangulation, **kwargs):
  1818. super().__init__(**kwargs)
  1819. self._triangulation = triangulation
  1820. self._shading = 'gouraud'
  1821. self._bbox = transforms.Bbox.unit()
  1822. # Unfortunately this requires a copy, unless Triangulation
  1823. # was rewritten.
  1824. xy = np.hstack((triangulation.x.reshape(-1, 1),
  1825. triangulation.y.reshape(-1, 1)))
  1826. self._bbox.update_from_data_xy(xy)
  1827. def get_paths(self):
  1828. if self._paths is None:
  1829. self.set_paths()
  1830. return self._paths
  1831. def set_paths(self):
  1832. self._paths = self.convert_mesh_to_paths(self._triangulation)
  1833. @staticmethod
  1834. def convert_mesh_to_paths(tri):
  1835. """
  1836. Convert a given mesh into a sequence of `.Path` objects.
  1837. This function is primarily of use to implementers of backends that do
  1838. not directly support meshes.
  1839. """
  1840. triangles = tri.get_masked_triangles()
  1841. verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
  1842. return [mpath.Path(x) for x in verts]
  1843. @artist.allow_rasterization
  1844. def draw(self, renderer):
  1845. if not self.get_visible():
  1846. return
  1847. renderer.open_group(self.__class__.__name__, gid=self.get_gid())
  1848. transform = self.get_transform()
  1849. # Get a list of triangles and the color at each vertex.
  1850. tri = self._triangulation
  1851. triangles = tri.get_masked_triangles()
  1852. verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
  1853. self.update_scalarmappable()
  1854. colors = self._facecolors[triangles]
  1855. gc = renderer.new_gc()
  1856. self._set_gc_clip(gc)
  1857. gc.set_linewidth(self.get_linewidth()[0])
  1858. renderer.draw_gouraud_triangles(gc, verts, colors, transform.frozen())
  1859. gc.restore()
  1860. renderer.close_group(self.__class__.__name__)
  1861. class _MeshData:
  1862. r"""
  1863. Class for managing the two dimensional coordinates of Quadrilateral meshes
  1864. and the associated data with them. This class is a mixin and is intended to
  1865. be used with another collection that will implement the draw separately.
  1866. A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are
  1867. defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is
  1868. defined by the vertices ::
  1869. (m+1, n) ----------- (m+1, n+1)
  1870. / /
  1871. / /
  1872. / /
  1873. (m, n) -------- (m, n+1)
  1874. The mesh need not be regular and the polygons need not be convex.
  1875. Parameters
  1876. ----------
  1877. coordinates : (M+1, N+1, 2) array-like
  1878. The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates
  1879. of vertex (m, n).
  1880. shading : {'flat', 'gouraud'}, default: 'flat'
  1881. """
  1882. def __init__(self, coordinates, *, shading='flat'):
  1883. _api.check_shape((None, None, 2), coordinates=coordinates)
  1884. self._coordinates = coordinates
  1885. self._shading = shading
  1886. def set_array(self, A):
  1887. """
  1888. Set the data values.
  1889. Parameters
  1890. ----------
  1891. A : array-like
  1892. The mesh data. Supported array shapes are:
  1893. - (M, N) or (M*N,): a mesh with scalar data. The values are mapped
  1894. to colors using normalization and a colormap. See parameters
  1895. *norm*, *cmap*, *vmin*, *vmax*.
  1896. - (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
  1897. - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),
  1898. i.e. including transparency.
  1899. If the values are provided as a 2D grid, the shape must match the
  1900. coordinates grid. If the values are 1D, they are reshaped to 2D.
  1901. M, N follow from the coordinates grid, where the coordinates grid
  1902. shape is (M, N) for 'gouraud' *shading* and (M+1, N+1) for 'flat'
  1903. shading.
  1904. """
  1905. height, width = self._coordinates.shape[0:-1]
  1906. if self._shading == 'flat':
  1907. h, w = height - 1, width - 1
  1908. else:
  1909. h, w = height, width
  1910. ok_shapes = [(h, w, 3), (h, w, 4), (h, w), (h * w,)]
  1911. if A is not None:
  1912. shape = np.shape(A)
  1913. if shape not in ok_shapes:
  1914. raise ValueError(
  1915. f"For X ({width}) and Y ({height}) with {self._shading} "
  1916. f"shading, A should have shape "
  1917. f"{' or '.join(map(str, ok_shapes))}, not {A.shape}")
  1918. return super().set_array(A)
  1919. def get_coordinates(self):
  1920. """
  1921. Return the vertices of the mesh as an (M+1, N+1, 2) array.
  1922. M, N are the number of quadrilaterals in the rows / columns of the
  1923. mesh, corresponding to (M+1, N+1) vertices.
  1924. The last dimension specifies the components (x, y).
  1925. """
  1926. return self._coordinates
  1927. def get_edgecolor(self):
  1928. # docstring inherited
  1929. # Note that we want to return an array of shape (N*M, 4)
  1930. # a flattened RGBA collection
  1931. return super().get_edgecolor().reshape(-1, 4)
  1932. def get_facecolor(self):
  1933. # docstring inherited
  1934. # Note that we want to return an array of shape (N*M, 4)
  1935. # a flattened RGBA collection
  1936. return super().get_facecolor().reshape(-1, 4)
  1937. @staticmethod
  1938. def _convert_mesh_to_paths(coordinates):
  1939. """
  1940. Convert a given mesh into a sequence of `.Path` objects.
  1941. This function is primarily of use to implementers of backends that do
  1942. not directly support quadmeshes.
  1943. """
  1944. if isinstance(coordinates, np.ma.MaskedArray):
  1945. c = coordinates.data
  1946. else:
  1947. c = coordinates
  1948. points = np.concatenate([
  1949. c[:-1, :-1],
  1950. c[:-1, 1:],
  1951. c[1:, 1:],
  1952. c[1:, :-1],
  1953. c[:-1, :-1]
  1954. ], axis=2).reshape((-1, 5, 2))
  1955. return [mpath.Path(x) for x in points]
  1956. def _convert_mesh_to_triangles(self, coordinates):
  1957. """
  1958. Convert a given mesh into a sequence of triangles, each point
  1959. with its own color. The result can be used to construct a call to
  1960. `~.RendererBase.draw_gouraud_triangles`.
  1961. """
  1962. if isinstance(coordinates, np.ma.MaskedArray):
  1963. p = coordinates.data
  1964. else:
  1965. p = coordinates
  1966. p_a = p[:-1, :-1]
  1967. p_b = p[:-1, 1:]
  1968. p_c = p[1:, 1:]
  1969. p_d = p[1:, :-1]
  1970. p_center = (p_a + p_b + p_c + p_d) / 4.0
  1971. triangles = np.concatenate([
  1972. p_a, p_b, p_center,
  1973. p_b, p_c, p_center,
  1974. p_c, p_d, p_center,
  1975. p_d, p_a, p_center,
  1976. ], axis=2).reshape((-1, 3, 2))
  1977. c = self.get_facecolor().reshape((*coordinates.shape[:2], 4))
  1978. z = self.get_array()
  1979. mask = z.mask if np.ma.is_masked(z) else None
  1980. if mask is not None:
  1981. c[mask, 3] = np.nan
  1982. c_a = c[:-1, :-1]
  1983. c_b = c[:-1, 1:]
  1984. c_c = c[1:, 1:]
  1985. c_d = c[1:, :-1]
  1986. c_center = (c_a + c_b + c_c + c_d) / 4.0
  1987. colors = np.concatenate([
  1988. c_a, c_b, c_center,
  1989. c_b, c_c, c_center,
  1990. c_c, c_d, c_center,
  1991. c_d, c_a, c_center,
  1992. ], axis=2).reshape((-1, 3, 4))
  1993. tmask = np.isnan(colors[..., 2, 3])
  1994. return triangles[~tmask], colors[~tmask]
  1995. class QuadMesh(_MeshData, Collection):
  1996. r"""
  1997. Class for the efficient drawing of a quadrilateral mesh.
  1998. A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are
  1999. defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is
  2000. defined by the vertices ::
  2001. (m+1, n) ----------- (m+1, n+1)
  2002. / /
  2003. / /
  2004. / /
  2005. (m, n) -------- (m, n+1)
  2006. The mesh need not be regular and the polygons need not be convex.
  2007. Parameters
  2008. ----------
  2009. coordinates : (M+1, N+1, 2) array-like
  2010. The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates
  2011. of vertex (m, n).
  2012. antialiased : bool, default: True
  2013. shading : {'flat', 'gouraud'}, default: 'flat'
  2014. Notes
  2015. -----
  2016. Unlike other `.Collection`\s, the default *pickradius* of `.QuadMesh` is 0,
  2017. i.e. `~.Artist.contains` checks whether the test point is within any of the
  2018. mesh quadrilaterals.
  2019. """
  2020. def __init__(self, coordinates, *, antialiased=True, shading='flat',
  2021. **kwargs):
  2022. kwargs.setdefault("pickradius", 0)
  2023. super().__init__(coordinates=coordinates, shading=shading)
  2024. Collection.__init__(self, **kwargs)
  2025. self._antialiased = antialiased
  2026. self._bbox = transforms.Bbox.unit()
  2027. self._bbox.update_from_data_xy(self._coordinates.reshape(-1, 2))
  2028. self.set_mouseover(False)
  2029. def get_paths(self):
  2030. if self._paths is None:
  2031. self.set_paths()
  2032. return self._paths
  2033. def set_paths(self):
  2034. self._paths = self._convert_mesh_to_paths(self._coordinates)
  2035. self.stale = True
  2036. def get_datalim(self, transData):
  2037. return (self.get_transform() - transData).transform_bbox(self._bbox)
  2038. @artist.allow_rasterization
  2039. def draw(self, renderer):
  2040. if not self.get_visible():
  2041. return
  2042. renderer.open_group(self.__class__.__name__, self.get_gid())
  2043. transform = self.get_transform()
  2044. offset_trf = self.get_offset_transform()
  2045. offsets = self.get_offsets()
  2046. if self.have_units():
  2047. xs = self.convert_xunits(offsets[:, 0])
  2048. ys = self.convert_yunits(offsets[:, 1])
  2049. offsets = np.column_stack([xs, ys])
  2050. self.update_scalarmappable()
  2051. if not transform.is_affine:
  2052. coordinates = self._coordinates.reshape((-1, 2))
  2053. coordinates = transform.transform(coordinates)
  2054. coordinates = coordinates.reshape(self._coordinates.shape)
  2055. transform = transforms.IdentityTransform()
  2056. else:
  2057. coordinates = self._coordinates
  2058. if not offset_trf.is_affine:
  2059. offsets = offset_trf.transform_non_affine(offsets)
  2060. offset_trf = offset_trf.get_affine()
  2061. gc = renderer.new_gc()
  2062. gc.set_snap(self.get_snap())
  2063. self._set_gc_clip(gc)
  2064. gc.set_linewidth(self.get_linewidth()[0])
  2065. if self._shading == 'gouraud':
  2066. triangles, colors = self._convert_mesh_to_triangles(coordinates)
  2067. renderer.draw_gouraud_triangles(
  2068. gc, triangles, colors, transform.frozen())
  2069. else:
  2070. renderer.draw_quad_mesh(
  2071. gc, transform.frozen(),
  2072. coordinates.shape[1] - 1, coordinates.shape[0] - 1,
  2073. coordinates, offsets, offset_trf,
  2074. # Backends expect flattened rgba arrays (n*m, 4) for fc and ec
  2075. self.get_facecolor().reshape((-1, 4)),
  2076. self._antialiased, self.get_edgecolors().reshape((-1, 4)))
  2077. gc.restore()
  2078. renderer.close_group(self.__class__.__name__)
  2079. self.stale = False
  2080. def get_cursor_data(self, event):
  2081. contained, info = self.contains(event)
  2082. if contained and self.get_array() is not None:
  2083. return self.get_array().ravel()[info["ind"]]
  2084. return None
  2085. class PolyQuadMesh(_MeshData, PolyCollection):
  2086. """
  2087. Class for drawing a quadrilateral mesh as individual Polygons.
  2088. A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are
  2089. defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is
  2090. defined by the vertices ::
  2091. (m+1, n) ----------- (m+1, n+1)
  2092. / /
  2093. / /
  2094. / /
  2095. (m, n) -------- (m, n+1)
  2096. The mesh need not be regular and the polygons need not be convex.
  2097. Parameters
  2098. ----------
  2099. coordinates : (M+1, N+1, 2) array-like
  2100. The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates
  2101. of vertex (m, n).
  2102. Notes
  2103. -----
  2104. Unlike `.QuadMesh`, this class will draw each cell as an individual Polygon.
  2105. This is significantly slower, but allows for more flexibility when wanting
  2106. to add additional properties to the cells, such as hatching.
  2107. Another difference from `.QuadMesh` is that if any of the vertices or data
  2108. of a cell are masked, that Polygon will **not** be drawn and it won't be in
  2109. the list of paths returned.
  2110. """
  2111. def __init__(self, coordinates, **kwargs):
  2112. super().__init__(coordinates=coordinates)
  2113. PolyCollection.__init__(self, verts=[], **kwargs)
  2114. # Setting the verts updates the paths of the PolyCollection
  2115. # This is called after the initializers to make sure the kwargs
  2116. # have all been processed and available for the masking calculations
  2117. self._set_unmasked_verts()
  2118. def _get_unmasked_polys(self):
  2119. """Get the unmasked regions using the coordinates and array"""
  2120. # mask(X) | mask(Y)
  2121. mask = np.any(np.ma.getmaskarray(self._coordinates), axis=-1)
  2122. # We want the shape of the polygon, which is the corner of each X/Y array
  2123. mask = (mask[0:-1, 0:-1] | mask[1:, 1:] | mask[0:-1, 1:] | mask[1:, 0:-1])
  2124. arr = self.get_array()
  2125. if arr is not None:
  2126. arr = np.ma.getmaskarray(arr)
  2127. if arr.ndim == 3:
  2128. # RGB(A) case
  2129. mask |= np.any(arr, axis=-1)
  2130. elif arr.ndim == 2:
  2131. mask |= arr
  2132. else:
  2133. mask |= arr.reshape(self._coordinates[:-1, :-1, :].shape[:2])
  2134. return ~mask
  2135. def _set_unmasked_verts(self):
  2136. X = self._coordinates[..., 0]
  2137. Y = self._coordinates[..., 1]
  2138. unmask = self._get_unmasked_polys()
  2139. X1 = np.ma.filled(X[:-1, :-1])[unmask]
  2140. Y1 = np.ma.filled(Y[:-1, :-1])[unmask]
  2141. X2 = np.ma.filled(X[1:, :-1])[unmask]
  2142. Y2 = np.ma.filled(Y[1:, :-1])[unmask]
  2143. X3 = np.ma.filled(X[1:, 1:])[unmask]
  2144. Y3 = np.ma.filled(Y[1:, 1:])[unmask]
  2145. X4 = np.ma.filled(X[:-1, 1:])[unmask]
  2146. Y4 = np.ma.filled(Y[:-1, 1:])[unmask]
  2147. npoly = len(X1)
  2148. xy = np.ma.stack([X1, Y1, X2, Y2, X3, Y3, X4, Y4, X1, Y1], axis=-1)
  2149. verts = xy.reshape((npoly, 5, 2))
  2150. self.set_verts(verts)
  2151. def get_edgecolor(self):
  2152. # docstring inherited
  2153. # We only want to return the facecolors of the polygons
  2154. # that were drawn.
  2155. ec = super().get_edgecolor()
  2156. unmasked_polys = self._get_unmasked_polys().ravel()
  2157. if len(ec) != len(unmasked_polys):
  2158. # Mapping is off
  2159. return ec
  2160. return ec[unmasked_polys, :]
  2161. def get_facecolor(self):
  2162. # docstring inherited
  2163. # We only want to return the facecolors of the polygons
  2164. # that were drawn.
  2165. fc = super().get_facecolor()
  2166. unmasked_polys = self._get_unmasked_polys().ravel()
  2167. if len(fc) != len(unmasked_polys):
  2168. # Mapping is off
  2169. return fc
  2170. return fc[unmasked_polys, :]
  2171. def set_array(self, A):
  2172. # docstring inherited
  2173. prev_unmask = self._get_unmasked_polys()
  2174. super().set_array(A)
  2175. # If the mask has changed at all we need to update
  2176. # the set of Polys that we are drawing
  2177. if not np.array_equal(prev_unmask, self._get_unmasked_polys()):
  2178. self._set_unmasked_verts()