collections.py 75 KB

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