Coverage for /usr/lib/python3/dist-packages/matplotlib/tri/tricontour.py: 30%
53 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
1import numpy as np
3from matplotlib import _docstring
4from matplotlib.contour import ContourSet
5from matplotlib.tri.triangulation import Triangulation
8@_docstring.dedent_interpd
9class TriContourSet(ContourSet):
10 """
11 Create and store a set of contour lines or filled regions for
12 a triangular grid.
14 This class is typically not instantiated directly by the user but by
15 `~.Axes.tricontour` and `~.Axes.tricontourf`.
17 %(contour_set_attributes)s
18 """
19 def __init__(self, ax, *args, **kwargs):
20 """
21 Draw triangular grid contour lines or filled regions,
22 depending on whether keyword arg *filled* is False
23 (default) or True.
25 The first argument of the initializer must be an `~.axes.Axes`
26 object. The remaining arguments and keyword arguments
27 are described in the docstring of `~.Axes.tricontour`.
28 """
29 super().__init__(ax, *args, **kwargs)
31 def _process_args(self, *args, **kwargs):
32 """
33 Process args and kwargs.
34 """
35 if isinstance(args[0], TriContourSet):
36 C = args[0]._contour_generator
37 if self.levels is None:
38 self.levels = args[0].levels
39 self.zmin = args[0].zmin
40 self.zmax = args[0].zmax
41 self._mins = args[0]._mins
42 self._maxs = args[0]._maxs
43 else:
44 from matplotlib import _tri
45 tri, z = self._contour_args(args, kwargs)
46 C = _tri.TriContourGenerator(tri.get_cpp_triangulation(), z)
47 self._mins = [tri.x.min(), tri.y.min()]
48 self._maxs = [tri.x.max(), tri.y.max()]
50 self._contour_generator = C
51 return kwargs
53 def _contour_args(self, args, kwargs):
54 tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args,
55 **kwargs)
56 z = np.ma.asarray(args[0])
57 if z.shape != tri.x.shape:
58 raise ValueError('z array must have same length as triangulation x'
59 ' and y arrays')
61 # z values must be finite, only need to check points that are included
62 # in the triangulation.
63 z_check = z[np.unique(tri.get_masked_triangles())]
64 if np.ma.is_masked(z_check):
65 raise ValueError('z must not contain masked points within the '
66 'triangulation')
67 if not np.isfinite(z_check).all():
68 raise ValueError('z array must not contain non-finite values '
69 'within the triangulation')
71 z = np.ma.masked_invalid(z, copy=False)
72 self.zmax = float(z_check.max())
73 self.zmin = float(z_check.min())
74 if self.logscale and self.zmin <= 0:
75 func = 'contourf' if self.filled else 'contour'
76 raise ValueError(f'Cannot {func} log of negative values.')
77 self._process_contour_level_args(args[1:])
78 return (tri, z)
81_docstring.interpd.update(_tricontour_doc="""
82Draw contour %%(type)s on an unstructured triangular grid.
84Call signatures::
86 %%(func)s(triangulation, z, [levels], ...)
87 %%(func)s(x, y, z, [levels], *, [triangles=triangles], [mask=mask], ...)
89The triangular grid can be specified either by passing a `.Triangulation`
90object as the first parameter, or by passing the points *x*, *y* and
91optionally the *triangles* and a *mask*. See `.Triangulation` for an
92explanation of these parameters. If neither of *triangulation* or
93*triangles* are given, the triangulation is calculated on the fly.
95It is possible to pass *triangles* positionally, i.e.
96``%%(func)s(x, y, triangles, z, ...)``. However, this is discouraged. For more
97clarity, pass *triangles* via keyword argument.
99Parameters
100----------
101triangulation : `.Triangulation`, optional
102 An already created triangular grid.
104x, y, triangles, mask
105 Parameters defining the triangular grid. See `.Triangulation`.
106 This is mutually exclusive with specifying *triangulation*.
108z : array-like
109 The height values over which the contour is drawn. Color-mapping is
110 controlled by *cmap*, *norm*, *vmin*, and *vmax*.
112levels : int or array-like, optional
113 Determines the number and positions of the contour lines / regions.
115 If an int *n*, use `~matplotlib.ticker.MaxNLocator`, which tries to
116 automatically choose no more than *n+1* "nice" contour levels between
117 between minimum and maximum numeric values of *Z*.
119 If array-like, draw contour lines at the specified levels. The values must
120 be in increasing order.
122Returns
123-------
124`~matplotlib.tri.TriContourSet`
126Other Parameters
127----------------
128colors : color string or sequence of colors, optional
129 The colors of the levels, i.e., the contour %%(type)s.
131 The sequence is cycled for the levels in ascending order. If the sequence
132 is shorter than the number of levels, it is repeated.
134 As a shortcut, single color strings may be used in place of one-element
135 lists, i.e. ``'red'`` instead of ``['red']`` to color all levels with the
136 same color. This shortcut does only work for color strings, not for other
137 ways of specifying colors.
139 By default (value *None*), the colormap specified by *cmap* will be used.
141alpha : float, default: 1
142 The alpha blending value, between 0 (transparent) and 1 (opaque).
144%(cmap_doc)s
146 This parameter is ignored if *colors* is set.
148%(norm_doc)s
150 This parameter is ignored if *colors* is set.
152%(vmin_vmax_doc)s
154 If *vmin* or *vmax* are not given, the default color scaling is based on
155 *levels*.
157 This parameter is ignored if *colors* is set.
159origin : {*None*, 'upper', 'lower', 'image'}, default: None
160 Determines the orientation and exact position of *z* by specifying the
161 position of ``z[0, 0]``. This is only relevant, if *X*, *Y* are not given.
163 - *None*: ``z[0, 0]`` is at X=0, Y=0 in the lower left corner.
164 - 'lower': ``z[0, 0]`` is at X=0.5, Y=0.5 in the lower left corner.
165 - 'upper': ``z[0, 0]`` is at X=N+0.5, Y=0.5 in the upper left corner.
166 - 'image': Use the value from :rc:`image.origin`.
168extent : (x0, x1, y0, y1), optional
169 If *origin* is not *None*, then *extent* is interpreted as in `.imshow`: it
170 gives the outer pixel boundaries. In this case, the position of z[0, 0] is
171 the center of the pixel, not a corner. If *origin* is *None*, then
172 (*x0*, *y0*) is the position of z[0, 0], and (*x1*, *y1*) is the position
173 of z[-1, -1].
175 This argument is ignored if *X* and *Y* are specified in the call to
176 contour.
178locator : ticker.Locator subclass, optional
179 The locator is used to determine the contour levels if they are not given
180 explicitly via *levels*.
181 Defaults to `~.ticker.MaxNLocator`.
183extend : {'neither', 'both', 'min', 'max'}, default: 'neither'
184 Determines the ``%%(func)s``-coloring of values that are outside the
185 *levels* range.
187 If 'neither', values outside the *levels* range are not colored. If 'min',
188 'max' or 'both', color the values below, above or below and above the
189 *levels* range.
191 Values below ``min(levels)`` and above ``max(levels)`` are mapped to the
192 under/over values of the `.Colormap`. Note that most colormaps do not have
193 dedicated colors for these by default, so that the over and under values
194 are the edge values of the colormap. You may want to set these values
195 explicitly using `.Colormap.set_under` and `.Colormap.set_over`.
197 .. note::
199 An existing `.TriContourSet` does not get notified if properties of its
200 colormap are changed. Therefore, an explicit call to
201 `.ContourSet.changed()` is needed after modifying the colormap. The
202 explicit call can be left out, if a colorbar is assigned to the
203 `.TriContourSet` because it internally calls `.ContourSet.changed()`.
205xunits, yunits : registered units, optional
206 Override axis units by specifying an instance of a
207 :class:`matplotlib.units.ConversionInterface`.
209antialiased : bool, optional
210 Enable antialiasing, overriding the defaults. For
211 filled contours, the default is *True*. For line contours,
212 it is taken from :rc:`lines.antialiased`.""" % _docstring.interpd.params)
215@_docstring.Substitution(func='tricontour', type='lines')
216@_docstring.dedent_interpd
217def tricontour(ax, *args, **kwargs):
218 """
219 %(_tricontour_doc)s
221 linewidths : float or array-like, default: :rc:`contour.linewidth`
222 The line width of the contour lines.
224 If a number, all levels will be plotted with this linewidth.
226 If a sequence, the levels in ascending order will be plotted with
227 the linewidths in the order specified.
229 If None, this falls back to :rc:`lines.linewidth`.
231 linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional
232 If *linestyles* is *None*, the default is 'solid' unless the lines are
233 monochrome. In that case, negative contours will take their linestyle
234 from :rc:`contour.negative_linestyle` setting.
236 *linestyles* can also be an iterable of the above strings specifying a
237 set of linestyles to be used. If this iterable is shorter than the
238 number of contour levels it will be repeated as necessary.
239 """
240 kwargs['filled'] = False
241 return TriContourSet(ax, *args, **kwargs)
244@_docstring.Substitution(func='tricontourf', type='regions')
245@_docstring.dedent_interpd
246def tricontourf(ax, *args, **kwargs):
247 """
248 %(_tricontour_doc)s
250 hatches : list[str], optional
251 A list of cross hatch patterns to use on the filled areas.
252 If None, no hatching will be added to the contour.
253 Hatching is supported in the PostScript, PDF, SVG and Agg
254 backends only.
256 Notes
257 -----
258 `.tricontourf` fills intervals that are closed at the top; that is, for
259 boundaries *z1* and *z2*, the filled region is::
261 z1 < Z <= z2
263 except for the lowest interval, which is closed on both sides (i.e. it
264 includes the lowest value).
265 """
266 kwargs['filled'] = True
267 return TriContourSet(ax, *args, **kwargs)