matplotlib.contour
¶These are classes to support contour plotting and labelling for the Axes 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)¶Bases: matplotlib.text.Text
Unlike 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 Text
instance at x, y
with string text.
Valid kwargs are
Property Description agg_filter
unknown alpha
float (0.0 transparent through 1.0 opaque) animated
[True | False] backgroundcolor
any matplotlib color bbox
FancyBboxPatch prop dict clip_box
a matplotlib.transforms.Bbox
instanceclip_on
[True | False] clip_path
[ ( Path
,Transform
) |Patch
| None ]color
any matplotlib color contains
a callable function family
or fontfamily or fontname or name[FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] figure
a matplotlib.figure.Figure
instancefontproperties
or font_propertiesa matplotlib.font_manager.FontProperties
instancegid
an id string horizontalalignment
or ha[ ‘center’ | ‘right’ | ‘left’ ] label
string or anything printable with ‘%s’ conversion. linespacing
float (multiple of font size) multialignment
[‘left’ | ‘right’ | ‘center’ ] path_effects
unknown picker
[None|float|boolean|callable] position
(x,y) rasterized
[True | False | None] rotation
[ angle in degrees | ‘vertical’ | ‘horizontal’ ] rotation_mode
unknown size
or fontsize[size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ | ‘xx-large’ ] sketch_params
unknown snap
unknown stretch
or fontstretch[a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘condensed’ | ‘semi-condensed’ | ‘normal’ | ‘semi-expanded’ | ‘expanded’ | ‘extra-expanded’ | ‘ultra-expanded’ ] style
or fontstyle[ ‘normal’ | ‘italic’ | ‘oblique’] text
string or anything printable with ‘%s’ conversion. transform
Transform
instanceurl
a url string usetex
unknown variant
or fontvariant[ ‘normal’ | ‘small-caps’ ] verticalalignment
or ma or va[ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] visible
[True | False] weight
or fontweight[a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | ‘book’ | ‘medium’ | ‘roman’ | ‘semibold’ | ‘demibold’ | ‘demi’ | ‘bold’ | ‘heavy’ | ‘extra bold’ | ‘black’ ] wrap
unknown x
float y
float zorder
any number
get_rotation
()¶matplotlib.contour.
ContourLabeler
¶Bases: object
Mixin to provide labelling capability to ContourSet
add_label_clabeltext
(x, y, rotation, lev, cvalue)¶Add contour label using ClabelText
class.
add_label_near
(x, y, inline=True, inline_spacing=5, transform=None)¶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.
calc_label_rot_and_inline
(slc, ind, lw, lc=None, spacing=5)¶This function calculates the appropriate label rotation given the linecontour coordinates in screen units, the index of the label location and the label width.
It will also break contour and calculate inlining if lc is not empty (lc defaults to the empty list if None). spacing is the space around the label in pixels to leave empty.
Do both of these tasks at once to avoid calling mlab.path_length multiple times, which is relatively costly.
The method used here involves calculating 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
(*args, **kwargs)¶Label a contour plot.
Call signature:
clabel(cs, **kwargs)
Adds labels to line contours in cs, where cs is a
ContourSet
object returned by
contour.
clabel(cs, v, **kwargs)
only labels contours listed in v.
Optional keyword arguments:
- fontsize:
- size in points or relative size e.g., ‘smaller’, ‘x-large’
- 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 matplotlib color args (string, float, rgb, etc), different labels will be plotted in different colors in the order specified
- inline:
- controls whether the underlying contour is removed or not. Default is True.
- inline_spacing:
- space in pixels to leave on each side of label when placing inline. Defaults to 5. This spacing will be exact for labels at locations where the contour is straight, less so for labels on curved contours.
- fmt:
- a format string for the label. Default is ‘%1.3f’ 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
Formatter
instance, that returns a string when called with a numeric contour level.- manual:
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 be an iterable object of x,y tuples. Contour labels will be created as if mouse is clicked at each x,y positions.
- rightside_up:
- if True (default), label rotations will always be plus or minus 90 degrees from level.
- use_clabeltext:
- if True (default is False), ClabelText class (instead of matplotlib.Text) is used to create labels. ClabelText recalculates rotation angles of texts during the drawing time, therefore this can be used if aspect of the axes changes.
get_label_coords
(distances, XX, YY, ysize, lw)¶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.
get_label_width
(lev, fmt, fsize)¶Return the width of the label in points.
get_real_label_width
(lev, fmt, fsize)¶This computes actual onscreen label width. This uses some black magic to determine onscreen extent of non-drawn label. This magic may not be very robust.
This method is not being used, and may be modified or removed.
get_text
(lev, fmt)¶get the text of the label
labels
(inline, inline_spacing)¶locate_label
(linecontour, labelwidth)¶Find a good place to plot a label (relatively flat part of the contour).
pop_label
(index=-1)¶Defaults to removing last label, but any index can be supplied
print_label
(linecontour, labelwidth)¶Return False if contours are too short for a label.
set_label_props
(label, text, color)¶set the label properties - color, fontsize, text
too_close
(x, y, lw)¶Return True if a label is already near this location.
matplotlib.contour.
ContourSet
(ax, *args, **kwargs)¶Bases: matplotlib.cm.ScalarMappable
, matplotlib.contour.ContourLabeler
Store a set of contour lines or filled regions.
User-callable method: clabel
_process_colors()
.Draw contour lines or filled regions, depending on whether keyword arg ‘filled’ is False (default) or True.
The first three arguments must be:
ax: axes object.
- 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
.level0segs = [polygon0, polygon1, …]
polygon0 = array_like [[x0,y0], [x1,y1], …]
- allkinds: None 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).
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].
Keyword arguments are as described in
matplotlib.contour.QuadContourSet.contour_doc
.
changed
()¶find_nearest_contour
(x, y, indices=None, pixel=True)¶Finds contour that is closest to a point. Defaults to measuring distance in pixels (screen space - useful for manual contour labeling), but this can be controlled via a keyword argument.
Returns a tuple containing the contour, segment, index of segment, x & y of segment point and distance to minimum point.
Optional keyword arguments:
- indices:
- Indexes of contour levels to consider when looking for nearest point. Defaults to using all levels.
- pixel:
- If True, measure distance in pixel space, if not, measure distance in axes space. Defaults to True.
get_alpha
()¶returns alpha to be applied to all ContourSet artists
legend_elements
(variable_name='x', str_format=<class 'str'>)¶Return a list of artist and labels suitable for passing through
to plt.legend()
which represent this ContourSet.
Args:
- variable_name: the string used inside the inequality used
- on the labels
str_format: function used to format the numbers in the labels
set_alpha
(alpha)¶sets alpha for all ContourSet artists
vmax
¶vmin
¶matplotlib.contour.
QuadContourSet
(ax, *args, **kwargs)¶Bases: matplotlib.contour.ContourSet
Create and store a set of contour lines or filled regions.
User-callable method: clabel()
_process_colors()
method.Draw contour lines or filled regions, depending on whether keyword arg ‘filled’ is False (default) or True.
The first three arguments must be:
ax: axes object.
- 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
.level0segs = [polygon0, polygon1, …]
polygon0 = array_like [[x0,y0], [x1,y1], …]
- allkinds: None 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).
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].
Keyword arguments are as described in
matplotlib.contour.QuadContourSet.contour_doc
.
contour_doc
= "\n Plot contours.\n\n :func:`~matplotlib.pyplot.contour` and\n :func:`~matplotlib.pyplot.contourf` draw contour lines and\n filled contours, respectively. Except as noted, function\n signatures and return values are the same for both versions.\n\n :func:`~matplotlib.pyplot.contourf` differs from the MATLAB\n version in that it does not draw the polygon edges.\n To draw edges, add line contours with\n calls to :func:`~matplotlib.pyplot.contour`.\n\n\n Call signatures::\n\n contour(Z)\n\n make a contour plot of an array *Z*. The level values are chosen\n automatically.\n\n ::\n\n contour(X,Y,Z)\n\n *X*, *Y* specify the (x, y) coordinates of the surface\n\n ::\n\n contour(Z,N)\n contour(X,Y,Z,N)\n\n contour up to *N* automatically-chosen levels.\n\n ::\n\n contour(Z,V)\n contour(X,Y,Z,V)\n\n draw contour lines at the values specified in sequence *V*,\n which must be in increasing order.\n\n ::\n\n contourf(..., V)\n\n fill the ``len(V)-1`` regions between the values in *V*,\n which must be in increasing order.\n\n ::\n\n contour(Z, **kwargs)\n\n Use keyword args to control colors, linewidth, origin, cmap ... see\n below for more details.\n\n *X* and *Y* must both be 2-D with the same shape as *Z*, or they\n must both be 1-D such that ``len(X)`` is the number of columns in\n *Z* and ``len(Y)`` is the number of rows in *Z*.\n\n ``C = contour(...)`` returns a\n :class:`~matplotlib.contour.QuadContourSet` object.\n\n Optional keyword arguments:\n\n *corner_mask*: [ *True* | *False* | 'legacy' ]\n Enable/disable corner masking, which only has an effect if *Z* is\n a masked array. If *False*, any quad touching a masked point is\n masked out. If *True*, only the triangular corners of quads\n nearest those points are always masked out, other triangular\n corners comprising three unmasked points are contoured as usual.\n If 'legacy', the old contouring algorithm is used, which is\n equivalent to *False* and is deprecated, only remaining whilst the\n new algorithm is tested fully.\n\n If not specified, the default is taken from\n rcParams['contour.corner_mask'], which is True unless it has\n been modified.\n\n *colors*: [ *None* | string | (mpl_colors) ]\n If *None*, the colormap specified by cmap will be used.\n\n If a string, like 'r' or 'red', all levels will be plotted in this\n color.\n\n If a tuple of matplotlib color args (string, float, rgb, etc),\n different levels will be plotted in different colors in the order\n specified.\n\n *alpha*: float\n The alpha blending value\n\n *cmap*: [ *None* | Colormap ]\n A cm :class:`~matplotlib.colors.Colormap` instance or\n *None*. If *cmap* is *None* and *colors* is *None*, a\n default Colormap is used.\n\n *norm*: [ *None* | Normalize ]\n A :class:`matplotlib.colors.Normalize` instance for\n scaling data values to colors. If *norm* is *None* and\n *colors* is *None*, the default linear scaling is used.\n\n *vmin*, *vmax*: [ *None* | scalar ]\n If not *None*, either or both of these values will be\n supplied to the :class:`matplotlib.colors.Normalize`\n instance, overriding the default color scaling based on\n *levels*.\n\n *levels*: [level0, level1, ..., leveln]\n A list of floating point numbers indicating the level\n curves to draw, in increasing order; e.g., to draw just\n the zero contour pass ``levels=[0]``\n\n *origin*: [ *None* | 'upper' | 'lower' | 'image' ]\n If *None*, the first value of *Z* will correspond to the\n lower left corner, location (0,0). If 'image', the rc\n value for ``image.origin`` will be used.\n\n This keyword is not active if *X* and *Y* are specified in\n the call to contour.\n\n *extent*: [ *None* | (x0,x1,y0,y1) ]\n\n If *origin* is not *None*, then *extent* is interpreted as\n in :func:`matplotlib.pyplot.imshow`: it gives the outer\n pixel boundaries. In this case, the position of Z[0,0]\n is the center of the pixel, not a corner. If *origin* is\n *None*, then (*x0*, *y0*) is the position of Z[0,0], and\n (*x1*, *y1*) is the position of Z[-1,-1].\n\n This keyword is not active if *X* and *Y* are specified in\n the call to contour.\n\n *locator*: [ *None* | ticker.Locator subclass ]\n If *locator* is *None*, the default\n :class:`~matplotlib.ticker.MaxNLocator` is used. The\n locator is used to determine the contour levels if they\n are not given explicitly via the *V* argument.\n\n *extend*: [ 'neither' | 'both' | 'min' | 'max' ]\n Unless this is 'neither', contour levels are automatically\n added to one or both ends of the range so that all data\n are included. These added ranges are then mapped to the\n special colormap values which default to the ends of the\n colormap range, but can be set via\n :meth:`matplotlib.colors.Colormap.set_under` and\n :meth:`matplotlib.colors.Colormap.set_over` methods.\n\n *xunits*, *yunits*: [ *None* | registered units ]\n Override axis units by specifying an instance of a\n :class:`matplotlib.units.ConversionInterface`.\n\n *antialiased*: [ *True* | *False* ]\n enable antialiasing, overriding the defaults. For\n filled contours, the default is *True*. For line contours,\n it is taken from rcParams['lines.antialiased'].\n\n *nchunk*: [ 0 | integer ]\n If 0, no subdivision of the domain. Specify a positive integer to\n divide the domain into subdomains of *nchunk* by *nchunk* quads.\n Chunking reduces the maximum length of polygons generated by the\n contouring algorithm which reduces the rendering workload passed\n on to the backend and also requires slightly less RAM. It can\n however introduce rendering artifacts at chunk boundaries depending\n on the backend, the *antialiased* flag and value of *alpha*.\n\n contour-only keyword arguments:\n\n *linewidths*: [ *None* | number | tuple of numbers ]\n If *linewidths* is *None*, the default width in\n ``lines.linewidth`` in ``matplotlibrc`` is used.\n\n If a number, all levels will be plotted with this linewidth.\n\n If a tuple, different levels will be plotted with different\n linewidths in the order specified.\n\n *linestyles*: [ *None* | 'solid' | 'dashed' | 'dashdot' | 'dotted' ]\n If *linestyles* is *None*, the default is 'solid' unless\n the lines are monochrome. In that case, negative\n contours will take their linestyle from the ``matplotlibrc``\n ``contour.negative_linestyle`` setting.\n\n *linestyles* can also be an iterable of the above strings\n specifying a set of linestyles to be used. If this\n iterable is shorter than the number of contour levels\n it will be repeated as necessary.\n\n contourf-only keyword arguments:\n\n *hatches*:\n A list of cross hatch patterns to use on the filled areas.\n If None, no hatching will be added to the contour.\n Hatching is supported in the PostScript, PDF, SVG and Agg\n backends only.\n\n\n Note: contourf fills intervals that are closed at the top; that\n is, for boundaries *z1* and *z2*, the filled region is::\n\n z1 < z <= z2\n\n There is one exception: if the lowest boundary coincides with\n the minimum value of the *z* array, then that minimum value\n will be included in the lowest interval.\n "¶