matplotlib.contour#

Classes to support contour plotting and labelling for the Axes class.

class matplotlib.contour.ContourLabeler[source]#

Bases: object

Mixin to provide labelling capability to ContourSet.

add_label(x, y, rotation, lev, cvalue)[source]#

Add a contour label, respecting whether use_clabeltext was set.

add_label_clabeltext(x, y, rotation, lev, cvalue)[source]#

[Deprecated] Add contour label with Text.set_transform_rotates_text.

Notes

Deprecated since version 3.8: Use add_label instead.

add_label_near(x, y, inline=True, inline_spacing=5, transform=None)[source]#

Add a label near the point (x, y).

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.

transformTransform or False, default: self.axes.transData

A transform applied to (x, y) before labeling. The default causes (x, y) to be interpreted as data coordinates. False is a synonym for IdentityTransform; i.e. (x, y) should be interpreted as display coordinates.

calc_label_rot_and_inline(slc, ind, lw, lc=None, spacing=5)[source]#

[Deprecated] 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.

Notes

Deprecated since version 3.8.

clabel(levels=None, *, fontsize=None, inline=True, inline_spacing=5, fmt=None, 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_size for 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 True the 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.

fmtFormatter or str or callable or dict, optional

How the levels are formatted:

  • If a Formatter, it is used to format all levels at once, using its Formatter.format_ticks method.

  • If a str, it is interpreted as a %-style format string.

  • If a callable, it is called with one level at a time and should return the corresponding label.

  • If a dict, it should directly map levels to labels.

The default is to use a standard ScalarFormatter.

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, use Text.set_transform_rotates_text to ensure that label rotation is updated whenever the Axes aspect changes.

zorderfloat or None, default: (2 + contour.get_zorder())

zorder of the contour labels.

Returns:
labels

A list of Text instances for the labels.

get_text(lev, fmt)[source]#

Get the text of the label.

labels(inline, inline_spacing)[source]#
locate_label(linecontour, labelwidth)[source]#

Find good place to draw a label (relatively flat part of the contour).

pop_label(index=-1)[source]#

Defaults to removing last label, but any index can be supplied

print_label(linecontour, labelwidth)[source]#

Return whether a contour is long enough to hold a label.

remove()[source]#
too_close(x, y, lw)[source]#

Return whether a label is already near this location.

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, negative_linestyles=None, clip_path=None, **kwargs)[source]#

Bases: ContourLabeler, Collection

Store a set of contour lines or filled regions.

User-callable method: clabel

Parameters:
axAxes
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 regions len(allsegs) = len(levels)-1. The lists should look like

level0segs = [polygon0, polygon1, ...]
polygon0 = [[x0, y0], [x1, y1], ...]
allkindsNone or [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 like

level0kinds = [polygon0kinds, ...]
polygon0kinds = [vertexcode0, vertexcode1, ...]

If allkinds is not None, usually all polygons for a particular contour level are grouped together so that level0segs = [polygon0] and level0kinds = [polygon0kinds].

**kwargs

Keyword arguments are as described in the docstring of contour.

Attributes:
axAxes

The Axes object in which the contours are drawn.

collectionssilent_list of PathCollections

[Deprecated]

levelsarray

The values of the contour levels.

layersarray

Same as levels for line contours; half-way between levels for filled contours. See ContourSet._process_colors.

Draw contour lines or filled regions, depending on whether keyword arg filled is False (default) or True.

Call signature:

ContourSet(ax, levels, allsegs, [allkinds], **kwargs)
Parameters:
axAxes

The Axes object 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 regions len(allsegs) = len(levels)-1. The lists should look like

level0segs = [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 like

level0kinds = [polygon0kinds, ...]
polygon0kinds = [vertexcode0, vertexcode1, ...]

If allkinds is not None, usually all polygons for a particular contour level are grouped together so that level0segs = [polygon0] and level0kinds = [polygon0kinds].

**kwargs

Keyword arguments are as described in the docstring of contour.

property allkinds#
property allsegs#
property alpha#
property antialiased[source]#
changed()[source]#

Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.

property collections[source]#

[Deprecated]

Notes

Deprecated since version 3.8:

draw(renderer)[source]#

Draw the Artist (and its children) using the given renderer.

This has no effect if the artist is not visible (Artist.get_visible returns False).

Parameters:
rendererRendererBase subclass.

Notes

This method is overridden in the Artist subclasses.

find_nearest_contour(x, y, indices=None, pixel=True)[source]#

Find the point in the contour plot that is closest to (x, y).

This method does not support filled contours.

Parameters:
x, yfloat

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:
pathint

The index of the path that is closest to (x, y). Each path corresponds to one contour level.

subpathint

The index within that closest path of the subpath that is closest to (x, y). Each subpath corresponds to one unbroken contour line.

indexint

The index of the vertices within that subpath that are closest to (x, y).

xmin, yminfloat

The point in the contour plot that is closest to (x, y).

d2float

The squared distance from (xmin, ymin) to (x, y).

get_transform()[source]#

Return the Transform instance used by this ContourSet.

legend_elements(variable_name='x', str_format=<class 'str'>)[source]#

Return a list of artists and labels suitable for passing through to legend which 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.

property linestyles#
set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, antialiased=<UNSET>, array=<UNSET>, capstyle=<UNSET>, clim=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, cmap=<UNSET>, color=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, gid=<UNSET>, hatch=<UNSET>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, mouseover=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, path_effects=<UNSET>, paths=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, urls=<UNSET>, visible=<UNSET>, zorder=<UNSET>)[source]#

Set multiple properties at once.

Supported properties are

Property

Description

agg_filter

a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image

alpha

array-like or scalar or None

animated

bool

antialiased or aa or antialiaseds

bool or list of bools

array

array-like or None

capstyle

CapStyle or {'butt', 'projecting', 'round'}

clim

(vmin: float, vmax: float)

clip_box

BboxBase or None

clip_on

bool

clip_path

Patch or (Path, Transform) or None

cmap

Colormap or str or None

color

color or list of RGBA tuples

edgecolor or ec or edgecolors

color or list of color or 'face'

facecolor or facecolors or fc

color or list of color

figure

Figure

gid

str

hatch

{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}

in_layout

bool

joinstyle

JoinStyle or {'miter', 'round', 'bevel'}

label

object

linestyle or dashes or linestyles or ls

str or tuple or list thereof

linewidth or linewidths or lw

float or list of floats

mouseover

bool

norm

Normalize or str or None

offset_transform or transOffset

Transform

offsets

(N, 2) or (2,) array-like

path_effects

list of AbstractPathEffect

paths

unknown

picker

None or bool or float or callable

pickradius

float

rasterized

bool

sketch_params

(scale: float, length: float, randomness: float)

snap

bool or None

transform

Transform

url

str

urls

list of str or None

visible

bool

zorder

float

property tcolors[source]#

[Deprecated]

Notes

Deprecated since version 3.8:

property tlinewidths[source]#

[Deprecated]

Notes

Deprecated since version 3.8:

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, negative_linestyles=None, clip_path=None, **kwargs)[source]#

