Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/matplotlib/contour.py : 9%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2These are classes to support contour plotting and labelling for the Axes class.
3"""
5from numbers import Integral
7import numpy as np
8from numpy import ma
10import matplotlib as mpl
11import matplotlib.path as mpath
12import matplotlib.ticker as ticker
13import matplotlib.cm as cm
14import matplotlib.colors as mcolors
15import matplotlib.collections as mcoll
16import matplotlib.font_manager as font_manager
17import matplotlib.text as text
18import matplotlib.cbook as cbook
19import matplotlib.mathtext as mathtext
20import matplotlib.patches as mpatches
21import matplotlib.texmanager as texmanager
22import matplotlib.transforms as mtransforms
24# Import needed for adding manual selection capability to clabel
25from matplotlib.blocking_input import BlockingContourLabeler
27# We can't use a single line collection for contour because a line
28# collection can have only a single line style, and we want to be able to have
29# dashed negative contours, for example, and solid positive contours.
30# We could use a single polygon collection for filled contours, but it
31# seems better to keep line and filled contours similar, with one collection
32# per level.
35class ClabelText(text.Text):
36 """
37 Unlike the ordinary text, the get_rotation returns an updated
38 angle in the pixel coordinate assuming that the input rotation is
39 an angle in data coordinate (or whatever transform set).
40 """
42 def get_rotation(self):
43 new_angle, = self.get_transform().transform_angles(
44 [text.Text.get_rotation(self)], [self.get_position()])
45 return new_angle
48class ContourLabeler:
49 """Mixin to provide labelling capability to `.ContourSet`."""
51 def clabel(self, levels=None, *,
52 fontsize=None, inline=True, inline_spacing=5, fmt='%1.3f',
53 colors=None, use_clabeltext=False, manual=False,
54 rightside_up=True):
55 """
56 Label a contour plot.
58 Adds labels to line contours in this `.ContourSet` (which inherits from
59 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.
67 fontsize : str or float, optional
68 Size in points or relative size e.g., 'smaller', 'x-large'.
69 See `.Text.set_size` for accepted string values.
71 colors : color-spec, optional
72 The label colors:
74 - If *None*, the color of each label matches the color of
75 the corresponding contour.
77 - If one string color, e.g., *colors* = 'r' or *colors* =
78 'red', all labels will be plotted in this color.
80 - If a tuple of matplotlib color args (string, float, rgb, etc),
81 different labels will be plotted in different colors in the order
82 specified.
84 inline : bool, optional
85 If ``True`` the underlying contour is removed where the label is
86 placed. Default is ``True``.
88 inline_spacing : float, optional
89 Space in pixels to leave on each side of label when
90 placing inline. Defaults to 5.
92 This spacing will be exact for labels at locations where the
93 contour is straight, less so for labels on curved contours.
95 fmt : str or dict, optional
96 A format string for the label. Default is '%1.3f'
98 Alternatively, this can be a dictionary matching contour levels
99 with arbitrary strings to use for each contour level (i.e.,
100 fmt[level]=string), or it can be any callable, such as a
101 `.Formatter` instance, that returns a string when called with a
102 numeric contour level.
104 manual : bool or iterable, optional
105 If ``True``, contour labels will be placed manually using
106 mouse clicks. Click the first button near a contour to
107 add a label, click the second button (or potentially both
108 mouse buttons at once) to finish adding labels. The third
109 button can be used to remove the last label added, but
110 only if labels are not inline. Alternatively, the keyboard
111 can be used to select label locations (enter to end label
112 placement, delete or backspace act like the third mouse button,
113 and any other key will select a label location).
115 *manual* can also be an iterable object of (x, y) tuples.
116 Contour labels will be created as if mouse is clicked at each
117 (x, y) position.
119 rightside_up : bool, optional
120 If ``True``, label rotations will always be plus
121 or minus 90 degrees from level. Default is ``True``.
123 use_clabeltext : bool, optional
124 If ``True``, `.ClabelText` class (instead of `.Text`) is used to
125 create labels. `ClabelText` recalculates rotation angles
126 of texts during the drawing time, therefore this can be used if
127 aspect of the axes changes. Default is ``False``.
129 Returns
130 -------
131 labels
132 A list of `.Text` instances for the labels.
133 """
135 # clabel basically takes the input arguments and uses them to
136 # add a list of "label specific" attributes to the ContourSet
137 # object. These attributes are all of the form label* and names
138 # should be fairly self explanatory.
139 #
140 # Once these attributes are set, clabel passes control to the
141 # labels method (case of automatic label placement) or
142 # `BlockingContourLabeler` (case of manual label placement).
144 self.labelFmt = fmt
145 self._use_clabeltext = use_clabeltext
146 # Detect if manual selection is desired and remove from argument list.
147 self.labelManual = manual
148 self.rightside_up = rightside_up
150 if levels is None:
151 levels = self.levels
152 indices = list(range(len(self.cvalues)))
153 else:
154 levlabs = list(levels)
155 indices, levels = [], []
156 for i, lev in enumerate(self.levels):
157 if lev in levlabs:
158 indices.append(i)
159 levels.append(lev)
160 if len(levels) < len(levlabs):
161 raise ValueError(f"Specified levels {levlabs} don't match "
162 f"available levels {self.levels}")
163 self.labelLevelList = levels
164 self.labelIndiceList = indices
166 self.labelFontProps = font_manager.FontProperties()
167 self.labelFontProps.set_size(fontsize)
168 font_size_pts = self.labelFontProps.get_size_in_points()
169 self.labelFontSizeList = [font_size_pts] * len(levels)
171 if colors is None:
172 self.labelMappable = self
173 self.labelCValueList = np.take(self.cvalues, self.labelIndiceList)
174 else:
175 cmap = mcolors.ListedColormap(colors, N=len(self.labelLevelList))
176 self.labelCValueList = list(range(len(self.labelLevelList)))
177 self.labelMappable = cm.ScalarMappable(cmap=cmap,
178 norm=mcolors.NoNorm())
180 self.labelXYs = []
182 if np.iterable(self.labelManual):
183 for x, y in self.labelManual:
184 self.add_label_near(x, y, inline, inline_spacing)
185 elif self.labelManual:
186 print('Select label locations manually using first mouse button.')
187 print('End manual selection with second mouse button.')
188 if not inline:
189 print('Remove last label by clicking third mouse button.')
190 blocking_contour_labeler = BlockingContourLabeler(self)
191 blocking_contour_labeler(inline, inline_spacing)
192 else:
193 self.labels(inline, inline_spacing)
195 self.labelTextsList = cbook.silent_list('text.Text', self.labelTexts)
196 return self.labelTextsList
198 def print_label(self, linecontour, labelwidth):
199 "Return *False* if contours are too short for a label."
200 return (len(linecontour) > 10 * labelwidth
201 or (np.ptp(linecontour, axis=0) > 1.2 * labelwidth).any())
203 def too_close(self, x, y, lw):
204 "Return *True* if a label is already near this location."
205 thresh = (1.2 * lw) ** 2
206 return any((x - loc[0]) ** 2 + (y - loc[1]) ** 2 < thresh
207 for loc in self.labelXYs)
209 def get_label_coords(self, distances, XX, YY, ysize, lw):
210 """
211 Return x, y, and the index of a label location.
213 Labels are plotted at a location with the smallest
214 deviation of the contour from a straight line
215 unless there is another label nearby, in which case
216 the next best place on the contour is picked up.
217 If all such candidates are rejected, the beginning
218 of the contour is chosen.
219 """
220 hysize = int(ysize / 2)
221 adist = np.argsort(distances)
223 for ind in adist:
224 x, y = XX[ind][hysize], YY[ind][hysize]
225 if self.too_close(x, y, lw):
226 continue
227 return x, y, ind
229 ind = adist[0]
230 x, y = XX[ind][hysize], YY[ind][hysize]
231 return x, y, ind
233 def get_label_width(self, lev, fmt, fsize):
234 """
235 Return the width of the label in points.
236 """
237 if not isinstance(lev, str):
238 lev = self.get_text(lev, fmt)
239 lev, ismath = text.Text()._preprocess_math(lev)
240 if ismath == 'TeX':
241 lw, _, _ = (texmanager.TexManager()
242 .get_text_width_height_descent(lev, fsize))
243 elif ismath:
244 if not hasattr(self, '_mathtext_parser'):
245 self._mathtext_parser = mathtext.MathTextParser('bitmap')
246 img, _ = self._mathtext_parser.parse(lev, dpi=72,
247 prop=self.labelFontProps)
248 _, lw = np.shape(img) # at dpi=72, the units are PostScript points
249 else:
250 # width is much less than "font size"
251 lw = len(lev) * fsize * 0.6
252 return lw
254 def set_label_props(self, label, text, color):
255 """Set the label properties - color, fontsize, text."""
256 label.set_text(text)
257 label.set_color(color)
258 label.set_fontproperties(self.labelFontProps)
259 label.set_clip_box(self.ax.bbox)
261 def get_text(self, lev, fmt):
262 """Get the text of the label."""
263 if isinstance(lev, str):
264 return lev
265 else:
266 if isinstance(fmt, dict):
267 return fmt.get(lev, '%1.3f')
268 elif callable(fmt):
269 return fmt(lev)
270 else:
271 return fmt % lev
273 def locate_label(self, linecontour, labelwidth):
274 """
275 Find good place to draw a label (relatively flat part of the contour).
276 """
278 # Number of contour points
279 nsize = len(linecontour)
280 if labelwidth > 1:
281 xsize = int(np.ceil(nsize / labelwidth))
282 else:
283 xsize = 1
284 if xsize == 1:
285 ysize = nsize
286 else:
287 ysize = int(labelwidth)
289 XX = np.resize(linecontour[:, 0], (xsize, ysize))
290 YY = np.resize(linecontour[:, 1], (xsize, ysize))
291 # I might have fouled up the following:
292 yfirst = YY[:, :1]
293 ylast = YY[:, -1:]
294 xfirst = XX[:, :1]
295 xlast = XX[:, -1:]
296 s = (yfirst - YY) * (xlast - xfirst) - (xfirst - XX) * (ylast - yfirst)
297 L = np.hypot(xlast - xfirst, ylast - yfirst)
298 # Ignore warning that divide by zero throws, as this is a valid option
299 with np.errstate(divide='ignore', invalid='ignore'):
300 dist = np.sum(np.abs(s) / L, axis=-1)
301 x, y, ind = self.get_label_coords(dist, XX, YY, ysize, labelwidth)
303 # There must be a more efficient way...
304 lc = [tuple(l) for l in linecontour]
305 dind = lc.index((x, y))
307 return x, y, dind
309 def calc_label_rot_and_inline(self, slc, ind, lw, lc=None, spacing=5):
310 """
311 This function calculates the appropriate label rotation given
312 the linecontour coordinates in screen units, the index of the
313 label location and the label width.
315 It will also break contour and calculate inlining if *lc* is
316 not empty (lc defaults to the empty list if None). *spacing*
317 is the space around the label in pixels to leave empty.
319 Do both of these tasks at once to avoid calculating path lengths
320 multiple times, which is relatively costly.
322 The method used here involves calculating the path length
323 along the contour in pixel coordinates and then looking
324 approximately label width / 2 away from central point to
325 determine rotation and then to break contour if desired.
326 """
328 if lc is None:
329 lc = []
330 # Half the label width
331 hlw = lw / 2.0
333 # Check if closed and, if so, rotate contour so label is at edge
334 closed = _is_closed_polygon(slc)
335 if closed:
336 slc = np.r_[slc[ind:-1], slc[:ind + 1]]
338 if len(lc): # Rotate lc also if not empty
339 lc = np.r_[lc[ind:-1], lc[:ind + 1]]
341 ind = 0
343 # Calculate path lengths
344 pl = np.zeros(slc.shape[0], dtype=float)
345 dx = np.diff(slc, axis=0)
346 pl[1:] = np.cumsum(np.hypot(dx[:, 0], dx[:, 1]))
347 pl = pl - pl[ind]
349 # Use linear interpolation to get points around label
350 xi = np.array([-hlw, hlw])
351 if closed: # Look at end also for closed contours
352 dp = np.array([pl[-1], 0])
353 else:
354 dp = np.zeros_like(xi)
356 # Get angle of vector between the two ends of the label - must be
357 # calculated in pixel space for text rotation to work correctly.
358 (dx,), (dy,) = (np.diff(np.interp(dp + xi, pl, slc_col))
359 for slc_col in slc.T)
360 rotation = np.rad2deg(np.arctan2(dy, dx))
362 if self.rightside_up:
363 # Fix angle so text is never upside-down
364 rotation = (rotation + 90) % 180 - 90
366 # Break contour if desired
367 nlc = []
368 if len(lc):
369 # Expand range by spacing
370 xi = dp + xi + np.array([-spacing, spacing])
372 # Get (integer) indices near points of interest; use -1 as marker
373 # for out of bounds.
374 I = np.interp(xi, pl, np.arange(len(pl)), left=-1, right=-1)
375 I = [np.floor(I[0]).astype(int), np.ceil(I[1]).astype(int)]
376 if I[0] != -1:
377 xy1 = [np.interp(xi[0], pl, lc_col) for lc_col in lc.T]
378 if I[1] != -1:
379 xy2 = [np.interp(xi[1], pl, lc_col) for lc_col in lc.T]
381 # Actually break contours
382 if closed:
383 # This will remove contour if shorter than label
384 if all(i != -1 for i in I):
385 nlc.append(np.row_stack([xy2, lc[I[1]:I[0]+1], xy1]))
386 else:
387 # These will remove pieces of contour if they have length zero
388 if I[0] != -1:
389 nlc.append(np.row_stack([lc[:I[0]+1], xy1]))
390 if I[1] != -1:
391 nlc.append(np.row_stack([xy2, lc[I[1]:]]))
393 # The current implementation removes contours completely
394 # covered by labels. Uncomment line below to keep
395 # original contour if this is the preferred behavior.
396 # if not len(nlc): nlc = [ lc ]
398 return rotation, nlc
400 def _get_label_text(self, x, y, rotation):
401 dx, dy = self.ax.transData.inverted().transform((x, y))
402 t = text.Text(dx, dy, rotation=rotation,
403 horizontalalignment='center',
404 verticalalignment='center')
405 return t
407 def _get_label_clabeltext(self, x, y, rotation):
408 # x, y, rotation is given in pixel coordinate. Convert them to
409 # the data coordinate and create a label using ClabelText
410 # class. This way, the rotation of the clabel is along the
411 # contour line always.
412 transDataInv = self.ax.transData.inverted()
413 dx, dy = transDataInv.transform((x, y))
414 drotation = transDataInv.transform_angles(np.array([rotation]),
415 np.array([[x, y]]))
416 t = ClabelText(dx, dy, rotation=drotation[0],
417 horizontalalignment='center',
418 verticalalignment='center')
420 return t
422 def _add_label(self, t, x, y, lev, cvalue):
423 color = self.labelMappable.to_rgba(cvalue, alpha=self.alpha)
425 _text = self.get_text(lev, self.labelFmt)
426 self.set_label_props(t, _text, color)
427 self.labelTexts.append(t)
428 self.labelCValues.append(cvalue)
429 self.labelXYs.append((x, y))
431 # Add label to plot here - useful for manual mode label selection
432 self.ax.add_artist(t)
434 def add_label(self, x, y, rotation, lev, cvalue):
435 """
436 Add contour label using :class:`~matplotlib.text.Text` class.
437 """
438 t = self._get_label_text(x, y, rotation)
439 self._add_label(t, x, y, lev, cvalue)
441 def add_label_clabeltext(self, x, y, rotation, lev, cvalue):
442 """
443 Add contour label using :class:`ClabelText` class.
444 """
445 # x, y, rotation is given in pixel coordinate. Convert them to
446 # the data coordinate and create a label using ClabelText
447 # class. This way, the rotation of the clabel is along the
448 # contour line always.
449 t = self._get_label_clabeltext(x, y, rotation)
450 self._add_label(t, x, y, lev, cvalue)
452 def add_label_near(self, x, y, inline=True, inline_spacing=5,
453 transform=None):
454 """
455 Add a label near the point (x, y). If transform is None
456 (default), (x, y) is in data coordinates; if transform is
457 False, (x, y) is in display coordinates; otherwise, the
458 specified transform will be used to translate (x, y) into
459 display coordinates.
461 Parameters
462 ----------
463 x, y : float
464 The approximate location of the label.
466 inline : bool, optional, default: True
467 If *True* remove the segment of the contour beneath the label.
469 inline_spacing : int, optional, default: 5
470 Space in pixels to leave on each side of label when placing
471 inline. This spacing will be exact for labels at locations where
472 the contour is straight, less so for labels on curved contours.
473 """
475 if transform is None:
476 transform = self.ax.transData
478 if transform:
479 x, y = transform.transform((x, y))
481 # find the nearest contour _in screen units_
482 conmin, segmin, imin, xmin, ymin = self.find_nearest_contour(
483 x, y, self.labelIndiceList)[:5]
485 # The calc_label_rot_and_inline routine requires that (xmin, ymin)
486 # be a vertex in the path. So, if it isn't, add a vertex here
488 # grab the paths from the collections
489 paths = self.collections[conmin].get_paths()
490 # grab the correct segment
491 active_path = paths[segmin]
492 # grab its vertices
493 lc = active_path.vertices
494 # sort out where the new vertex should be added data-units
495 xcmin = self.ax.transData.inverted().transform([xmin, ymin])
496 # if there isn't a vertex close enough
497 if not np.allclose(xcmin, lc[imin]):
498 # insert new data into the vertex list
499 lc = np.r_[lc[:imin], np.array(xcmin)[None, :], lc[imin:]]
500 # replace the path with the new one
501 paths[segmin] = mpath.Path(lc)
503 # Get index of nearest level in subset of levels used for labeling
504 lmin = self.labelIndiceList.index(conmin)
506 # Coordinates of contour
507 paths = self.collections[conmin].get_paths()
508 lc = paths[segmin].vertices
510 # In pixel/screen space
511 slc = self.ax.transData.transform(lc)
513 # Get label width for rotating labels and breaking contours
514 lw = self.get_label_width(self.labelLevelList[lmin],
515 self.labelFmt, self.labelFontSizeList[lmin])
516 # lw is in points.
517 lw *= self.ax.figure.dpi / 72.0 # scale to screen coordinates
518 # now lw in pixels
520 # Figure out label rotation.
521 if inline:
522 lcarg = lc
523 else:
524 lcarg = None
525 rotation, nlc = self.calc_label_rot_and_inline(
526 slc, imin, lw, lcarg,
527 inline_spacing)
529 self.add_label(xmin, ymin, rotation, self.labelLevelList[lmin],
530 self.labelCValueList[lmin])
532 if inline:
533 # Remove old, not looping over paths so we can do this up front
534 paths.pop(segmin)
536 # Add paths if not empty or single point
537 for n in nlc:
538 if len(n) > 1:
539 paths.append(mpath.Path(n))
541 def pop_label(self, index=-1):
542 """Defaults to removing last label, but any index can be supplied"""
543 self.labelCValues.pop(index)
544 t = self.labelTexts.pop(index)
545 t.remove()
547 def labels(self, inline, inline_spacing):
549 if self._use_clabeltext:
550 add_label = self.add_label_clabeltext
551 else:
552 add_label = self.add_label
554 for icon, lev, fsize, cvalue in zip(
555 self.labelIndiceList, self.labelLevelList,
556 self.labelFontSizeList, self.labelCValueList):
558 con = self.collections[icon]
559 trans = con.get_transform()
560 lw = self.get_label_width(lev, self.labelFmt, fsize)
561 lw *= self.ax.figure.dpi / 72.0 # scale to screen coordinates
562 additions = []
563 paths = con.get_paths()
564 for segNum, linepath in enumerate(paths):
565 lc = linepath.vertices # Line contour
566 slc0 = trans.transform(lc) # Line contour in screen coords
568 # For closed polygons, add extra point to avoid division by
569 # zero in print_label and locate_label. Other than these
570 # functions, this is not necessary and should probably be
571 # eventually removed.
572 if _is_closed_polygon(lc):
573 slc = np.r_[slc0, slc0[1:2, :]]
574 else:
575 slc = slc0
577 # Check if long enough for a label
578 if self.print_label(slc, lw):
579 x, y, ind = self.locate_label(slc, lw)
581 if inline:
582 lcarg = lc
583 else:
584 lcarg = None
585 rotation, new = self.calc_label_rot_and_inline(
586 slc0, ind, lw, lcarg,
587 inline_spacing)
589 # Actually add the label
590 add_label(x, y, rotation, lev, cvalue)
592 # If inline, add new contours
593 if inline:
594 for n in new:
595 # Add path if not empty or single point
596 if len(n) > 1:
597 additions.append(mpath.Path(n))
598 else: # If not adding label, keep old path
599 additions.append(linepath)
601 # After looping over all segments on a contour, replace old paths
602 # by new ones if inlining.
603 if inline:
604 paths[:] = additions
607def _find_closest_point_on_leg(p1, p2, p0):
608 """Find the closest point to p0 on line segment connecting p1 and p2."""
610 # handle degenerate case
611 if np.all(p2 == p1):
612 d = np.sum((p0 - p1)**2)
613 return d, p1
615 d21 = p2 - p1
616 d01 = p0 - p1
618 # project on to line segment to find closest point
619 proj = np.dot(d01, d21) / np.dot(d21, d21)
620 if proj < 0:
621 proj = 0
622 if proj > 1:
623 proj = 1
624 pc = p1 + proj * d21
626 # find squared distance
627 d = np.sum((pc-p0)**2)
629 return d, pc
632def _is_closed_polygon(X):
633 """
634 Return whether first and last object in a sequence are the same. These are
635 presumably coordinates on a polygonal curve, in which case this function
636 tests if that curve is closed.
637 """
638 return np.all(X[0] == X[-1])
641def _find_closest_point_on_path(lc, point):
642 """
643 Parameters
644 ----------
645 lc : coordinates of vertices
646 point : coordinates of test point
647 """
649 # find index of closest vertex for this segment
650 ds = np.sum((lc - point[None, :])**2, 1)
651 imin = np.argmin(ds)
653 dmin = np.inf
654 xcmin = None
655 legmin = (None, None)
657 closed = _is_closed_polygon(lc)
659 # build list of legs before and after this vertex
660 legs = []
661 if imin > 0 or closed:
662 legs.append(((imin-1) % len(lc), imin))
663 if imin < len(lc) - 1 or closed:
664 legs.append((imin, (imin+1) % len(lc)))
666 for leg in legs:
667 d, xc = _find_closest_point_on_leg(lc[leg[0]], lc[leg[1]], point)
668 if d < dmin:
669 dmin = d
670 xcmin = xc
671 legmin = leg
673 return (dmin, xcmin, legmin)
676class ContourSet(cm.ScalarMappable, ContourLabeler):
677 """
678 Store a set of contour lines or filled regions.
680 User-callable method: `~.axes.Axes.clabel`
682 Parameters
683 ----------
684 ax : `~.axes.Axes`
686 levels : [level0, level1, ..., leveln]
687 A list of floating point numbers indicating the contour
688 levels.
690 allsegs : [level0segs, level1segs, ...]
691 List of all the polygon segments for all the *levels*.
692 For contour lines ``len(allsegs) == len(levels)``, and for
693 filled contour regions ``len(allsegs) = len(levels)-1``. The lists
694 should look like ::
696 level0segs = [polygon0, polygon1, ...]
697 polygon0 = [[x0, y0], [x1, y1], ...]
699 allkinds : ``None`` or [level0kinds, level1kinds, ...]
700 Optional list of all the polygon vertex kinds (code types), as
701 described and used in Path. This is used to allow multiply-
702 connected paths such as holes within filled polygons.
703 If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
704 should look like ::
706 level0kinds = [polygon0kinds, ...]
707 polygon0kinds = [vertexcode0, vertexcode1, ...]
709 If *allkinds* is not ``None``, usually all polygons for a
710 particular contour level are grouped together so that
711 ``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
713 **kwargs
714 Keyword arguments are as described in the docstring of
715 `~.axes.Axes.contour`.
717 Attributes
718 ----------
719 ax
720 The axes object in which the contours are drawn.
722 collections
723 A silent_list of LineCollections or PolyCollections.
725 levels
726 Contour levels.
728 layers
729 Same as levels for line contours; half-way between
730 levels for filled contours. See :meth:`_process_colors`.
731 """
733 def __init__(self, ax, *args,
734 levels=None, filled=False, linewidths=None, linestyles=None,
735 alpha=None, origin=None, extent=None,
736 cmap=None, colors=None, norm=None, vmin=None, vmax=None,
737 extend='neither', antialiased=None,
738 **kwargs):
739 """
740 Draw contour lines or filled regions, depending on
741 whether keyword arg *filled* is ``False`` (default) or ``True``.
743 Call signature::
745 ContourSet(ax, levels, allsegs, [allkinds], **kwargs)
747 Parameters
748 ----------
749 ax : `~.axes.Axes`
750 The `~.axes.Axes` object to draw on.
752 levels : [level0, level1, ..., leveln]
753 A list of floating point numbers indicating the contour
754 levels.
756 allsegs : [level0segs, level1segs, ...]
757 List of all the polygon segments for all the *levels*.
758 For contour lines ``len(allsegs) == len(levels)``, and for
759 filled contour regions ``len(allsegs) = len(levels)-1``. The lists
760 should look like ::
762 level0segs = [polygon0, polygon1, ...]
763 polygon0 = [[x0, y0], [x1, y1], ...]
765 allkinds : [level0kinds, level1kinds, ...], optional
766 Optional list of all the polygon vertex kinds (code types), as
767 described and used in Path. This is used to allow multiply-
768 connected paths such as holes within filled polygons.
769 If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
770 should look like ::
772 level0kinds = [polygon0kinds, ...]
773 polygon0kinds = [vertexcode0, vertexcode1, ...]
775 If *allkinds* is not ``None``, usually all polygons for a
776 particular contour level are grouped together so that
777 ``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
779 **kwargs
780 Keyword arguments are as described in the docstring of
781 `~axes.Axes.contour`.
782 """
783 self.ax = ax
784 self.levels = levels
785 self.filled = filled
786 self.linewidths = linewidths
787 self.linestyles = linestyles
788 self.hatches = kwargs.pop('hatches', [None])
789 self.alpha = alpha
790 self.origin = origin
791 self.extent = extent
792 self.colors = colors
793 self.extend = extend
794 self.antialiased = antialiased
795 if self.antialiased is None and self.filled:
796 # Eliminate artifacts; we are not stroking the boundaries.
797 self.antialiased = False
798 # The default for line contours will be taken from the
799 # LineCollection default, which uses :rc:`lines.antialiased`.
801 self.nchunk = kwargs.pop('nchunk', 0)
802 self.locator = kwargs.pop('locator', None)
803 if (isinstance(norm, mcolors.LogNorm)
804 or isinstance(self.locator, ticker.LogLocator)):
805 self.logscale = True
806 if norm is None:
807 norm = mcolors.LogNorm()
808 else:
809 self.logscale = False
811 cbook._check_in_list([None, 'lower', 'upper', 'image'], origin=origin)
812 if self.extent is not None and len(self.extent) != 4:
813 raise ValueError(
814 "If given, 'extent' must be None or (x0, x1, y0, y1)")
815 if self.colors is not None and cmap is not None:
816 raise ValueError('Either colors or cmap must be None')
817 if self.origin == 'image':
818 self.origin = mpl.rcParams['image.origin']
820 self._transform = kwargs.pop('transform', None)
822 kwargs = self._process_args(*args, **kwargs)
823 self._process_levels()
825 if self.colors is not None:
826 ncolors = len(self.levels)
827 if self.filled:
828 ncolors -= 1
829 i0 = 0
831 # Handle the case where colors are given for the extended
832 # parts of the contour.
833 extend_min = self.extend in ['min', 'both']
834 extend_max = self.extend in ['max', 'both']
835 use_set_under_over = False
836 # if we are extending the lower end, and we've been given enough
837 # colors then skip the first color in the resulting cmap. For the
838 # extend_max case we don't need to worry about passing more colors
839 # than ncolors as ListedColormap will clip.
840 total_levels = ncolors + int(extend_min) + int(extend_max)
841 if len(self.colors) == total_levels and (extend_min or extend_max):
842 use_set_under_over = True
843 if extend_min:
844 i0 = 1
846 cmap = mcolors.ListedColormap(self.colors[i0:None], N=ncolors)
848 if use_set_under_over:
849 if extend_min:
850 cmap.set_under(self.colors[0])
851 if extend_max:
852 cmap.set_over(self.colors[-1])
854 if self.filled:
855 self.collections = cbook.silent_list('mcoll.PathCollection')
856 else:
857 self.collections = cbook.silent_list('mcoll.LineCollection')
858 # label lists must be initialized here
859 self.labelTexts = []
860 self.labelCValues = []
862 kw = {'cmap': cmap}
863 if norm is not None:
864 kw['norm'] = norm
865 # sets self.cmap, norm if needed;
866 cm.ScalarMappable.__init__(self, **kw)
867 if vmin is not None:
868 self.norm.vmin = vmin
869 if vmax is not None:
870 self.norm.vmax = vmax
871 self._process_colors()
873 self.allsegs, self.allkinds = self._get_allsegs_and_allkinds()
875 if self.filled:
876 if self.linewidths is not None:
877 cbook._warn_external('linewidths is ignored by contourf')
879 # Lower and upper contour levels.
880 lowers, uppers = self._get_lowers_and_uppers()
882 # Ensure allkinds can be zipped below.
883 if self.allkinds is None:
884 self.allkinds = [None] * len(self.allsegs)
886 # Default zorder taken from Collection
887 zorder = kwargs.pop('zorder', 1)
888 for level, level_upper, segs, kinds in \
889 zip(lowers, uppers, self.allsegs, self.allkinds):
890 paths = self._make_paths(segs, kinds)
892 col = mcoll.PathCollection(
893 paths,
894 antialiaseds=(self.antialiased,),
895 edgecolors='none',
896 alpha=self.alpha,
897 transform=self.get_transform(),
898 zorder=zorder)
899 self.ax.add_collection(col, autolim=False)
900 self.collections.append(col)
901 else:
902 tlinewidths = self._process_linewidths()
903 self.tlinewidths = tlinewidths
904 tlinestyles = self._process_linestyles()
905 aa = self.antialiased
906 if aa is not None:
907 aa = (self.antialiased,)
908 # Default zorder taken from LineCollection
909 zorder = kwargs.pop('zorder', 2)
910 for level, width, lstyle, segs in \
911 zip(self.levels, tlinewidths, tlinestyles, self.allsegs):
912 col = mcoll.LineCollection(
913 segs,
914 antialiaseds=aa,
915 linewidths=width,
916 linestyles=[lstyle],
917 alpha=self.alpha,
918 transform=self.get_transform(),
919 zorder=zorder)
920 col.set_label('_nolegend_')
921 self.ax.add_collection(col, autolim=False)
922 self.collections.append(col)
924 for col in self.collections:
925 col.sticky_edges.x[:] = [self._mins[0], self._maxs[0]]
926 col.sticky_edges.y[:] = [self._mins[1], self._maxs[1]]
927 self.ax.update_datalim([self._mins, self._maxs])
928 self.ax.autoscale_view(tight=True)
930 self.changed() # set the colors
932 if kwargs:
933 s = ", ".join(map(repr, kwargs))
934 cbook._warn_external('The following kwargs were not used by '
935 'contour: ' + s)
937 def get_transform(self):
938 """
939 Return the :class:`~matplotlib.transforms.Transform`
940 instance used by this ContourSet.
941 """
942 if self._transform is None:
943 self._transform = self.ax.transData
944 elif (not isinstance(self._transform, mtransforms.Transform)
945 and hasattr(self._transform, '_as_mpl_transform')):
946 self._transform = self._transform._as_mpl_transform(self.ax)
947 return self._transform
949 def __getstate__(self):
950 state = self.__dict__.copy()
951 # the C object _contour_generator cannot currently be pickled. This
952 # isn't a big issue as it is not actually used once the contour has
953 # been calculated.
954 state['_contour_generator'] = None
955 return state
957 def legend_elements(self, variable_name='x', str_format=str):
958 """
959 Return a list of artists and labels suitable for passing through
960 to :func:`plt.legend` which represent this ContourSet.
962 The labels have the form "0 < x <= 1" stating the data ranges which
963 the artists represent.
965 Parameters
966 ----------
967 variable_name : str
968 The string used inside the inequality used on the labels.
970 str_format : function: float -> str
971 Function used to format the numbers in the labels.
973 Returns
974 -------
975 artists : List[`.Artist`]
976 A list of the artists.
978 labels : List[str]
979 A list of the labels.
981 """
982 artists = []
983 labels = []
985 if self.filled:
986 lowers, uppers = self._get_lowers_and_uppers()
987 n_levels = len(self.collections)
989 for i, (collection, lower, upper) in enumerate(
990 zip(self.collections, lowers, uppers)):
991 patch = mpatches.Rectangle(
992 (0, 0), 1, 1,
993 facecolor=collection.get_facecolor()[0],
994 hatch=collection.get_hatch(),
995 alpha=collection.get_alpha())
996 artists.append(patch)
998 lower = str_format(lower)
999 upper = str_format(upper)
1001 if i == 0 and self.extend in ('min', 'both'):
1002 labels.append(fr'${variable_name} \leq {lower}s$')
1003 elif i == n_levels - 1 and self.extend in ('max', 'both'):
1004 labels.append(fr'${variable_name} > {upper}s$')
1005 else:
1006 labels.append(fr'${lower} < {variable_name} \leq {upper}$')
1007 else:
1008 for collection, level in zip(self.collections, self.levels):
1010 patch = mcoll.LineCollection(None)
1011 patch.update_from(collection)
1013 artists.append(patch)
1014 # format the level for insertion into the labels
1015 level = str_format(level)
1016 labels.append(fr'${variable_name} = {level}$')
1018 return artists, labels
1020 def _process_args(self, *args, **kwargs):
1021 """
1022 Process *args* and *kwargs*; override in derived classes.
1024 Must set self.levels, self.zmin and self.zmax, and update axes
1025 limits.
1026 """
1027 self.levels = args[0]
1028 self.allsegs = args[1]
1029 self.allkinds = args[2] if len(args) > 2 else None
1030 self.zmax = np.max(self.levels)
1031 self.zmin = np.min(self.levels)
1033 # Check lengths of levels and allsegs.
1034 if self.filled:
1035 if len(self.allsegs) != len(self.levels) - 1:
1036 raise ValueError('must be one less number of segments as '
1037 'levels')
1038 else:
1039 if len(self.allsegs) != len(self.levels):
1040 raise ValueError('must be same number of segments as levels')
1042 # Check length of allkinds.
1043 if (self.allkinds is not None and
1044 len(self.allkinds) != len(self.allsegs)):
1045 raise ValueError('allkinds has different length to allsegs')
1047 # Determine x, y bounds and update axes data limits.
1048 flatseglist = [s for seg in self.allsegs for s in seg]
1049 points = np.concatenate(flatseglist, axis=0)
1050 self._mins = points.min(axis=0)
1051 self._maxs = points.max(axis=0)
1053 return kwargs
1055 def _get_allsegs_and_allkinds(self):
1056 """
1057 Override in derived classes to create and return allsegs and allkinds.
1058 allkinds can be None.
1059 """
1060 return self.allsegs, self.allkinds
1062 def _get_lowers_and_uppers(self):
1063 """
1064 Return ``(lowers, uppers)`` for filled contours.
1065 """
1066 lowers = self._levels[:-1]
1067 if self.zmin == lowers[0]:
1068 # Include minimum values in lowest interval
1069 lowers = lowers.copy() # so we don't change self._levels
1070 if self.logscale:
1071 lowers[0] = 0.99 * self.zmin
1072 else:
1073 lowers[0] -= 1
1074 uppers = self._levels[1:]
1075 return (lowers, uppers)
1077 def _make_paths(self, segs, kinds):
1078 if kinds is not None:
1079 return [mpath.Path(seg, codes=kind)
1080 for seg, kind in zip(segs, kinds)]
1081 else:
1082 return [mpath.Path(seg) for seg in segs]
1084 def changed(self):
1085 tcolors = [(tuple(rgba),)
1086 for rgba in self.to_rgba(self.cvalues, alpha=self.alpha)]
1087 self.tcolors = tcolors
1088 hatches = self.hatches * len(tcolors)
1089 for color, hatch, collection in zip(tcolors, hatches,
1090 self.collections):
1091 if self.filled:
1092 collection.set_facecolor(color)
1093 # update the collection's hatch (may be None)
1094 collection.set_hatch(hatch)
1095 else:
1096 collection.set_color(color)
1097 for label, cv in zip(self.labelTexts, self.labelCValues):
1098 label.set_alpha(self.alpha)
1099 label.set_color(self.labelMappable.to_rgba(cv))
1100 # add label colors
1101 cm.ScalarMappable.changed(self)
1103 def _autolev(self, N):
1104 """
1105 Select contour levels to span the data.
1107 The target number of levels, *N*, is used only when the
1108 scale is not log and default locator is used.
1110 We need two more levels for filled contours than for
1111 line contours, because for the latter we need to specify
1112 the lower and upper boundary of each range. For example,
1113 a single contour boundary, say at z = 0, requires only
1114 one contour line, but two filled regions, and therefore
1115 three levels to provide boundaries for both regions.
1116 """
1117 if self.locator is None:
1118 if self.logscale:
1119 self.locator = ticker.LogLocator()
1120 else:
1121 self.locator = ticker.MaxNLocator(N + 1, min_n_ticks=1)
1123 lev = self.locator.tick_values(self.zmin, self.zmax)
1125 try:
1126 if self.locator._symmetric:
1127 return lev
1128 except AttributeError:
1129 pass
1131 # Trim excess levels the locator may have supplied.
1132 under = np.nonzero(lev < self.zmin)[0]
1133 i0 = under[-1] if len(under) else 0
1134 over = np.nonzero(lev > self.zmax)[0]
1135 i1 = over[0] + 1 if len(over) else len(lev)
1136 if self.extend in ('min', 'both'):
1137 i0 += 1
1138 if self.extend in ('max', 'both'):
1139 i1 -= 1
1141 if i1 - i0 < 3:
1142 i0, i1 = 0, len(lev)
1144 return lev[i0:i1]
1146 def _contour_level_args(self, z, args):
1147 """
1148 Determine the contour levels and store in self.levels.
1149 """
1150 if self.levels is None:
1151 if len(args) == 0:
1152 levels_arg = 7 # Default, hard-wired.
1153 else:
1154 levels_arg = args[0]
1155 else:
1156 levels_arg = self.levels
1157 if isinstance(levels_arg, Integral):
1158 self.levels = self._autolev(levels_arg)
1159 else:
1160 self.levels = np.asarray(levels_arg).astype(np.float64)
1162 if not self.filled:
1163 inside = (self.levels > self.zmin) & (self.levels < self.zmax)
1164 levels_in = self.levels[inside]
1165 if len(levels_in) == 0:
1166 self.levels = [self.zmin]
1167 cbook._warn_external(
1168 "No contour levels were found within the data range.")
1170 if self.filled and len(self.levels) < 2:
1171 raise ValueError("Filled contours require at least 2 levels.")
1173 if len(self.levels) > 1 and np.min(np.diff(self.levels)) <= 0.0:
1174 raise ValueError("Contour levels must be increasing")
1176 def _process_levels(self):
1177 """
1178 Assign values to :attr:`layers` based on :attr:`levels`,
1179 adding extended layers as needed if contours are filled.
1181 For line contours, layers simply coincide with levels;
1182 a line is a thin layer. No extended levels are needed
1183 with line contours.
1184 """
1185 # Make a private _levels to include extended regions; we
1186 # want to leave the original levels attribute unchanged.
1187 # (Colorbar needs this even for line contours.)
1188 self._levels = list(self.levels)
1190 if self.logscale:
1191 lower, upper = 1e-250, 1e250
1192 else:
1193 lower, upper = -1e250, 1e250
1195 if self.extend in ('both', 'min'):
1196 self._levels.insert(0, lower)
1197 if self.extend in ('both', 'max'):
1198 self._levels.append(upper)
1199 self._levels = np.asarray(self._levels)
1201 if not self.filled:
1202 self.layers = self.levels
1203 return
1205 # Layer values are mid-way between levels in screen space.
1206 if self.logscale:
1207 # Avoid overflow by taking sqrt before multiplying.
1208 self.layers = (np.sqrt(self._levels[:-1])
1209 * np.sqrt(self._levels[1:]))
1210 else:
1211 self.layers = 0.5 * (self._levels[:-1] + self._levels[1:])
1213 def _process_colors(self):
1214 """
1215 Color argument processing for contouring.
1217 Note that we base the color mapping on the contour levels
1218 and layers, not on the actual range of the Z values. This
1219 means we don't have to worry about bad values in Z, and we
1220 always have the full dynamic range available for the selected
1221 levels.
1223 The color is based on the midpoint of the layer, except for
1224 extended end layers. By default, the norm vmin and vmax
1225 are the extreme values of the non-extended levels. Hence,
1226 the layer color extremes are not the extreme values of
1227 the colormap itself, but approach those values as the number
1228 of levels increases. An advantage of this scheme is that
1229 line contours, when added to filled contours, take on
1230 colors that are consistent with those of the filled regions;
1231 for example, a contour line on the boundary between two
1232 regions will have a color intermediate between those
1233 of the regions.
1235 """
1236 self.monochrome = self.cmap.monochrome
1237 if self.colors is not None:
1238 # Generate integers for direct indexing.
1239 i0, i1 = 0, len(self.levels)
1240 if self.filled:
1241 i1 -= 1
1242 # Out of range indices for over and under:
1243 if self.extend in ('both', 'min'):
1244 i0 -= 1
1245 if self.extend in ('both', 'max'):
1246 i1 += 1
1247 self.cvalues = list(range(i0, i1))
1248 self.set_norm(mcolors.NoNorm())
1249 else:
1250 self.cvalues = self.layers
1251 self.set_array(self.levels)
1252 self.autoscale_None()
1253 if self.extend in ('both', 'max', 'min'):
1254 self.norm.clip = False
1256 # self.tcolors are set by the "changed" method
1258 def _process_linewidths(self):
1259 linewidths = self.linewidths
1260 Nlev = len(self.levels)
1261 if linewidths is None:
1262 tlinewidths = [(mpl.rcParams['lines.linewidth'],)] * Nlev
1263 else:
1264 if not np.iterable(linewidths):
1265 linewidths = [linewidths] * Nlev
1266 else:
1267 linewidths = list(linewidths)
1268 if len(linewidths) < Nlev:
1269 nreps = int(np.ceil(Nlev / len(linewidths)))
1270 linewidths = linewidths * nreps
1271 if len(linewidths) > Nlev:
1272 linewidths = linewidths[:Nlev]
1273 tlinewidths = [(w,) for w in linewidths]
1274 return tlinewidths
1276 def _process_linestyles(self):
1277 linestyles = self.linestyles
1278 Nlev = len(self.levels)
1279 if linestyles is None:
1280 tlinestyles = ['solid'] * Nlev
1281 if self.monochrome:
1282 neg_ls = mpl.rcParams['contour.negative_linestyle']
1283 eps = - (self.zmax - self.zmin) * 1e-15
1284 for i, lev in enumerate(self.levels):
1285 if lev < eps:
1286 tlinestyles[i] = neg_ls
1287 else:
1288 if isinstance(linestyles, str):
1289 tlinestyles = [linestyles] * Nlev
1290 elif np.iterable(linestyles):
1291 tlinestyles = list(linestyles)
1292 if len(tlinestyles) < Nlev:
1293 nreps = int(np.ceil(Nlev / len(linestyles)))
1294 tlinestyles = tlinestyles * nreps
1295 if len(tlinestyles) > Nlev:
1296 tlinestyles = tlinestyles[:Nlev]
1297 else:
1298 raise ValueError("Unrecognized type for linestyles kwarg")
1299 return tlinestyles
1301 def get_alpha(self):
1302 """returns alpha to be applied to all ContourSet artists"""
1303 return self.alpha
1305 def set_alpha(self, alpha):
1306 """
1307 Set the alpha blending value for all ContourSet artists.
1308 *alpha* must be between 0 (transparent) and 1 (opaque).
1309 """
1310 self.alpha = alpha
1311 self.changed()
1313 def find_nearest_contour(self, x, y, indices=None, pixel=True):
1314 """
1315 Finds contour that is closest to a point. Defaults to
1316 measuring distance in pixels (screen space - useful for manual
1317 contour labeling), but this can be controlled via a keyword
1318 argument.
1320 Returns a tuple containing the contour, segment, index of
1321 segment, x & y of segment point and distance to minimum point.
1323 Optional keyword arguments:
1325 *indices*:
1326 Indexes of contour levels to consider when looking for
1327 nearest point. Defaults to using all levels.
1329 *pixel*:
1330 If *True*, measure distance in pixel space, if not, measure
1331 distance in axes space. Defaults to *True*.
1333 """
1335 # This function uses a method that is probably quite
1336 # inefficient based on converting each contour segment to
1337 # pixel coordinates and then comparing the given point to
1338 # those coordinates for each contour. This will probably be
1339 # quite slow for complex contours, but for normal use it works
1340 # sufficiently well that the time is not noticeable.
1341 # Nonetheless, improvements could probably be made.
1343 if indices is None:
1344 indices = list(range(len(self.levels)))
1346 dmin = np.inf
1347 conmin = None
1348 segmin = None
1349 xmin = None
1350 ymin = None
1352 point = np.array([x, y])
1354 for icon in indices:
1355 con = self.collections[icon]
1356 trans = con.get_transform()
1357 paths = con.get_paths()
1359 for segNum, linepath in enumerate(paths):
1360 lc = linepath.vertices
1361 # transfer all data points to screen coordinates if desired
1362 if pixel:
1363 lc = trans.transform(lc)
1365 d, xc, leg = _find_closest_point_on_path(lc, point)
1366 if d < dmin:
1367 dmin = d
1368 conmin = icon
1369 segmin = segNum
1370 imin = leg[1]
1371 xmin = xc[0]
1372 ymin = xc[1]
1374 return (conmin, segmin, imin, xmin, ymin, dmin)
1377class QuadContourSet(ContourSet):
1378 """
1379 Create and store a set of contour lines or filled regions.
1381 User-callable method: `~axes.Axes.clabel`
1383 Attributes
1384 ----------
1385 ax
1386 The axes object in which the contours are drawn.
1388 collections
1389 A silent_list of LineCollections or PolyCollections.
1391 levels
1392 Contour levels.
1394 layers
1395 Same as levels for line contours; half-way between
1396 levels for filled contours. See :meth:`_process_colors` method.
1397 """
1399 def _process_args(self, *args, **kwargs):
1400 """
1401 Process args and kwargs.
1402 """
1403 if isinstance(args[0], QuadContourSet):
1404 if self.levels is None:
1405 self.levels = args[0].levels
1406 self.zmin = args[0].zmin
1407 self.zmax = args[0].zmax
1408 self._corner_mask = args[0]._corner_mask
1409 contour_generator = args[0]._contour_generator
1410 self._mins = args[0]._mins
1411 self._maxs = args[0]._maxs
1412 else:
1413 import matplotlib._contour as _contour
1415 self._corner_mask = kwargs.pop('corner_mask', None)
1416 if self._corner_mask is None:
1417 self._corner_mask = mpl.rcParams['contour.corner_mask']
1419 x, y, z = self._contour_args(args, kwargs)
1421 _mask = ma.getmask(z)
1422 if _mask is ma.nomask or not _mask.any():
1423 _mask = None
1425 contour_generator = _contour.QuadContourGenerator(
1426 x, y, z.filled(), _mask, self._corner_mask, self.nchunk)
1428 t = self.get_transform()
1430 # if the transform is not trans data, and some part of it
1431 # contains transData, transform the xs and ys to data coordinates
1432 if (t != self.ax.transData and
1433 any(t.contains_branch_seperately(self.ax.transData))):
1434 trans_to_data = t - self.ax.transData
1435 pts = (np.vstack([x.flat, y.flat]).T)
1436 transformed_pts = trans_to_data.transform(pts)
1437 x = transformed_pts[..., 0]
1438 y = transformed_pts[..., 1]
1440 self._mins = [ma.min(x), ma.min(y)]
1441 self._maxs = [ma.max(x), ma.max(y)]
1443 self._contour_generator = contour_generator
1445 return kwargs
1447 def _get_allsegs_and_allkinds(self):
1448 """Compute ``allsegs`` and ``allkinds`` using C extension."""
1449 allsegs = []
1450 if self.filled:
1451 lowers, uppers = self._get_lowers_and_uppers()
1452 allkinds = []
1453 for level, level_upper in zip(lowers, uppers):
1454 vertices, kinds = \
1455 self._contour_generator.create_filled_contour(
1456 level, level_upper)
1457 allsegs.append(vertices)
1458 allkinds.append(kinds)
1459 else:
1460 allkinds = None
1461 for level in self.levels:
1462 vertices = self._contour_generator.create_contour(level)
1463 allsegs.append(vertices)
1464 return allsegs, allkinds
1466 def _contour_args(self, args, kwargs):
1467 if self.filled:
1468 fn = 'contourf'
1469 else:
1470 fn = 'contour'
1471 Nargs = len(args)
1472 if Nargs <= 2:
1473 z = ma.asarray(args[0], dtype=np.float64)
1474 x, y = self._initialize_x_y(z)
1475 args = args[1:]
1476 elif Nargs <= 4:
1477 x, y, z = self._check_xyz(args[:3], kwargs)
1478 args = args[3:]
1479 else:
1480 raise TypeError("Too many arguments to %s; see help(%s)" %
1481 (fn, fn))
1482 z = ma.masked_invalid(z, copy=False)
1483 self.zmax = float(z.max())
1484 self.zmin = float(z.min())
1485 if self.logscale and self.zmin <= 0:
1486 z = ma.masked_where(z <= 0, z)
1487 cbook._warn_external('Log scale: values of z <= 0 have been '
1488 'masked')
1489 self.zmin = float(z.min())
1490 self._contour_level_args(z, args)
1491 return (x, y, z)
1493 def _check_xyz(self, args, kwargs):
1494 """
1495 Check that the shapes of the input arrays match; if x and y are 1D,
1496 convert them to 2D using meshgrid.
1497 """
1498 x, y = args[:2]
1499 kwargs = self.ax._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
1500 x = self.ax.convert_xunits(x)
1501 y = self.ax.convert_yunits(y)
1503 x = np.asarray(x, dtype=np.float64)
1504 y = np.asarray(y, dtype=np.float64)
1505 z = ma.asarray(args[2], dtype=np.float64)
1507 if z.ndim != 2:
1508 raise TypeError(f"Input z must be 2D, not {z.ndim}D")
1509 if z.shape[0] < 2 or z.shape[1] < 2:
1510 raise TypeError(f"Input z must be at least a (2, 2) shaped array, "
1511 f"but has shape {z.shape}")
1512 Ny, Nx = z.shape
1514 if x.ndim != y.ndim:
1515 raise TypeError(f"Number of dimensions of x ({x.ndim}) and y "
1516 f"({y.ndim}) do not match")
1517 if x.ndim == 1:
1518 nx, = x.shape
1519 ny, = y.shape
1520 if nx != Nx:
1521 raise TypeError(f"Length of x ({nx}) must match number of "
1522 f"columns in z ({Nx})")
1523 if ny != Ny:
1524 raise TypeError(f"Length of y ({ny}) must match number of "
1525 f"rows in z ({Ny})")
1526 x, y = np.meshgrid(x, y)
1527 elif x.ndim == 2:
1528 if x.shape != z.shape:
1529 raise TypeError(
1530 f"Shapes of x {x.shape} and z {z.shape} do not match")
1531 if y.shape != z.shape:
1532 raise TypeError(
1533 f"Shapes of y {y.shape} and z {z.shape} do not match")
1534 else:
1535 raise TypeError(f"Inputs x and y must be 1D or 2D, not {x.ndim}D")
1537 return x, y, z
1539 def _initialize_x_y(self, z):
1540 """
1541 Return X, Y arrays such that contour(Z) will match imshow(Z)
1542 if origin is not None.
1543 The center of pixel Z[i, j] depends on origin:
1544 if origin is None, x = j, y = i;
1545 if origin is 'lower', x = j + 0.5, y = i + 0.5;
1546 if origin is 'upper', x = j + 0.5, y = Nrows - i - 0.5
1547 If extent is not None, x and y will be scaled to match,
1548 as in imshow.
1549 If origin is None and extent is not None, then extent
1550 will give the minimum and maximum values of x and y.
1551 """
1552 if z.ndim != 2:
1553 raise TypeError(f"Input z must be 2D, not {z.ndim}D")
1554 elif z.shape[0] < 2 or z.shape[1] < 2:
1555 raise TypeError(f"Input z must be at least a (2, 2) shaped array, "
1556 f"but has shape {z.shape}")
1557 else:
1558 Ny, Nx = z.shape
1559 if self.origin is None: # Not for image-matching.
1560 if self.extent is None:
1561 return np.meshgrid(np.arange(Nx), np.arange(Ny))
1562 else:
1563 x0, x1, y0, y1 = self.extent
1564 x = np.linspace(x0, x1, Nx)
1565 y = np.linspace(y0, y1, Ny)
1566 return np.meshgrid(x, y)
1567 # Match image behavior:
1568 if self.extent is None:
1569 x0, x1, y0, y1 = (0, Nx, 0, Ny)
1570 else:
1571 x0, x1, y0, y1 = self.extent
1572 dx = (x1 - x0) / Nx
1573 dy = (y1 - y0) / Ny
1574 x = x0 + (np.arange(Nx) + 0.5) * dx
1575 y = y0 + (np.arange(Ny) + 0.5) * dy
1576 if self.origin == 'upper':
1577 y = y[::-1]
1578 return np.meshgrid(x, y)
1580 _contour_doc = """
1581 Plot contours.
1583 Call signature::
1585 contour([X, Y,] Z, [levels], **kwargs)
1587 `.contour` and `.contourf` draw contour lines and filled contours,
1588 respectively. Except as noted, function signatures and return values
1589 are the same for both versions.
1591 Parameters
1592 ----------
1593 X, Y : array-like, optional
1594 The coordinates of the values in *Z*.
1596 *X* and *Y* must both be 2-D with the same shape as *Z* (e.g.
1597 created via `numpy.meshgrid`), or they must both be 1-D such
1598 that ``len(X) == M`` is the number of columns in *Z* and
1599 ``len(Y) == N`` is the number of rows in *Z*.
1601 If not given, they are assumed to be integer indices, i.e.
1602 ``X = range(M)``, ``Y = range(N)``.
1604 Z : array-like(N, M)
1605 The height values over which the contour is drawn.
1607 levels : int or array-like, optional
1608 Determines the number and positions of the contour lines / regions.
1610 If an int *n*, use *n* data intervals; i.e. draw *n+1* contour
1611 lines. The level heights are automatically chosen.
1613 If array-like, draw contour lines at the specified levels.
1614 The values must be in increasing order.
1616 Returns
1617 -------
1618 c : `~.contour.QuadContourSet`
1620 Other Parameters
1621 ----------------
1622 corner_mask : bool, optional
1623 Enable/disable corner masking, which only has an effect if *Z* is
1624 a masked array. If ``False``, any quad touching a masked point is
1625 masked out. If ``True``, only the triangular corners of quads
1626 nearest those points are always masked out, other triangular
1627 corners comprising three unmasked points are contoured as usual.
1629 Defaults to :rc:`contour.corner_mask`.
1631 colors : color string or sequence of colors, optional
1632 The colors of the levels, i.e. the lines for `.contour` and the
1633 areas for `.contourf`.
1635 The sequence is cycled for the levels in ascending order. If the
1636 sequence is shorter than the number of levels, it's repeated.
1638 As a shortcut, single color strings may be used in place of
1639 one-element lists, i.e. ``'red'`` instead of ``['red']`` to color
1640 all levels with the same color. This shortcut does only work for
1641 color strings, not for other ways of specifying colors.
1643 By default (value *None*), the colormap specified by *cmap*
1644 will be used.
1646 alpha : float, optional
1647 The alpha blending value, between 0 (transparent) and 1 (opaque).
1649 cmap : str or `.Colormap`, optional
1650 A `.Colormap` instance or registered colormap name. The colormap
1651 maps the level values to colors.
1652 Defaults to :rc:`image.cmap`.
1654 If both *colors* and *cmap* are given, an error is raised.
1656 norm : `~matplotlib.colors.Normalize`, optional
1657 If a colormap is used, the `.Normalize` instance scales the level
1658 values to the canonical colormap range [0, 1] for mapping to
1659 colors. If not given, the default linear scaling is used.
1661 vmin, vmax : float, optional
1662 If not *None*, either or both of these values will be supplied to
1663 the `.Normalize` instance, overriding the default color scaling
1664 based on *levels*.
1666 origin : {*None*, 'upper', 'lower', 'image'}, optional
1667 Determines the orientation and exact position of *Z* by specifying
1668 the position of ``Z[0, 0]``. This is only relevant, if *X*, *Y*
1669 are not given.
1671 - *None*: ``Z[0, 0]`` is at X=0, Y=0 in the lower left corner.
1672 - 'lower': ``Z[0, 0]`` is at X=0.5, Y=0.5 in the lower left corner.
1673 - 'upper': ``Z[0, 0]`` is at X=N+0.5, Y=0.5 in the upper left
1674 corner.
1675 - 'image': Use the value from :rc:`image.origin`.
1677 extent : (x0, x1, y0, y1), optional
1678 If *origin* is not *None*, then *extent* is interpreted as in
1679 `.imshow`: it gives the outer pixel boundaries. In this case, the
1680 position of Z[0, 0] is the center of the pixel, not a corner. If
1681 *origin* is *None*, then (*x0*, *y0*) is the position of Z[0, 0],
1682 and (*x1*, *y1*) is the position of Z[-1,-1].
1684 This argument is ignored if *X* and *Y* are specified in the call
1685 to contour.
1687 locator : ticker.Locator subclass, optional
1688 The locator is used to determine the contour levels if they
1689 are not given explicitly via *levels*.
1690 Defaults to `~.ticker.MaxNLocator`.
1692 extend : {'neither', 'both', 'min', 'max'}, optional, default: \
1693'neither'
1694 Determines the ``contourf``-coloring of values that are outside the
1695 *levels* range.
1697 If 'neither', values outside the *levels* range are not colored.
1698 If 'min', 'max' or 'both', color the values below, above or below
1699 and above the *levels* range.
1701 Values below ``min(levels)`` and above ``max(levels)`` are mapped
1702 to the under/over values of the `.Colormap`. Note, that most
1703 colormaps do not have dedicated colors for these by default, so
1704 that the over and under values are the edge values of the colormap.
1705 You may want to set these values explicitly using
1706 `.Colormap.set_under` and `.Colormap.set_over`.
1708 .. note::
1710 An exising `.QuadContourSet` does not get notified if
1711 properties of its colormap are changed. Therefore, an explicit
1712 call `.QuadContourSet.changed()` is needed after modifying the
1713 colormap. The explicit call can be left out, if a colorbar is
1714 assigned to the `.QuadContourSet` because it internally calls
1715 `.QuadContourSet.changed()`.
1717 Example::
1719 x = np.arange(1, 10)
1720 y = x.reshape(-1, 1)
1721 h = x * y
1723 cs = plt.contourf(h, levels=[10, 30, 50],
1724 colors=['#808080', '#A0A0A0', '#C0C0C0'], extend='both')
1725 cs.cmap.set_over('red')
1726 cs.cmap.set_under('blue')
1727 cs.changed()
1729 xunits, yunits : registered units, optional
1730 Override axis units by specifying an instance of a
1731 :class:`matplotlib.units.ConversionInterface`.
1733 antialiased : bool, optional
1734 Enable antialiasing, overriding the defaults. For
1735 filled contours, the default is *True*. For line contours,
1736 it is taken from :rc:`lines.antialiased`.
1738 nchunk : int >= 0, optional
1739 If 0, no subdivision of the domain. Specify a positive integer to
1740 divide the domain into subdomains of *nchunk* by *nchunk* quads.
1741 Chunking reduces the maximum length of polygons generated by the
1742 contouring algorithm which reduces the rendering workload passed
1743 on to the backend and also requires slightly less RAM. It can
1744 however introduce rendering artifacts at chunk boundaries depending
1745 on the backend, the *antialiased* flag and value of *alpha*.
1747 linewidths : float or sequence of float, optional
1748 *Only applies to* `.contour`.
1750 The line width of the contour lines.
1752 If a number, all levels will be plotted with this linewidth.
1754 If a sequence, the levels in ascending order will be plotted with
1755 the linewidths in the order specified.
1757 Defaults to :rc:`lines.linewidth`.
1759 linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional
1760 *Only applies to* `.contour`.
1762 If *linestyles* is *None*, the default is 'solid' unless the lines
1763 are monochrome. In that case, negative contours will take their
1764 linestyle from :rc:`contour.negative_linestyle` setting.
1766 *linestyles* can also be an iterable of the above strings
1767 specifying a set of linestyles to be used. If this
1768 iterable is shorter than the number of contour levels
1769 it will be repeated as necessary.
1771 hatches : List[str], optional
1772 *Only applies to* `.contourf`.
1774 A list of cross hatch patterns to use on the filled areas.
1775 If None, no hatching will be added to the contour.
1776 Hatching is supported in the PostScript, PDF, SVG and Agg
1777 backends only.
1779 Notes
1780 -----
1781 1. `.contourf` differs from the MATLAB version in that it does not draw
1782 the polygon edges. To draw edges, add line contours with calls to
1783 `.contour`.
1785 2. `.contourf` fills intervals that are closed at the top; that is, for
1786 boundaries *z1* and *z2*, the filled region is::
1788 z1 < Z <= z2
1790 except for the lowest interval, which is closed on both sides (i.e.
1791 it includes the lowest value).
1792 """