matplotlib.contour¶
Classes to support contour plotting and labelling for the Axes class.
-
class
matplotlib.contour.ClabelText(x=0, y=0, text='', color=None, verticalalignment='baseline', horizontalalignment='left', multialignment=None, fontproperties=None, rotation=None, linespacing=None, rotation_mode=None, usetex=None, wrap=False, **kwargs)[source]¶ Bases:
matplotlib.text.TextUnlike the ordinary text, the get_rotation returns an updated angle in the pixel coordinate assuming that the input rotation is an angle in data coordinate (or whatever transform set).
Create a
Textinstance at x, y with string text.Valid keyword arguments are:
Property Description agg_filtera filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alphafloat or None animatedbool backgroundcolorcolor bboxdict with properties for patches.FancyBboxPatchclip_boxBboxclip_onbool clip_pathPatch or (Path, Transform) or None coloror ccolor containsunknown figureFigurefontfamilyor family{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'} fontpropertiesor font or font_propertiesfont_manager.FontPropertiesorstrorpathlib.Pathfontsizeor sizefloat or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'} fontstretchor stretch{a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'} fontstyleor style{'normal', 'italic', 'oblique'} fontvariantor variant{'normal', 'small-caps'} fontweightor weight{a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'} gidstr horizontalalignmentor ha{'center', 'right', 'left'} in_layoutbool labelobject linespacingfloat (multiple of font size) multialignmentor ma{'left', 'right', 'center'} path_effectsAbstractPathEffectpickerNone or bool or callable position(float, float) rasterizedbool or None rotationfloat or {'vertical', 'horizontal'} rotation_mode{None, 'default', 'anchor'} sketch_params(scale: float, length: float, randomness: float) snapbool or None textobject transformTransformurlstr usetexbool or None verticalalignmentor va{'center', 'top', 'bottom', 'baseline', 'center_baseline'} visiblebool wrapbool xfloat yfloat zorderfloat
-
class
matplotlib.contour.ContourLabeler[source]¶ Bases:
objectMixin to provide labelling capability to
ContourSet.-
add_label_clabeltext(self, x, y, rotation, lev, cvalue)[source]¶ Add contour label using
ClabelTextclass.
-
add_label_near(self, x, y, inline=True, inline_spacing=5, transform=None)[source]¶ Add a label near the point (x, y). If transform is None (default), (x, y) is in data coordinates; if transform is False, (x, y) is in display coordinates; otherwise, the specified transform will be used to translate (x, y) into display coordinates.
Parameters: - x, yfloat
The approximate location of the label.
- inlinebool, default: True
If True remove the segment of the contour beneath the label.
- inline_spacingint, default: 5
Space in pixels to leave on each side of label when placing inline. This spacing will be exact for labels at locations where the contour is straight, less so for labels on curved contours.
-
calc_label_rot_and_inline(self, slc, ind, lw, lc=None, spacing=5)[source]¶ Calculate the appropriate label rotation given the linecontour coordinates in screen units, the index of the label location and the label width.
If lc is not None or empty, also break contours and compute inlining.
spacing is the empty space to leave around the label, in pixels.
Both tasks are done together to avoid calculating path lengths multiple times, which is relatively costly.
The method used here involves computing the path length along the contour in pixel coordinates and then looking approximately (label width / 2) away from central point to determine rotation and then to break contour if desired.
-
clabel(self, levels=None, *, fontsize=None, inline=True, inline_spacing=5, fmt='%1.3f', colors=None, use_clabeltext=False, manual=False, rightside_up=True, zorder=None)[source]¶ Label a contour plot.
Adds labels to line contours in this
ContourSet(which inherits from this mixin class).Parameters: - levelsarray-like, optional
A list of level values, that should be labeled. The list must be a subset of
cs.levels. If not given, all levels are labeled.- fontsizestr or float, default:
rcParams["font.size"](default:10.0) Size in points or relative size e.g., 'smaller', 'x-large'. See
Text.set_sizefor accepted string values.- colorscolor or colors or None, default: None
The label colors:
- If None, the color of each label matches the color of the corresponding contour.
- If one string color, e.g., colors = 'r' or colors = 'red', all labels will be plotted in this color.
- If a tuple of colors (string, float, rgb, etc), different labels will be plotted in different colors in the order specified.
- inlinebool, default: True
If
Truethe underlying contour is removed where the label is placed.- inline_spacingfloat, default: 5
Space in pixels to leave on each side of label when placing inline.
This spacing will be exact for labels at locations where the contour is straight, less so for labels on curved contours.
- fmtstr or dict, default: '%1.3f'
A format string for the label.
Alternatively, this can be a dictionary matching contour levels with arbitrary strings to use for each contour level (i.e., fmt[level]=string), or it can be any callable, such as a
Formatterinstance, that returns a string when called with a numeric contour level.- manualbool or iterable, default: False
If
True, contour labels will be placed manually using mouse clicks. Click the first button near a contour to add a label, click the second button (or potentially both mouse buttons at once) to finish adding labels. The third button can be used to remove the last label added, but only if labels are not inline. Alternatively, the keyboard can be used to select label locations (enter to end label placement, delete or backspace act like the third mouse button, and any other key will select a label location).manual can also be an iterable object of (x, y) tuples. Contour labels will be created as if mouse is clicked at each (x, y) position.
- rightside_upbool, default: True
If
True, label rotations will always be plus or minus 90 degrees from level.- use_clabeltextbool, default: False
If
True,ClabelTextclass (instead ofText) is used to create labels.ClabelTextrecalculates rotation angles of texts during the drawing time, therefore this can be used if aspect of the axes changes.- zorderfloat or None, default:
(2 + contour.get_zorder()) zorder of the contour labels.
Returns: - labels
A list of
Textinstances for the labels.
-
get_label_coords(self, distances, XX, YY, ysize, lw)[source]¶ Return x, y, and the index of a label location.
Labels are plotted at a location with the smallest deviation of the contour from a straight line unless there is another label nearby, in which case the next best place on the contour is picked up. If all such candidates are rejected, the beginning of the contour is chosen.
-
locate_label(self, linecontour, labelwidth)[source]¶ Find good place to draw a label (relatively flat part of the contour).
-
print_label(self, linecontour, labelwidth)[source]¶ Return whether a contour is long enough to hold a label.
-
-
class
matplotlib.contour.ContourSet(ax, *args, levels=None, filled=False, linewidths=None, linestyles=None, hatches=None, alpha=None, origin=None, extent=None, cmap=None, colors=None, norm=None, vmin=None, vmax=None, extend='neither', antialiased=None, nchunk=0, locator=None, transform=None, **kwargs)[source]¶ Bases:
matplotlib.cm.ScalarMappable,matplotlib.contour.ContourLabelerStore a set of contour lines or filled regions.
User-callable method:
clabelParameters: - ax
Axes - levels[level0, level1, ..., leveln]
A list of floating point numbers indicating the contour levels.
- allsegs[level0segs, level1segs, ...]
List of all the polygon segments for all the levels. For contour lines
len(allsegs) == len(levels), and for filled contour regionslen(allsegs) = len(levels)-1. The lists should look likelevel0segs = [polygon0, polygon1, ...] polygon0 = [[x0, y0], [x1, y1], ...]
- allkinds
Noneor [level0kinds, level1kinds, ...] Optional list of all the polygon vertex kinds (code types), as described and used in Path. This is used to allow multiply- connected paths such as holes within filled polygons. If not
None,len(allkinds) == len(allsegs). The lists should look likelevel0kinds = [polygon0kinds, ...] polygon0kinds = [vertexcode0, vertexcode1, ...]
If allkinds is not
None, usually all polygons for a particular contour level are grouped together so thatlevel0segs = [polygon0]andlevel0kinds = [polygon0kinds].- **kwargs
Keyword arguments are as described in the docstring of
contour.
Attributes: - ax
The axes object in which the contours are drawn.
- collections
A silent_list of LineCollections or PolyCollections.
- levels
Contour levels.
- layers
Same as levels for line contours; half-way between levels for filled contours. See
_process_colors().
Draw contour lines or filled regions, depending on whether keyword arg filled is
False(default) orTrue.Call signature:
ContourSet(ax, levels, allsegs, [allkinds], **kwargs)
Parameters: - ax
Axes The
Axesobject to draw on.- levels[level0, level1, ..., leveln]
A list of floating point numbers indicating the contour levels.
- allsegs[level0segs, level1segs, ...]
List of all the polygon segments for all the levels. For contour lines
len(allsegs) == len(levels), and for filled contour regionslen(allsegs) = len(levels)-1. The lists should look likelevel0segs = [polygon0, polygon1, ...] polygon0 = [[x0, y0], [x1, y1], ...]
- allkinds[level0kinds, level1kinds, ...], optional
Optional list of all the polygon vertex kinds (code types), as described and used in Path. This is used to allow multiply- connected paths such as holes within filled polygons. If not
None,len(allkinds) == len(allsegs). The lists should look likelevel0kinds = [polygon0kinds, ...] polygon0kinds = [vertexcode0, vertexcode1, ...]
If allkinds is not
None, usually all polygons for a particular contour level are grouped together so thatlevel0segs = [polygon0]andlevel0kinds = [polygon0kinds].- **kwargs
Keyword arguments are as described in the docstring of
contour.
-
property
ax¶
-
changed(self)[source]¶ Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.
-
find_nearest_contour(self, x, y, indices=None, pixel=True)[source]¶ Find the point in the contour plot that is closest to
(x, y).Parameters: - x, y: float
The reference point.
- indiceslist of int or None, default: None
Indices of contour levels to consider. If None (the default), all levels are considered.
- pixelbool, default: True
If True, measure distance in pixel (screen) space, which is useful for manual contour labeling; else, measure distance in axes space.
Returns: - contour
Collection The contour that is closest to
(x, y).- segmentint
The index of the
Pathin contour that is closest to(x, y).- indexint
The index of the path segment in segment that is closest to
(x, y).- xmin, yminfloat
The point in the contour plot that is closest to
(x, y).- dfloat
The distance from
(xmin, ymin)to(x, y).
-
legend_elements(self, variable_name='x', str_format=<class 'str'>)[source]¶ Return a list of artists and labels suitable for passing through to
legendwhich represent this ContourSet.The labels have the form "0 < x <= 1" stating the data ranges which the artists represent.
Parameters: - variable_namestr
The string used inside the inequality used on the labels.
- str_formatfunction: float -> str
Function used to format the numbers in the labels.
Returns: - artistsList[
Artist] A list of the artists.
- labelsList[str]
A list of the labels.
- ax
-
class
matplotlib.contour.QuadContourSet(ax, *args, levels=None, filled=False, linewidths=None, linestyles=None, hatches=None, alpha=None, origin=None, extent=None, cmap=None, colors=None, norm=None, vmin=None, vmax=None, extend='neither', antialiased=None, nchunk=0, locator=None, transform=None, **kwargs)[source]¶ Bases:
matplotlib.contour.ContourSetCreate and store a set of contour lines or filled regions.
User-callable method:
clabelAttributes: - ax
The axes object in which the contours are drawn.
- collections
A silent_list of LineCollections or PolyCollections.
- levels
Contour levels.
- layers
Same as levels for line contours; half-way between levels for filled contours. See
_process_colors()method.
Draw contour lines or filled regions, depending on whether keyword arg filled is
False(default) orTrue.Call signature:
ContourSet(ax, levels, allsegs, [allkinds], **kwargs)
Parameters: - ax
Axes The
Axesobject to draw on.- levels[level0, level1, ..., leveln]
A list of floating point numbers indicating the contour levels.
- allsegs[level0segs, level1segs, ...]
List of all the polygon segments for all the levels. For contour lines
len(allsegs) == len(levels), and for filled contour regionslen(allsegs) = len(levels)-1. The lists should look likelevel0segs = [polygon0, polygon1, ...] polygon0 = [[x0, y0], [x1, y1], ...]
- allkinds[level0kinds, level1kinds, ...], optional
Optional list of all the polygon vertex kinds (code types), as described and used in Path. This is used to allow multiply- connected paths such as holes within filled polygons. If not
None,len(allkinds) == len(allsegs). The lists should look likelevel0kinds = [polygon0kinds, ...] polygon0kinds = [vertexcode0, vertexcode1, ...]
If allkinds is not
None, usually all polygons for a particular contour level are grouped together so thatlevel0segs = [polygon0]andlevel0kinds = [polygon0kinds].- **kwargs
Keyword arguments are as described in the docstring of
contour.