Bases: ContourSet

Create and store a set of contour lines or filled regions.

This class is typically not instantiated directly by the user but by contour and contourf.

Attributes:
axAxes

The Axes object in which the contours are drawn.

collectionssilent_list of PathCollections

[Deprecated]

levelsarray

The values of the contour levels.

layersarray

Same as levels for line contours; half-way between levels for filled contours. See ContourSet._process_colors.

Draw contour lines or filled regions, depending on whether keyword arg filled is False (default) or True.

Call signature:

ContourSet(ax, levels, allsegs, [allkinds], **kwargs)
Parameters:
axAxes

The Axes object 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 regions len(allsegs) = len(levels)-1. The lists should look like

level0segs = [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 like

level0kinds = [polygon0kinds, ...]
polygon0kinds = [vertexcode0, vertexcode1, ...]

If allkinds is not None, usually all polygons for a particular contour level are grouped together so that level0segs = [polygon0] and level0kinds = [polygon0kinds].

**kwargs

Keyword arguments are as described in the docstring of contour.

set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, antialiased=<UNSET>, array=<UNSET>, capstyle=<UNSET>, clim=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, cmap=<UNSET>, color=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, gid=<UNSET>, hatch=<UNSET>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, mouseover=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, path_effects=<UNSET>, paths=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, urls=<UNSET>, visible=<UNSET>, zorder=<UNSET>)[source]#

Set multiple properties at once.

Supported properties are

Property

Description

agg_filter

a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image

alpha

array-like or scalar or None

animated

bool

antialiased or aa or antialiaseds

bool or list of bools

array

array-like or None

capstyle

CapStyle or {'butt', 'projecting', 'round'}

clim

(vmin: float, vmax: float)

clip_box

BboxBase or None

clip_on

bool

clip_path

Patch or (Path, Transform) or None

cmap

Colormap or str or None

color

color or list of RGBA tuples

edgecolor or ec or edgecolors

color or list of color or 'face'

facecolor or facecolors or fc

color or list of color

figure

Figure

gid

str

hatch

{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}

in_layout

bool

joinstyle

JoinStyle or {'miter', 'round', 'bevel'}

label

object

linestyle or dashes or linestyles or ls

str or tuple or list thereof

linewidth or linewidths or lw

float or list of floats

mouseover

bool

norm

Normalize or str or None

offset_transform or transOffset

Transform

offsets

(N, 2) or (2,) array-like

path_effects

list of AbstractPathEffect

paths

unknown

picker

None or bool or float or callable

pickradius

float

rasterized

bool

sketch_params

(scale: float, length: float, randomness: float)

snap

bool or None

transform

Transform

url

str

urls

list of str or None

visible

bool

zorder

float