contour.py 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  1. """
  2. Classes to support contour plotting and labelling for the Axes class.
  3. """
  4. from contextlib import ExitStack
  5. import functools
  6. import math
  7. from numbers import Integral
  8. import numpy as np
  9. from numpy import ma
  10. import matplotlib as mpl
  11. from matplotlib import _api, _docstring
  12. from matplotlib.backend_bases import MouseButton
  13. from matplotlib.lines import Line2D
  14. from matplotlib.path import Path
  15. from matplotlib.text import Text
  16. import matplotlib.ticker as ticker
  17. import matplotlib.cm as cm
  18. import matplotlib.colors as mcolors
  19. import matplotlib.collections as mcoll
  20. import matplotlib.font_manager as font_manager
  21. import matplotlib.cbook as cbook
  22. import matplotlib.patches as mpatches
  23. import matplotlib.transforms as mtransforms
  24. def _contour_labeler_event_handler(cs, inline, inline_spacing, event):
  25. canvas = cs.axes.get_figure(root=True).canvas
  26. is_button = event.name == "button_press_event"
  27. is_key = event.name == "key_press_event"
  28. # Quit (even if not in infinite mode; this is consistent with
  29. # MATLAB and sometimes quite useful, but will require the user to
  30. # test how many points were actually returned before using data).
  31. if (is_button and event.button == MouseButton.MIDDLE
  32. or is_key and event.key in ["escape", "enter"]):
  33. canvas.stop_event_loop()
  34. # Pop last click.
  35. elif (is_button and event.button == MouseButton.RIGHT
  36. or is_key and event.key in ["backspace", "delete"]):
  37. # Unfortunately, if one is doing inline labels, then there is currently
  38. # no way to fix the broken contour - once humpty-dumpty is broken, he
  39. # can't be put back together. In inline mode, this does nothing.
  40. if not inline:
  41. cs.pop_label()
  42. canvas.draw()
  43. # Add new click.
  44. elif (is_button and event.button == MouseButton.LEFT
  45. # On macOS/gtk, some keys return None.
  46. or is_key and event.key is not None):
  47. if cs.axes.contains(event)[0]:
  48. cs.add_label_near(event.x, event.y, transform=False,
  49. inline=inline, inline_spacing=inline_spacing)
  50. canvas.draw()
  51. class ContourLabeler:
  52. """Mixin to provide labelling capability to `.ContourSet`."""
  53. def clabel(self, levels=None, *,
  54. fontsize=None, inline=True, inline_spacing=5, fmt=None,
  55. colors=None, use_clabeltext=False, manual=False,
  56. rightside_up=True, zorder=None):
  57. """
  58. Label a contour plot.
  59. Adds labels to line contours in this `.ContourSet` (which inherits from
  60. this mixin class).
  61. Parameters
  62. ----------
  63. levels : array-like, optional
  64. A list of level values, that should be labeled. The list must be
  65. a subset of ``cs.levels``. If not given, all levels are labeled.
  66. fontsize : str or float, default: :rc:`font.size`
  67. Size in points or relative size e.g., 'smaller', 'x-large'.
  68. See `.Text.set_size` for accepted string values.
  69. colors : :mpltype:`color` or colors or None, default: None
  70. The label colors:
  71. - If *None*, the color of each label matches the color of
  72. the corresponding contour.
  73. - If one string color, e.g., *colors* = 'r' or *colors* =
  74. 'red', all labels will be plotted in this color.
  75. - If a tuple of colors (string, float, RGB, etc), different labels
  76. will be plotted in different colors in the order specified.
  77. inline : bool, default: True
  78. If ``True`` the underlying contour is removed where the label is
  79. placed.
  80. inline_spacing : float, default: 5
  81. Space in pixels to leave on each side of label when placing inline.
  82. This spacing will be exact for labels at locations where the
  83. contour is straight, less so for labels on curved contours.
  84. fmt : `.Formatter` or str or callable or dict, optional
  85. How the levels are formatted:
  86. - If a `.Formatter`, it is used to format all levels at once, using
  87. its `.Formatter.format_ticks` method.
  88. - If a str, it is interpreted as a %-style format string.
  89. - If a callable, it is called with one level at a time and should
  90. return the corresponding label.
  91. - If a dict, it should directly map levels to labels.
  92. The default is to use a standard `.ScalarFormatter`.
  93. manual : bool or iterable, default: False
  94. If ``True``, contour labels will be placed manually using
  95. mouse clicks. Click the first button near a contour to
  96. add a label, click the second button (or potentially both
  97. mouse buttons at once) to finish adding labels. The third
  98. button can be used to remove the last label added, but
  99. only if labels are not inline. Alternatively, the keyboard
  100. can be used to select label locations (enter to end label
  101. placement, delete or backspace act like the third mouse button,
  102. and any other key will select a label location).
  103. *manual* can also be an iterable object of (x, y) tuples.
  104. Contour labels will be created as if mouse is clicked at each
  105. (x, y) position.
  106. rightside_up : bool, default: True
  107. If ``True``, label rotations will always be plus
  108. or minus 90 degrees from level.
  109. use_clabeltext : bool, default: False
  110. If ``True``, use `.Text.set_transform_rotates_text` to ensure that
  111. label rotation is updated whenever the Axes aspect changes.
  112. zorder : float or None, default: ``(2 + contour.get_zorder())``
  113. zorder of the contour labels.
  114. Returns
  115. -------
  116. labels
  117. A list of `.Text` instances for the labels.
  118. """
  119. # Based on the input arguments, clabel() adds a list of "label
  120. # specific" attributes to the ContourSet object. These attributes are
  121. # all of the form label* and names should be fairly self explanatory.
  122. #
  123. # Once these attributes are set, clabel passes control to the labels()
  124. # method (for automatic label placement) or blocking_input_loop and
  125. # _contour_labeler_event_handler (for manual label placement).
  126. if fmt is None:
  127. fmt = ticker.ScalarFormatter(useOffset=False)
  128. fmt.create_dummy_axis()
  129. self.labelFmt = fmt
  130. self._use_clabeltext = use_clabeltext
  131. self.labelManual = manual
  132. self.rightside_up = rightside_up
  133. self._clabel_zorder = 2 + self.get_zorder() if zorder is None else zorder
  134. if levels is None:
  135. levels = self.levels
  136. indices = list(range(len(self.cvalues)))
  137. else:
  138. levlabs = list(levels)
  139. indices, levels = [], []
  140. for i, lev in enumerate(self.levels):
  141. if lev in levlabs:
  142. indices.append(i)
  143. levels.append(lev)
  144. if len(levels) < len(levlabs):
  145. raise ValueError(f"Specified levels {levlabs} don't match "
  146. f"available levels {self.levels}")
  147. self.labelLevelList = levels
  148. self.labelIndiceList = indices
  149. self._label_font_props = font_manager.FontProperties(size=fontsize)
  150. if colors is None:
  151. self.labelMappable = self
  152. self.labelCValueList = np.take(self.cvalues, self.labelIndiceList)
  153. else:
  154. cmap = mcolors.ListedColormap(colors, N=len(self.labelLevelList))
  155. self.labelCValueList = list(range(len(self.labelLevelList)))
  156. self.labelMappable = cm.ScalarMappable(cmap=cmap,
  157. norm=mcolors.NoNorm())
  158. self.labelXYs = []
  159. if np.iterable(manual):
  160. for x, y in manual:
  161. self.add_label_near(x, y, inline, inline_spacing)
  162. elif manual:
  163. print('Select label locations manually using first mouse button.')
  164. print('End manual selection with second mouse button.')
  165. if not inline:
  166. print('Remove last label by clicking third mouse button.')
  167. mpl._blocking_input.blocking_input_loop(
  168. self.axes.get_figure(root=True),
  169. ["button_press_event", "key_press_event"],
  170. timeout=-1, handler=functools.partial(
  171. _contour_labeler_event_handler,
  172. self, inline, inline_spacing))
  173. else:
  174. self.labels(inline, inline_spacing)
  175. return cbook.silent_list('text.Text', self.labelTexts)
  176. def print_label(self, linecontour, labelwidth):
  177. """Return whether a contour is long enough to hold a label."""
  178. return (len(linecontour) > 10 * labelwidth
  179. or (len(linecontour)
  180. and (np.ptp(linecontour, axis=0) > 1.2 * labelwidth).any()))
  181. def too_close(self, x, y, lw):
  182. """Return whether a label is already near this location."""
  183. thresh = (1.2 * lw) ** 2
  184. return any((x - loc[0]) ** 2 + (y - loc[1]) ** 2 < thresh
  185. for loc in self.labelXYs)
  186. def _get_nth_label_width(self, nth):
  187. """Return the width of the *nth* label, in pixels."""
  188. fig = self.axes.get_figure(root=False)
  189. renderer = fig.get_figure(root=True)._get_renderer()
  190. return (Text(0, 0,
  191. self.get_text(self.labelLevelList[nth], self.labelFmt),
  192. figure=fig, fontproperties=self._label_font_props)
  193. .get_window_extent(renderer).width)
  194. def get_text(self, lev, fmt):
  195. """Get the text of the label."""
  196. if isinstance(lev, str):
  197. return lev
  198. elif isinstance(fmt, dict):
  199. return fmt.get(lev, '%1.3f')
  200. elif callable(getattr(fmt, "format_ticks", None)):
  201. return fmt.format_ticks([*self.labelLevelList, lev])[-1]
  202. elif callable(fmt):
  203. return fmt(lev)
  204. else:
  205. return fmt % lev
  206. def locate_label(self, linecontour, labelwidth):
  207. """
  208. Find good place to draw a label (relatively flat part of the contour).
  209. """
  210. ctr_size = len(linecontour)
  211. n_blocks = int(np.ceil(ctr_size / labelwidth)) if labelwidth > 1 else 1
  212. block_size = ctr_size if n_blocks == 1 else int(labelwidth)
  213. # Split contour into blocks of length ``block_size``, filling the last
  214. # block by cycling the contour start (per `np.resize` semantics). (Due
  215. # to cycling, the index returned is taken modulo ctr_size.)
  216. xx = np.resize(linecontour[:, 0], (n_blocks, block_size))
  217. yy = np.resize(linecontour[:, 1], (n_blocks, block_size))
  218. yfirst = yy[:, :1]
  219. ylast = yy[:, -1:]
  220. xfirst = xx[:, :1]
  221. xlast = xx[:, -1:]
  222. s = (yfirst - yy) * (xlast - xfirst) - (xfirst - xx) * (ylast - yfirst)
  223. l = np.hypot(xlast - xfirst, ylast - yfirst)
  224. # Ignore warning that divide by zero throws, as this is a valid option
  225. with np.errstate(divide='ignore', invalid='ignore'):
  226. distances = (abs(s) / l).sum(axis=-1)
  227. # Labels are drawn in the middle of the block (``hbsize``) where the
  228. # contour is the closest (per ``distances``) to a straight line, but
  229. # not `too_close()` to a preexisting label.
  230. hbsize = block_size // 2
  231. adist = np.argsort(distances)
  232. # If all candidates are `too_close()`, go back to the straightest part
  233. # (``adist[0]``).
  234. for idx in np.append(adist, adist[0]):
  235. x, y = xx[idx, hbsize], yy[idx, hbsize]
  236. if not self.too_close(x, y, labelwidth):
  237. break
  238. return x, y, (idx * block_size + hbsize) % ctr_size
  239. def _split_path_and_get_label_rotation(self, path, idx, screen_pos, lw, spacing=5):
  240. """
  241. Prepare for insertion of a label at index *idx* of *path*.
  242. Parameters
  243. ----------
  244. path : Path
  245. The path where the label will be inserted, in data space.
  246. idx : int
  247. The vertex index after which the label will be inserted.
  248. screen_pos : (float, float)
  249. The position where the label will be inserted, in screen space.
  250. lw : float
  251. The label width, in screen space.
  252. spacing : float
  253. Extra spacing around the label, in screen space.
  254. Returns
  255. -------
  256. path : Path
  257. The path, broken so that the label can be drawn over it.
  258. angle : float
  259. The rotation of the label.
  260. Notes
  261. -----
  262. Both tasks are done together to avoid calculating path lengths multiple times,
  263. which is relatively costly.
  264. The method used here involves computing the path length along the contour in
  265. pixel coordinates and then looking (label width / 2) away from central point to
  266. determine rotation and then to break contour if desired. The extra spacing is
  267. taken into account when breaking the path, but not when computing the angle.
  268. """
  269. xys = path.vertices
  270. codes = path.codes
  271. # Insert a vertex at idx/pos (converting back to data space), if there isn't yet
  272. # a vertex there. With infinite precision one could also always insert the
  273. # extra vertex (it will get masked out by the label below anyways), but floating
  274. # point inaccuracies (the point can have undergone a data->screen->data
  275. # transform loop) can slightly shift the point and e.g. shift the angle computed
  276. # below from exactly zero to nonzero.
  277. pos = self.get_transform().inverted().transform(screen_pos)
  278. if not np.allclose(pos, xys[idx]):
  279. xys = np.insert(xys, idx, pos, axis=0)
  280. codes = np.insert(codes, idx, Path.LINETO)
  281. # Find the connected component where the label will be inserted. Note that a
  282. # path always starts with a MOVETO, and we consider there's an implicit
  283. # MOVETO (closing the last path) at the end.
  284. movetos = (codes == Path.MOVETO).nonzero()[0]
  285. start = movetos[movetos <= idx][-1]
  286. try:
  287. stop = movetos[movetos > idx][0]
  288. except IndexError:
  289. stop = len(codes)
  290. # Restrict ourselves to the connected component.
  291. cc_xys = xys[start:stop]
  292. idx -= start
  293. # If the path is closed, rotate it s.t. it starts at the label.
  294. is_closed_path = codes[stop - 1] == Path.CLOSEPOLY
  295. if is_closed_path:
  296. cc_xys = np.concatenate([cc_xys[idx:-1], cc_xys[:idx+1]])
  297. idx = 0
  298. # Like np.interp, but additionally vectorized over fp.
  299. def interp_vec(x, xp, fp): return [np.interp(x, xp, col) for col in fp.T]
  300. # Use cumulative path lengths ("cpl") as curvilinear coordinate along contour.
  301. screen_xys = self.get_transform().transform(cc_xys)
  302. path_cpls = np.insert(
  303. np.cumsum(np.hypot(*np.diff(screen_xys, axis=0).T)), 0, 0)
  304. path_cpls -= path_cpls[idx]
  305. # Use linear interpolation to get end coordinates of label.
  306. target_cpls = np.array([-lw/2, lw/2])
  307. if is_closed_path: # For closed paths, target from the other end.
  308. target_cpls[0] += (path_cpls[-1] - path_cpls[0])
  309. (sx0, sx1), (sy0, sy1) = interp_vec(target_cpls, path_cpls, screen_xys)
  310. angle = np.rad2deg(np.arctan2(sy1 - sy0, sx1 - sx0)) # Screen space.
  311. if self.rightside_up: # Fix angle so text is never upside-down
  312. angle = (angle + 90) % 180 - 90
  313. target_cpls += [-spacing, +spacing] # Expand range by spacing.
  314. # Get indices near points of interest; use -1 as out of bounds marker.
  315. i0, i1 = np.interp(target_cpls, path_cpls, range(len(path_cpls)),
  316. left=-1, right=-1)
  317. i0 = math.floor(i0)
  318. i1 = math.ceil(i1)
  319. (x0, x1), (y0, y1) = interp_vec(target_cpls, path_cpls, cc_xys)
  320. # Actually break contours (dropping zero-len parts).
  321. new_xy_blocks = []
  322. new_code_blocks = []
  323. if is_closed_path:
  324. if i0 != -1 and i1 != -1:
  325. # This is probably wrong in the case that the entire contour would
  326. # be discarded, but ensures that a valid path is returned and is
  327. # consistent with behavior of mpl <3.8
  328. points = cc_xys[i1:i0+1]
  329. new_xy_blocks.extend([[(x1, y1)], points, [(x0, y0)]])
  330. nlines = len(points) + 1
  331. new_code_blocks.extend([[Path.MOVETO], [Path.LINETO] * nlines])
  332. else:
  333. if i0 != -1:
  334. new_xy_blocks.extend([cc_xys[:i0 + 1], [(x0, y0)]])
  335. new_code_blocks.extend([[Path.MOVETO], [Path.LINETO] * (i0 + 1)])
  336. if i1 != -1:
  337. new_xy_blocks.extend([[(x1, y1)], cc_xys[i1:]])
  338. new_code_blocks.extend([
  339. [Path.MOVETO], [Path.LINETO] * (len(cc_xys) - i1)])
  340. # Back to the full path.
  341. xys = np.concatenate([xys[:start], *new_xy_blocks, xys[stop:]])
  342. codes = np.concatenate([codes[:start], *new_code_blocks, codes[stop:]])
  343. return angle, Path(xys, codes)
  344. def add_label(self, x, y, rotation, lev, cvalue):
  345. """Add a contour label, respecting whether *use_clabeltext* was set."""
  346. data_x, data_y = self.axes.transData.inverted().transform((x, y))
  347. t = Text(
  348. data_x, data_y,
  349. text=self.get_text(lev, self.labelFmt),
  350. rotation=rotation,
  351. horizontalalignment='center', verticalalignment='center',
  352. zorder=self._clabel_zorder,
  353. color=self.labelMappable.to_rgba(cvalue, alpha=self.get_alpha()),
  354. fontproperties=self._label_font_props,
  355. clip_box=self.axes.bbox)
  356. if self._use_clabeltext:
  357. data_rotation, = self.axes.transData.inverted().transform_angles(
  358. [rotation], [[x, y]])
  359. t.set(rotation=data_rotation, transform_rotates_text=True)
  360. self.labelTexts.append(t)
  361. self.labelCValues.append(cvalue)
  362. self.labelXYs.append((x, y))
  363. # Add label to plot here - useful for manual mode label selection
  364. self.axes.add_artist(t)
  365. def add_label_near(self, x, y, inline=True, inline_spacing=5,
  366. transform=None):
  367. """
  368. Add a label near the point ``(x, y)``.
  369. Parameters
  370. ----------
  371. x, y : float
  372. The approximate location of the label.
  373. inline : bool, default: True
  374. If *True* remove the segment of the contour beneath the label.
  375. inline_spacing : int, default: 5
  376. Space in pixels to leave on each side of label when placing
  377. inline. This spacing will be exact for labels at locations where
  378. the contour is straight, less so for labels on curved contours.
  379. transform : `.Transform` or `False`, default: ``self.axes.transData``
  380. A transform applied to ``(x, y)`` before labeling. The default
  381. causes ``(x, y)`` to be interpreted as data coordinates. `False`
  382. is a synonym for `.IdentityTransform`; i.e. ``(x, y)`` should be
  383. interpreted as display coordinates.
  384. """
  385. if transform is None:
  386. transform = self.axes.transData
  387. if transform:
  388. x, y = transform.transform((x, y))
  389. idx_level_min, idx_vtx_min, proj = self._find_nearest_contour(
  390. (x, y), self.labelIndiceList)
  391. path = self._paths[idx_level_min]
  392. level = self.labelIndiceList.index(idx_level_min)
  393. label_width = self._get_nth_label_width(level)
  394. rotation, path = self._split_path_and_get_label_rotation(
  395. path, idx_vtx_min, proj, label_width, inline_spacing)
  396. self.add_label(*proj, rotation, self.labelLevelList[idx_level_min],
  397. self.labelCValueList[idx_level_min])
  398. if inline:
  399. self._paths[idx_level_min] = path
  400. def pop_label(self, index=-1):
  401. """Defaults to removing last label, but any index can be supplied"""
  402. self.labelCValues.pop(index)
  403. t = self.labelTexts.pop(index)
  404. t.remove()
  405. def labels(self, inline, inline_spacing):
  406. for idx, (icon, lev, cvalue) in enumerate(zip(
  407. self.labelIndiceList,
  408. self.labelLevelList,
  409. self.labelCValueList,
  410. )):
  411. trans = self.get_transform()
  412. label_width = self._get_nth_label_width(idx)
  413. additions = []
  414. for subpath in self._paths[icon]._iter_connected_components():
  415. screen_xys = trans.transform(subpath.vertices)
  416. # Check if long enough for a label
  417. if self.print_label(screen_xys, label_width):
  418. x, y, idx = self.locate_label(screen_xys, label_width)
  419. rotation, path = self._split_path_and_get_label_rotation(
  420. subpath, idx, (x, y),
  421. label_width, inline_spacing)
  422. self.add_label(x, y, rotation, lev, cvalue) # Really add label.
  423. if inline: # If inline, add new contours
  424. additions.append(path)
  425. else: # If not adding label, keep old path
  426. additions.append(subpath)
  427. # After looping over all segments on a contour, replace old path by new one
  428. # if inlining.
  429. if inline:
  430. self._paths[icon] = Path.make_compound_path(*additions)
  431. def remove(self):
  432. super().remove()
  433. for text in self.labelTexts:
  434. text.remove()
  435. def _find_closest_point_on_path(xys, p):
  436. """
  437. Parameters
  438. ----------
  439. xys : (N, 2) array-like
  440. Coordinates of vertices.
  441. p : (float, float)
  442. Coordinates of point.
  443. Returns
  444. -------
  445. d2min : float
  446. Minimum square distance of *p* to *xys*.
  447. proj : (float, float)
  448. Projection of *p* onto *xys*.
  449. imin : (int, int)
  450. Consecutive indices of vertices of segment in *xys* where *proj* is.
  451. Segments are considered as including their end-points; i.e. if the
  452. closest point on the path is a node in *xys* with index *i*, this
  453. returns ``(i-1, i)``. For the special case where *xys* is a single
  454. point, this returns ``(0, 0)``.
  455. """
  456. if len(xys) == 1:
  457. return (((p - xys[0]) ** 2).sum(), xys[0], (0, 0))
  458. dxys = xys[1:] - xys[:-1] # Individual segment vectors.
  459. norms = (dxys ** 2).sum(axis=1)
  460. norms[norms == 0] = 1 # For zero-length segment, replace 0/0 by 0/1.
  461. rel_projs = np.clip( # Project onto each segment in relative 0-1 coords.
  462. ((p - xys[:-1]) * dxys).sum(axis=1) / norms,
  463. 0, 1)[:, None]
  464. projs = xys[:-1] + rel_projs * dxys # Projs. onto each segment, in (x, y).
  465. d2s = ((projs - p) ** 2).sum(axis=1) # Squared distances.
  466. imin = np.argmin(d2s)
  467. return (d2s[imin], projs[imin], (imin, imin+1))
  468. _docstring.interpd.register(contour_set_attributes=r"""
  469. Attributes
  470. ----------
  471. levels : array
  472. The values of the contour levels.
  473. layers : array
  474. Same as levels for line contours; half-way between
  475. levels for filled contours. See ``ContourSet._process_colors``.
  476. """)
  477. @_docstring.interpd
  478. class ContourSet(ContourLabeler, mcoll.Collection):
  479. """
  480. Store a set of contour lines or filled regions.
  481. User-callable method: `~.Axes.clabel`
  482. Parameters
  483. ----------
  484. ax : `~matplotlib.axes.Axes`
  485. levels : [level0, level1, ..., leveln]
  486. A list of floating point numbers indicating the contour levels.
  487. allsegs : [level0segs, level1segs, ...]
  488. List of all the polygon segments for all the *levels*.
  489. For contour lines ``len(allsegs) == len(levels)``, and for
  490. filled contour regions ``len(allsegs) = len(levels)-1``. The lists
  491. should look like ::
  492. level0segs = [polygon0, polygon1, ...]
  493. polygon0 = [[x0, y0], [x1, y1], ...]
  494. allkinds : ``None`` or [level0kinds, level1kinds, ...]
  495. Optional list of all the polygon vertex kinds (code types), as
  496. described and used in Path. This is used to allow multiply-
  497. connected paths such as holes within filled polygons.
  498. If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
  499. should look like ::
  500. level0kinds = [polygon0kinds, ...]
  501. polygon0kinds = [vertexcode0, vertexcode1, ...]
  502. If *allkinds* is not ``None``, usually all polygons for a
  503. particular contour level are grouped together so that
  504. ``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
  505. **kwargs
  506. Keyword arguments are as described in the docstring of
  507. `~.Axes.contour`.
  508. %(contour_set_attributes)s
  509. """
  510. def __init__(self, ax, *args,
  511. levels=None, filled=False, linewidths=None, linestyles=None,
  512. hatches=(None,), alpha=None, origin=None, extent=None,
  513. cmap=None, colors=None, norm=None, vmin=None, vmax=None,
  514. colorizer=None, extend='neither', antialiased=None, nchunk=0,
  515. locator=None, transform=None, negative_linestyles=None, clip_path=None,
  516. **kwargs):
  517. """
  518. Draw contour lines or filled regions, depending on
  519. whether keyword arg *filled* is ``False`` (default) or ``True``.
  520. Call signature::
  521. ContourSet(ax, levels, allsegs, [allkinds], **kwargs)
  522. Parameters
  523. ----------
  524. ax : `~matplotlib.axes.Axes`
  525. The `~.axes.Axes` object to draw on.
  526. levels : [level0, level1, ..., leveln]
  527. A list of floating point numbers indicating the contour
  528. levels.
  529. allsegs : [level0segs, level1segs, ...]
  530. List of all the polygon segments for all the *levels*.
  531. For contour lines ``len(allsegs) == len(levels)``, and for
  532. filled contour regions ``len(allsegs) = len(levels)-1``. The lists
  533. should look like ::
  534. level0segs = [polygon0, polygon1, ...]
  535. polygon0 = [[x0, y0], [x1, y1], ...]
  536. allkinds : [level0kinds, level1kinds, ...], optional
  537. Optional list of all the polygon vertex kinds (code types), as
  538. described and used in Path. This is used to allow multiply-
  539. connected paths such as holes within filled polygons.
  540. If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
  541. should look like ::
  542. level0kinds = [polygon0kinds, ...]
  543. polygon0kinds = [vertexcode0, vertexcode1, ...]
  544. If *allkinds* is not ``None``, usually all polygons for a
  545. particular contour level are grouped together so that
  546. ``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
  547. **kwargs
  548. Keyword arguments are as described in the docstring of
  549. `~.Axes.contour`.
  550. """
  551. if antialiased is None and filled:
  552. # Eliminate artifacts; we are not stroking the boundaries.
  553. antialiased = False
  554. # The default for line contours will be taken from the
  555. # LineCollection default, which uses :rc:`lines.antialiased`.
  556. super().__init__(
  557. antialiaseds=antialiased,
  558. alpha=alpha,
  559. clip_path=clip_path,
  560. transform=transform,
  561. colorizer=colorizer,
  562. )
  563. self.axes = ax
  564. self.levels = levels
  565. self.filled = filled
  566. self.hatches = hatches
  567. self.origin = origin
  568. self.extent = extent
  569. self.colors = colors
  570. self.extend = extend
  571. self.nchunk = nchunk
  572. self.locator = locator
  573. if colorizer:
  574. self._set_colorizer_check_keywords(colorizer, cmap=cmap,
  575. norm=norm, vmin=vmin,
  576. vmax=vmax, colors=colors)
  577. norm = colorizer.norm
  578. cmap = colorizer.cmap
  579. if (isinstance(norm, mcolors.LogNorm)
  580. or isinstance(self.locator, ticker.LogLocator)):
  581. self.logscale = True
  582. if norm is None:
  583. norm = mcolors.LogNorm()
  584. else:
  585. self.logscale = False
  586. _api.check_in_list([None, 'lower', 'upper', 'image'], origin=origin)
  587. if self.extent is not None and len(self.extent) != 4:
  588. raise ValueError(
  589. "If given, 'extent' must be None or (x0, x1, y0, y1)")
  590. if self.colors is not None and cmap is not None:
  591. raise ValueError('Either colors or cmap must be None')
  592. if self.origin == 'image':
  593. self.origin = mpl.rcParams['image.origin']
  594. self._orig_linestyles = linestyles # Only kept for user access.
  595. self.negative_linestyles = negative_linestyles
  596. # If negative_linestyles was not defined as a keyword argument, define
  597. # negative_linestyles with rcParams
  598. if self.negative_linestyles is None:
  599. self.negative_linestyles = \
  600. mpl.rcParams['contour.negative_linestyle']
  601. kwargs = self._process_args(*args, **kwargs)
  602. self._process_levels()
  603. self._extend_min = self.extend in ['min', 'both']
  604. self._extend_max = self.extend in ['max', 'both']
  605. if self.colors is not None:
  606. if mcolors.is_color_like(self.colors):
  607. color_sequence = [self.colors]
  608. else:
  609. color_sequence = self.colors
  610. ncolors = len(self.levels)
  611. if self.filled:
  612. ncolors -= 1
  613. i0 = 0
  614. # Handle the case where colors are given for the extended
  615. # parts of the contour.
  616. use_set_under_over = False
  617. # if we are extending the lower end, and we've been given enough
  618. # colors then skip the first color in the resulting cmap. For the
  619. # extend_max case we don't need to worry about passing more colors
  620. # than ncolors as ListedColormap will clip.
  621. total_levels = (ncolors +
  622. int(self._extend_min) +
  623. int(self._extend_max))
  624. if (len(color_sequence) == total_levels and
  625. (self._extend_min or self._extend_max)):
  626. use_set_under_over = True
  627. if self._extend_min:
  628. i0 = 1
  629. cmap = mcolors.ListedColormap(color_sequence[i0:None], N=ncolors)
  630. if use_set_under_over:
  631. if self._extend_min:
  632. cmap.set_under(color_sequence[0])
  633. if self._extend_max:
  634. cmap.set_over(color_sequence[-1])
  635. # label lists must be initialized here
  636. self.labelTexts = []
  637. self.labelCValues = []
  638. self.set_cmap(cmap)
  639. if norm is not None:
  640. self.set_norm(norm)
  641. with self.norm.callbacks.blocked(signal="changed"):
  642. if vmin is not None:
  643. self.norm.vmin = vmin
  644. if vmax is not None:
  645. self.norm.vmax = vmax
  646. self.norm._changed()
  647. self._process_colors()
  648. if self._paths is None:
  649. self._paths = self._make_paths_from_contour_generator()
  650. if self.filled:
  651. if linewidths is not None:
  652. _api.warn_external('linewidths is ignored by contourf')
  653. # Lower and upper contour levels.
  654. lowers, uppers = self._get_lowers_and_uppers()
  655. self.set(
  656. edgecolor="none",
  657. # Default zorder taken from Collection
  658. zorder=kwargs.pop("zorder", 1),
  659. )
  660. else:
  661. self.set(
  662. facecolor="none",
  663. linewidths=self._process_linewidths(linewidths),
  664. linestyle=self._process_linestyles(linestyles),
  665. # Default zorder taken from LineCollection, which is higher
  666. # than for filled contours so that lines are displayed on top.
  667. zorder=kwargs.pop("zorder", 2),
  668. label="_nolegend_",
  669. )
  670. self.axes.add_collection(self, autolim=False)
  671. self.sticky_edges.x[:] = [self._mins[0], self._maxs[0]]
  672. self.sticky_edges.y[:] = [self._mins[1], self._maxs[1]]
  673. self.axes.update_datalim([self._mins, self._maxs])
  674. self.axes.autoscale_view(tight=True)
  675. self.changed() # set the colors
  676. if kwargs:
  677. _api.warn_external(
  678. 'The following kwargs were not used by contour: ' +
  679. ", ".join(map(repr, kwargs))
  680. )
  681. allsegs = property(lambda self: [
  682. [subp.vertices for subp in p._iter_connected_components()]
  683. for p in self.get_paths()])
  684. allkinds = property(lambda self: [
  685. [subp.codes for subp in p._iter_connected_components()]
  686. for p in self.get_paths()])
  687. alpha = property(lambda self: self.get_alpha())
  688. linestyles = property(lambda self: self._orig_linestyles)
  689. def get_transform(self):
  690. """Return the `.Transform` instance used by this ContourSet."""
  691. if self._transform is None:
  692. self._transform = self.axes.transData
  693. elif (not isinstance(self._transform, mtransforms.Transform)
  694. and hasattr(self._transform, '_as_mpl_transform')):
  695. self._transform = self._transform._as_mpl_transform(self.axes)
  696. return self._transform
  697. def __getstate__(self):
  698. state = self.__dict__.copy()
  699. # the C object _contour_generator cannot currently be pickled. This
  700. # isn't a big issue as it is not actually used once the contour has
  701. # been calculated.
  702. state['_contour_generator'] = None
  703. return state
  704. def legend_elements(self, variable_name='x', str_format=str):
  705. """
  706. Return a list of artists and labels suitable for passing through
  707. to `~.Axes.legend` which represent this ContourSet.
  708. The labels have the form "0 < x <= 1" stating the data ranges which
  709. the artists represent.
  710. Parameters
  711. ----------
  712. variable_name : str
  713. The string used inside the inequality used on the labels.
  714. str_format : function: float -> str
  715. Function used to format the numbers in the labels.
  716. Returns
  717. -------
  718. artists : list[`.Artist`]
  719. A list of the artists.
  720. labels : list[str]
  721. A list of the labels.
  722. """
  723. artists = []
  724. labels = []
  725. if self.filled:
  726. lowers, uppers = self._get_lowers_and_uppers()
  727. n_levels = len(self._paths)
  728. for idx in range(n_levels):
  729. artists.append(mpatches.Rectangle(
  730. (0, 0), 1, 1,
  731. facecolor=self.get_facecolor()[idx],
  732. hatch=self.hatches[idx % len(self.hatches)],
  733. ))
  734. lower = str_format(lowers[idx])
  735. upper = str_format(uppers[idx])
  736. if idx == 0 and self.extend in ('min', 'both'):
  737. labels.append(fr'${variable_name} \leq {lower}s$')
  738. elif idx == n_levels - 1 and self.extend in ('max', 'both'):
  739. labels.append(fr'${variable_name} > {upper}s$')
  740. else:
  741. labels.append(fr'${lower} < {variable_name} \leq {upper}$')
  742. else:
  743. for idx, level in enumerate(self.levels):
  744. artists.append(Line2D(
  745. [], [],
  746. color=self.get_edgecolor()[idx],
  747. linewidth=self.get_linewidths()[idx],
  748. linestyle=self.get_linestyles()[idx],
  749. ))
  750. labels.append(fr'${variable_name} = {str_format(level)}$')
  751. return artists, labels
  752. def _process_args(self, *args, **kwargs):
  753. """
  754. Process *args* and *kwargs*; override in derived classes.
  755. Must set self.levels, self.zmin and self.zmax, and update Axes limits.
  756. """
  757. self.levels = args[0]
  758. allsegs = args[1]
  759. allkinds = args[2] if len(args) > 2 else None
  760. self.zmax = np.max(self.levels)
  761. self.zmin = np.min(self.levels)
  762. if allkinds is None:
  763. allkinds = [[None] * len(segs) for segs in allsegs]
  764. # Check lengths of levels and allsegs.
  765. if self.filled:
  766. if len(allsegs) != len(self.levels) - 1:
  767. raise ValueError('must be one less number of segments as '
  768. 'levels')
  769. else:
  770. if len(allsegs) != len(self.levels):
  771. raise ValueError('must be same number of segments as levels')
  772. # Check length of allkinds.
  773. if len(allkinds) != len(allsegs):
  774. raise ValueError('allkinds has different length to allsegs')
  775. # Determine x, y bounds and update axes data limits.
  776. flatseglist = [s for seg in allsegs for s in seg]
  777. points = np.concatenate(flatseglist, axis=0)
  778. self._mins = points.min(axis=0)
  779. self._maxs = points.max(axis=0)
  780. # Each entry in (allsegs, allkinds) is a list of (segs, kinds): segs is a list
  781. # of (N, 2) arrays of xy coordinates, kinds is a list of arrays of corresponding
  782. # pathcodes. However, kinds can also be None; in which case all paths in that
  783. # list are codeless (this case is normalized above). These lists are used to
  784. # construct paths, which then get concatenated.
  785. self._paths = [Path.make_compound_path(*map(Path, segs, kinds))
  786. for segs, kinds in zip(allsegs, allkinds)]
  787. return kwargs
  788. def _make_paths_from_contour_generator(self):
  789. """Compute ``paths`` using C extension."""
  790. if self._paths is not None:
  791. return self._paths
  792. cg = self._contour_generator
  793. empty_path = Path(np.empty((0, 2)))
  794. vertices_and_codes = (
  795. map(cg.create_filled_contour, *self._get_lowers_and_uppers())
  796. if self.filled else
  797. map(cg.create_contour, self.levels))
  798. return [Path(np.concatenate(vs), np.concatenate(cs)) if len(vs) else empty_path
  799. for vs, cs in vertices_and_codes]
  800. def _get_lowers_and_uppers(self):
  801. """
  802. Return ``(lowers, uppers)`` for filled contours.
  803. """
  804. lowers = self._levels[:-1]
  805. if self.zmin == lowers[0]:
  806. # Include minimum values in lowest interval
  807. lowers = lowers.copy() # so we don't change self._levels
  808. if self.logscale:
  809. lowers[0] = 0.99 * self.zmin
  810. else:
  811. lowers[0] -= 1
  812. uppers = self._levels[1:]
  813. return (lowers, uppers)
  814. def changed(self):
  815. if not hasattr(self, "cvalues"):
  816. self._process_colors() # Sets cvalues.
  817. # Force an autoscale immediately because self.to_rgba() calls
  818. # autoscale_None() internally with the data passed to it,
  819. # so if vmin/vmax are not set yet, this would override them with
  820. # content from *cvalues* rather than levels like we want
  821. self.norm.autoscale_None(self.levels)
  822. self.set_array(self.cvalues)
  823. self.update_scalarmappable()
  824. alphas = np.broadcast_to(self.get_alpha(), len(self.cvalues))
  825. for label, cv, alpha in zip(self.labelTexts, self.labelCValues, alphas):
  826. label.set_alpha(alpha)
  827. label.set_color(self.labelMappable.to_rgba(cv))
  828. super().changed()
  829. def _autolev(self, N):
  830. """
  831. Select contour levels to span the data.
  832. The target number of levels, *N*, is used only when the
  833. scale is not log and default locator is used.
  834. We need two more levels for filled contours than for
  835. line contours, because for the latter we need to specify
  836. the lower and upper boundary of each range. For example,
  837. a single contour boundary, say at z = 0, requires only
  838. one contour line, but two filled regions, and therefore
  839. three levels to provide boundaries for both regions.
  840. """
  841. if self.locator is None:
  842. if self.logscale:
  843. self.locator = ticker.LogLocator()
  844. else:
  845. self.locator = ticker.MaxNLocator(N + 1, min_n_ticks=1)
  846. lev = self.locator.tick_values(self.zmin, self.zmax)
  847. try:
  848. if self.locator._symmetric:
  849. return lev
  850. except AttributeError:
  851. pass
  852. # Trim excess levels the locator may have supplied.
  853. under = np.nonzero(lev < self.zmin)[0]
  854. i0 = under[-1] if len(under) else 0
  855. over = np.nonzero(lev > self.zmax)[0]
  856. i1 = over[0] + 1 if len(over) else len(lev)
  857. if self.extend in ('min', 'both'):
  858. i0 += 1
  859. if self.extend in ('max', 'both'):
  860. i1 -= 1
  861. if i1 - i0 < 3:
  862. i0, i1 = 0, len(lev)
  863. return lev[i0:i1]
  864. def _process_contour_level_args(self, args, z_dtype):
  865. """
  866. Determine the contour levels and store in self.levels.
  867. """
  868. if self.levels is None:
  869. if args:
  870. levels_arg = args[0]
  871. elif np.issubdtype(z_dtype, bool):
  872. if self.filled:
  873. levels_arg = [0, .5, 1]
  874. else:
  875. levels_arg = [.5]
  876. else:
  877. levels_arg = 7 # Default, hard-wired.
  878. else:
  879. levels_arg = self.levels
  880. if isinstance(levels_arg, Integral):
  881. self.levels = self._autolev(levels_arg)
  882. else:
  883. self.levels = np.asarray(levels_arg, np.float64)
  884. if self.filled and len(self.levels) < 2:
  885. raise ValueError("Filled contours require at least 2 levels.")
  886. if len(self.levels) > 1 and np.min(np.diff(self.levels)) <= 0.0:
  887. raise ValueError("Contour levels must be increasing")
  888. def _process_levels(self):
  889. """
  890. Assign values to :attr:`layers` based on :attr:`levels`,
  891. adding extended layers as needed if contours are filled.
  892. For line contours, layers simply coincide with levels;
  893. a line is a thin layer. No extended levels are needed
  894. with line contours.
  895. """
  896. # Make a private _levels to include extended regions; we
  897. # want to leave the original levels attribute unchanged.
  898. # (Colorbar needs this even for line contours.)
  899. self._levels = list(self.levels)
  900. if self.logscale:
  901. lower, upper = 1e-250, 1e250
  902. else:
  903. lower, upper = -1e250, 1e250
  904. if self.extend in ('both', 'min'):
  905. self._levels.insert(0, lower)
  906. if self.extend in ('both', 'max'):
  907. self._levels.append(upper)
  908. self._levels = np.asarray(self._levels)
  909. if not self.filled:
  910. self.layers = self.levels
  911. return
  912. # Layer values are mid-way between levels in screen space.
  913. if self.logscale:
  914. # Avoid overflow by taking sqrt before multiplying.
  915. self.layers = (np.sqrt(self._levels[:-1])
  916. * np.sqrt(self._levels[1:]))
  917. else:
  918. self.layers = 0.5 * (self._levels[:-1] + self._levels[1:])
  919. def _process_colors(self):
  920. """
  921. Color argument processing for contouring.
  922. Note that we base the colormapping on the contour levels
  923. and layers, not on the actual range of the Z values. This
  924. means we don't have to worry about bad values in Z, and we
  925. always have the full dynamic range available for the selected
  926. levels.
  927. The color is based on the midpoint of the layer, except for
  928. extended end layers. By default, the norm vmin and vmax
  929. are the extreme values of the non-extended levels. Hence,
  930. the layer color extremes are not the extreme values of
  931. the colormap itself, but approach those values as the number
  932. of levels increases. An advantage of this scheme is that
  933. line contours, when added to filled contours, take on
  934. colors that are consistent with those of the filled regions;
  935. for example, a contour line on the boundary between two
  936. regions will have a color intermediate between those
  937. of the regions.
  938. """
  939. self.monochrome = self.cmap.monochrome
  940. if self.colors is not None:
  941. # Generate integers for direct indexing.
  942. i0, i1 = 0, len(self.levels)
  943. if self.filled:
  944. i1 -= 1
  945. # Out of range indices for over and under:
  946. if self.extend in ('both', 'min'):
  947. i0 -= 1
  948. if self.extend in ('both', 'max'):
  949. i1 += 1
  950. self.cvalues = list(range(i0, i1))
  951. self.set_norm(mcolors.NoNorm())
  952. else:
  953. self.cvalues = self.layers
  954. self.norm.autoscale_None(self.levels)
  955. self.set_array(self.cvalues)
  956. self.update_scalarmappable()
  957. if self.extend in ('both', 'max', 'min'):
  958. self.norm.clip = False
  959. def _process_linewidths(self, linewidths):
  960. Nlev = len(self.levels)
  961. if linewidths is None:
  962. default_linewidth = mpl.rcParams['contour.linewidth']
  963. if default_linewidth is None:
  964. default_linewidth = mpl.rcParams['lines.linewidth']
  965. return [default_linewidth] * Nlev
  966. elif not np.iterable(linewidths):
  967. return [linewidths] * Nlev
  968. else:
  969. linewidths = list(linewidths)
  970. return (linewidths * math.ceil(Nlev / len(linewidths)))[:Nlev]
  971. def _process_linestyles(self, linestyles):
  972. Nlev = len(self.levels)
  973. if linestyles is None:
  974. tlinestyles = ['solid'] * Nlev
  975. if self.monochrome:
  976. eps = - (self.zmax - self.zmin) * 1e-15
  977. for i, lev in enumerate(self.levels):
  978. if lev < eps:
  979. tlinestyles[i] = self.negative_linestyles
  980. else:
  981. if isinstance(linestyles, str):
  982. tlinestyles = [linestyles] * Nlev
  983. elif np.iterable(linestyles):
  984. tlinestyles = list(linestyles)
  985. if len(tlinestyles) < Nlev:
  986. nreps = int(np.ceil(Nlev / len(linestyles)))
  987. tlinestyles = tlinestyles * nreps
  988. if len(tlinestyles) > Nlev:
  989. tlinestyles = tlinestyles[:Nlev]
  990. else:
  991. raise ValueError("Unrecognized type for linestyles kwarg")
  992. return tlinestyles
  993. def _find_nearest_contour(self, xy, indices=None):
  994. """
  995. Find the point in the unfilled contour plot that is closest (in screen
  996. space) to point *xy*.
  997. Parameters
  998. ----------
  999. xy : tuple[float, float]
  1000. The reference point (in screen space).
  1001. indices : list of int or None, default: None
  1002. Indices of contour levels to consider. If None (the default), all levels
  1003. are considered.
  1004. Returns
  1005. -------
  1006. idx_level_min : int
  1007. The index of the contour level closest to *xy*.
  1008. idx_vtx_min : int
  1009. The index of the `.Path` segment closest to *xy* (at that level).
  1010. proj : (float, float)
  1011. The point in the contour plot closest to *xy*.
  1012. """
  1013. # Convert each contour segment to pixel coordinates and then compare the given
  1014. # point to those coordinates for each contour. This is fast enough in normal
  1015. # cases, but speedups may be possible.
  1016. if self.filled:
  1017. raise ValueError("Method does not support filled contours")
  1018. if indices is None:
  1019. indices = range(len(self._paths))
  1020. d2min = np.inf
  1021. idx_level_min = idx_vtx_min = proj_min = None
  1022. for idx_level in indices:
  1023. path = self._paths[idx_level]
  1024. idx_vtx_start = 0
  1025. for subpath in path._iter_connected_components():
  1026. if not len(subpath.vertices):
  1027. continue
  1028. lc = self.get_transform().transform(subpath.vertices)
  1029. d2, proj, leg = _find_closest_point_on_path(lc, xy)
  1030. if d2 < d2min:
  1031. d2min = d2
  1032. idx_level_min = idx_level
  1033. idx_vtx_min = leg[1] + idx_vtx_start
  1034. proj_min = proj
  1035. idx_vtx_start += len(subpath)
  1036. return idx_level_min, idx_vtx_min, proj_min
  1037. def find_nearest_contour(self, x, y, indices=None, pixel=True):
  1038. """
  1039. Find the point in the contour plot that is closest to ``(x, y)``.
  1040. This method does not support filled contours.
  1041. Parameters
  1042. ----------
  1043. x, y : float
  1044. The reference point.
  1045. indices : list of int or None, default: None
  1046. Indices of contour levels to consider. If None (the default), all
  1047. levels are considered.
  1048. pixel : bool, default: True
  1049. If *True*, measure distance in pixel (screen) space, which is
  1050. useful for manual contour labeling; else, measure distance in axes
  1051. space.
  1052. Returns
  1053. -------
  1054. path : int
  1055. The index of the path that is closest to ``(x, y)``. Each path corresponds
  1056. to one contour level.
  1057. subpath : int
  1058. The index within that closest path of the subpath that is closest to
  1059. ``(x, y)``. Each subpath corresponds to one unbroken contour line.
  1060. index : int
  1061. The index of the vertices within that subpath that are closest to
  1062. ``(x, y)``.
  1063. xmin, ymin : float
  1064. The point in the contour plot that is closest to ``(x, y)``.
  1065. d2 : float
  1066. The squared distance from ``(xmin, ymin)`` to ``(x, y)``.
  1067. """
  1068. segment = index = d2 = None
  1069. with ExitStack() as stack:
  1070. if not pixel:
  1071. # _find_nearest_contour works in pixel space. We want axes space, so
  1072. # effectively disable the transformation here by setting to identity.
  1073. stack.enter_context(self._cm_set(
  1074. transform=mtransforms.IdentityTransform()))
  1075. i_level, i_vtx, (xmin, ymin) = self._find_nearest_contour((x, y), indices)
  1076. if i_level is not None:
  1077. cc_cumlens = np.cumsum(
  1078. [*map(len, self._paths[i_level]._iter_connected_components())])
  1079. segment = cc_cumlens.searchsorted(i_vtx, "right")
  1080. index = i_vtx if segment == 0 else i_vtx - cc_cumlens[segment - 1]
  1081. d2 = (xmin-x)**2 + (ymin-y)**2
  1082. return (i_level, segment, index, xmin, ymin, d2)
  1083. def draw(self, renderer):
  1084. paths = self._paths
  1085. n_paths = len(paths)
  1086. if not self.filled or all(hatch is None for hatch in self.hatches):
  1087. super().draw(renderer)
  1088. return
  1089. # In presence of hatching, draw contours one at a time.
  1090. edgecolors = self.get_edgecolors()
  1091. if edgecolors.size == 0:
  1092. edgecolors = ("none",)
  1093. for idx in range(n_paths):
  1094. with cbook._setattr_cm(self, _paths=[paths[idx]]), self._cm_set(
  1095. hatch=self.hatches[idx % len(self.hatches)],
  1096. array=[self.get_array()[idx]],
  1097. linewidths=[self.get_linewidths()[idx % len(self.get_linewidths())]],
  1098. linestyles=[self.get_linestyles()[idx % len(self.get_linestyles())]],
  1099. edgecolors=edgecolors[idx % len(edgecolors)],
  1100. ):
  1101. super().draw(renderer)
  1102. @_docstring.interpd
  1103. class QuadContourSet(ContourSet):
  1104. """
  1105. Create and store a set of contour lines or filled regions.
  1106. This class is typically not instantiated directly by the user but by
  1107. `~.Axes.contour` and `~.Axes.contourf`.
  1108. %(contour_set_attributes)s
  1109. """
  1110. def _process_args(self, *args, corner_mask=None, algorithm=None, **kwargs):
  1111. """
  1112. Process args and kwargs.
  1113. """
  1114. if args and isinstance(args[0], QuadContourSet):
  1115. if self.levels is None:
  1116. self.levels = args[0].levels
  1117. self.zmin = args[0].zmin
  1118. self.zmax = args[0].zmax
  1119. self._corner_mask = args[0]._corner_mask
  1120. contour_generator = args[0]._contour_generator
  1121. self._mins = args[0]._mins
  1122. self._maxs = args[0]._maxs
  1123. self._algorithm = args[0]._algorithm
  1124. else:
  1125. import contourpy
  1126. if algorithm is None:
  1127. algorithm = mpl.rcParams['contour.algorithm']
  1128. mpl.rcParams.validate["contour.algorithm"](algorithm)
  1129. self._algorithm = algorithm
  1130. if corner_mask is None:
  1131. if self._algorithm == "mpl2005":
  1132. # mpl2005 does not support corner_mask=True so if not
  1133. # specifically requested then disable it.
  1134. corner_mask = False
  1135. else:
  1136. corner_mask = mpl.rcParams['contour.corner_mask']
  1137. self._corner_mask = corner_mask
  1138. x, y, z = self._contour_args(args, kwargs)
  1139. contour_generator = contourpy.contour_generator(
  1140. x, y, z, name=self._algorithm, corner_mask=self._corner_mask,
  1141. line_type=contourpy.LineType.SeparateCode,
  1142. fill_type=contourpy.FillType.OuterCode,
  1143. chunk_size=self.nchunk)
  1144. t = self.get_transform()
  1145. # if the transform is not trans data, and some part of it
  1146. # contains transData, transform the xs and ys to data coordinates
  1147. if (t != self.axes.transData and
  1148. any(t.contains_branch_seperately(self.axes.transData))):
  1149. trans_to_data = t - self.axes.transData
  1150. pts = np.vstack([x.flat, y.flat]).T
  1151. transformed_pts = trans_to_data.transform(pts)
  1152. x = transformed_pts[..., 0]
  1153. y = transformed_pts[..., 1]
  1154. self._mins = [ma.min(x), ma.min(y)]
  1155. self._maxs = [ma.max(x), ma.max(y)]
  1156. self._contour_generator = contour_generator
  1157. return kwargs
  1158. def _contour_args(self, args, kwargs):
  1159. if self.filled:
  1160. fn = 'contourf'
  1161. else:
  1162. fn = 'contour'
  1163. nargs = len(args)
  1164. if 0 < nargs <= 2:
  1165. z, *args = args
  1166. z = ma.asarray(z)
  1167. x, y = self._initialize_x_y(z)
  1168. elif 2 < nargs <= 4:
  1169. x, y, z_orig, *args = args
  1170. x, y, z = self._check_xyz(x, y, z_orig, kwargs)
  1171. else:
  1172. raise _api.nargs_error(fn, takes="from 1 to 4", given=nargs)
  1173. z = ma.masked_invalid(z, copy=False)
  1174. self.zmax = z.max().astype(float)
  1175. self.zmin = z.min().astype(float)
  1176. if self.logscale and self.zmin <= 0:
  1177. z = ma.masked_where(z <= 0, z)
  1178. _api.warn_external('Log scale: values of z <= 0 have been masked')
  1179. self.zmin = z.min().astype(float)
  1180. self._process_contour_level_args(args, z.dtype)
  1181. return (x, y, z)
  1182. def _check_xyz(self, x, y, z, kwargs):
  1183. """
  1184. Check that the shapes of the input arrays match; if x and y are 1D,
  1185. convert them to 2D using meshgrid.
  1186. """
  1187. x, y = self.axes._process_unit_info([("x", x), ("y", y)], kwargs)
  1188. x = np.asarray(x, dtype=np.float64)
  1189. y = np.asarray(y, dtype=np.float64)
  1190. z = ma.asarray(z)
  1191. if z.ndim != 2:
  1192. raise TypeError(f"Input z must be 2D, not {z.ndim}D")
  1193. if z.shape[0] < 2 or z.shape[1] < 2:
  1194. raise TypeError(f"Input z must be at least a (2, 2) shaped array, "
  1195. f"but has shape {z.shape}")
  1196. Ny, Nx = z.shape
  1197. if x.ndim != y.ndim:
  1198. raise TypeError(f"Number of dimensions of x ({x.ndim}) and y "
  1199. f"({y.ndim}) do not match")
  1200. if x.ndim == 1:
  1201. nx, = x.shape
  1202. ny, = y.shape
  1203. if nx != Nx:
  1204. raise TypeError(f"Length of x ({nx}) must match number of "
  1205. f"columns in z ({Nx})")
  1206. if ny != Ny:
  1207. raise TypeError(f"Length of y ({ny}) must match number of "
  1208. f"rows in z ({Ny})")
  1209. x, y = np.meshgrid(x, y)
  1210. elif x.ndim == 2:
  1211. if x.shape != z.shape:
  1212. raise TypeError(
  1213. f"Shapes of x {x.shape} and z {z.shape} do not match")
  1214. if y.shape != z.shape:
  1215. raise TypeError(
  1216. f"Shapes of y {y.shape} and z {z.shape} do not match")
  1217. else:
  1218. raise TypeError(f"Inputs x and y must be 1D or 2D, not {x.ndim}D")
  1219. return x, y, z
  1220. def _initialize_x_y(self, z):
  1221. """
  1222. Return X, Y arrays such that contour(Z) will match imshow(Z)
  1223. if origin is not None.
  1224. The center of pixel Z[i, j] depends on origin:
  1225. if origin is None, x = j, y = i;
  1226. if origin is 'lower', x = j + 0.5, y = i + 0.5;
  1227. if origin is 'upper', x = j + 0.5, y = Nrows - i - 0.5
  1228. If extent is not None, x and y will be scaled to match,
  1229. as in imshow.
  1230. If origin is None and extent is not None, then extent
  1231. will give the minimum and maximum values of x and y.
  1232. """
  1233. if z.ndim != 2:
  1234. raise TypeError(f"Input z must be 2D, not {z.ndim}D")
  1235. elif z.shape[0] < 2 or z.shape[1] < 2:
  1236. raise TypeError(f"Input z must be at least a (2, 2) shaped array, "
  1237. f"but has shape {z.shape}")
  1238. else:
  1239. Ny, Nx = z.shape
  1240. if self.origin is None: # Not for image-matching.
  1241. if self.extent is None:
  1242. return np.meshgrid(np.arange(Nx), np.arange(Ny))
  1243. else:
  1244. x0, x1, y0, y1 = self.extent
  1245. x = np.linspace(x0, x1, Nx)
  1246. y = np.linspace(y0, y1, Ny)
  1247. return np.meshgrid(x, y)
  1248. # Match image behavior:
  1249. if self.extent is None:
  1250. x0, x1, y0, y1 = (0, Nx, 0, Ny)
  1251. else:
  1252. x0, x1, y0, y1 = self.extent
  1253. dx = (x1 - x0) / Nx
  1254. dy = (y1 - y0) / Ny
  1255. x = x0 + (np.arange(Nx) + 0.5) * dx
  1256. y = y0 + (np.arange(Ny) + 0.5) * dy
  1257. if self.origin == 'upper':
  1258. y = y[::-1]
  1259. return np.meshgrid(x, y)
  1260. _docstring.interpd.register(contour_doc="""
  1261. `.contour` and `.contourf` draw contour lines and filled contours,
  1262. respectively. Except as noted, function signatures and return values
  1263. are the same for both versions.
  1264. Parameters
  1265. ----------
  1266. X, Y : array-like, optional
  1267. The coordinates of the values in *Z*.
  1268. *X* and *Y* must both be 2D with the same shape as *Z* (e.g.
  1269. created via `numpy.meshgrid`), or they must both be 1-D such
  1270. that ``len(X) == N`` is the number of columns in *Z* and
  1271. ``len(Y) == M`` is the number of rows in *Z*.
  1272. *X* and *Y* must both be ordered monotonically.
  1273. If not given, they are assumed to be integer indices, i.e.
  1274. ``X = range(N)``, ``Y = range(M)``.
  1275. Z : (M, N) array-like
  1276. The height values over which the contour is drawn. Color-mapping is
  1277. controlled by *cmap*, *norm*, *vmin*, and *vmax*.
  1278. levels : int or array-like, optional
  1279. Determines the number and positions of the contour lines / regions.
  1280. If an int *n*, use `~matplotlib.ticker.MaxNLocator`, which tries
  1281. to automatically choose no more than *n+1* "nice" contour levels
  1282. between minimum and maximum numeric values of *Z*.
  1283. If array-like, draw contour lines at the specified levels.
  1284. The values must be in increasing order.
  1285. Returns
  1286. -------
  1287. `~.contour.QuadContourSet`
  1288. Other Parameters
  1289. ----------------
  1290. corner_mask : bool, default: :rc:`contour.corner_mask`
  1291. Enable/disable corner masking, which only has an effect if *Z* is
  1292. a masked array. If ``False``, any quad touching a masked point is
  1293. masked out. If ``True``, only the triangular corners of quads
  1294. nearest those points are always masked out, other triangular
  1295. corners comprising three unmasked points are contoured as usual.
  1296. colors : :mpltype:`color` or list of :mpltype:`color`, optional
  1297. The colors of the levels, i.e. the lines for `.contour` and the
  1298. areas for `.contourf`.
  1299. The sequence is cycled for the levels in ascending order. If the
  1300. sequence is shorter than the number of levels, it's repeated.
  1301. As a shortcut, a single color may be used in place of one-element lists, i.e.
  1302. ``'red'`` instead of ``['red']`` to color all levels with the same color.
  1303. .. versionchanged:: 3.10
  1304. Previously a single color had to be expressed as a string, but now any
  1305. valid color format may be passed.
  1306. By default (value *None*), the colormap specified by *cmap*
  1307. will be used.
  1308. alpha : float, default: 1
  1309. The alpha blending value, between 0 (transparent) and 1 (opaque).
  1310. %(cmap_doc)s
  1311. This parameter is ignored if *colors* is set.
  1312. %(norm_doc)s
  1313. This parameter is ignored if *colors* is set.
  1314. %(vmin_vmax_doc)s
  1315. If *vmin* or *vmax* are not given, the default color scaling is based on
  1316. *levels*.
  1317. This parameter is ignored if *colors* is set.
  1318. %(colorizer_doc)s
  1319. This parameter is ignored if *colors* is set.
  1320. origin : {*None*, 'upper', 'lower', 'image'}, default: None
  1321. Determines the orientation and exact position of *Z* by specifying
  1322. the position of ``Z[0, 0]``. This is only relevant, if *X*, *Y*
  1323. are not given.
  1324. - *None*: ``Z[0, 0]`` is at X=0, Y=0 in the lower left corner.
  1325. - 'lower': ``Z[0, 0]`` is at X=0.5, Y=0.5 in the lower left corner.
  1326. - 'upper': ``Z[0, 0]`` is at X=N+0.5, Y=0.5 in the upper left
  1327. corner.
  1328. - 'image': Use the value from :rc:`image.origin`.
  1329. extent : (x0, x1, y0, y1), optional
  1330. If *origin* is not *None*, then *extent* is interpreted as in
  1331. `.imshow`: it gives the outer pixel boundaries. In this case, the
  1332. position of Z[0, 0] is the center of the pixel, not a corner. If
  1333. *origin* is *None*, then (*x0*, *y0*) is the position of Z[0, 0],
  1334. and (*x1*, *y1*) is the position of Z[-1, -1].
  1335. This argument is ignored if *X* and *Y* are specified in the call
  1336. to contour.
  1337. locator : ticker.Locator subclass, optional
  1338. The locator is used to determine the contour levels if they
  1339. are not given explicitly via *levels*.
  1340. Defaults to `~.ticker.MaxNLocator`.
  1341. extend : {'neither', 'both', 'min', 'max'}, default: 'neither'
  1342. Determines the ``contourf``-coloring of values that are outside the
  1343. *levels* range.
  1344. If 'neither', values outside the *levels* range are not colored.
  1345. If 'min', 'max' or 'both', color the values below, above or below
  1346. and above the *levels* range.
  1347. Values below ``min(levels)`` and above ``max(levels)`` are mapped
  1348. to the under/over values of the `.Colormap`. Note that most
  1349. colormaps do not have dedicated colors for these by default, so
  1350. that the over and under values are the edge values of the colormap.
  1351. You may want to set these values explicitly using
  1352. `.Colormap.set_under` and `.Colormap.set_over`.
  1353. .. note::
  1354. An existing `.QuadContourSet` does not get notified if
  1355. properties of its colormap are changed. Therefore, an explicit
  1356. call `~.ContourSet.changed()` is needed after modifying the
  1357. colormap. The explicit call can be left out, if a colorbar is
  1358. assigned to the `.QuadContourSet` because it internally calls
  1359. `~.ContourSet.changed()`.
  1360. Example::
  1361. x = np.arange(1, 10)
  1362. y = x.reshape(-1, 1)
  1363. h = x * y
  1364. cs = plt.contourf(h, levels=[10, 30, 50],
  1365. colors=['#808080', '#A0A0A0', '#C0C0C0'], extend='both')
  1366. cs.cmap.set_over('red')
  1367. cs.cmap.set_under('blue')
  1368. cs.changed()
  1369. xunits, yunits : registered units, optional
  1370. Override axis units by specifying an instance of a
  1371. :class:`matplotlib.units.ConversionInterface`.
  1372. antialiased : bool, optional
  1373. Enable antialiasing, overriding the defaults. For
  1374. filled contours, the default is *False*. For line contours,
  1375. it is taken from :rc:`lines.antialiased`.
  1376. nchunk : int >= 0, optional
  1377. If 0, no subdivision of the domain. Specify a positive integer to
  1378. divide the domain into subdomains of *nchunk* by *nchunk* quads.
  1379. Chunking reduces the maximum length of polygons generated by the
  1380. contouring algorithm which reduces the rendering workload passed
  1381. on to the backend and also requires slightly less RAM. It can
  1382. however introduce rendering artifacts at chunk boundaries depending
  1383. on the backend, the *antialiased* flag and value of *alpha*.
  1384. linewidths : float or array-like, default: :rc:`contour.linewidth`
  1385. *Only applies to* `.contour`.
  1386. The line width of the contour lines.
  1387. If a number, all levels will be plotted with this linewidth.
  1388. If a sequence, the levels in ascending order will be plotted with
  1389. the linewidths in the order specified.
  1390. If None, this falls back to :rc:`lines.linewidth`.
  1391. linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional
  1392. *Only applies to* `.contour`.
  1393. If *linestyles* is *None*, the default is 'solid' unless the lines are
  1394. monochrome. In that case, negative contours will instead take their
  1395. linestyle from the *negative_linestyles* argument.
  1396. *linestyles* can also be an iterable of the above strings specifying a set
  1397. of linestyles to be used. If this iterable is shorter than the number of
  1398. contour levels it will be repeated as necessary.
  1399. negative_linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, \
  1400. optional
  1401. *Only applies to* `.contour`.
  1402. If *linestyles* is *None* and the lines are monochrome, this argument
  1403. specifies the line style for negative contours.
  1404. If *negative_linestyles* is *None*, the default is taken from
  1405. :rc:`contour.negative_linestyle`.
  1406. *negative_linestyles* can also be an iterable of the above strings
  1407. specifying a set of linestyles to be used. If this iterable is shorter than
  1408. the number of contour levels it will be repeated as necessary.
  1409. hatches : list[str], optional
  1410. *Only applies to* `.contourf`.
  1411. A list of cross hatch patterns to use on the filled areas.
  1412. If None, no hatching will be added to the contour.
  1413. algorithm : {'mpl2005', 'mpl2014', 'serial', 'threaded'}, optional
  1414. Which contouring algorithm to use to calculate the contour lines and
  1415. polygons. The algorithms are implemented in
  1416. `ContourPy <https://github.com/contourpy/contourpy>`_, consult the
  1417. `ContourPy documentation <https://contourpy.readthedocs.io>`_ for
  1418. further information.
  1419. The default is taken from :rc:`contour.algorithm`.
  1420. clip_path : `~matplotlib.patches.Patch` or `.Path` or `.TransformedPath`
  1421. Set the clip path. See `~matplotlib.artist.Artist.set_clip_path`.
  1422. .. versionadded:: 3.8
  1423. data : indexable object, optional
  1424. DATA_PARAMETER_PLACEHOLDER
  1425. Notes
  1426. -----
  1427. 1. `.contourf` differs from the MATLAB version in that it does not draw
  1428. the polygon edges. To draw edges, add line contours with calls to
  1429. `.contour`.
  1430. 2. `.contourf` fills intervals that are closed at the top; that is, for
  1431. boundaries *z1* and *z2*, the filled region is::
  1432. z1 < Z <= z2
  1433. except for the lowest interval, which is closed on both sides (i.e.
  1434. it includes the lowest value).
  1435. 3. `.contour` and `.contourf` use a `marching squares
  1436. <https://en.wikipedia.org/wiki/Marching_squares>`_ algorithm to
  1437. compute contour locations. More information can be found in
  1438. `ContourPy documentation <https://contourpy.readthedocs.io>`_.
  1439. """ % _docstring.interpd.params)