matplotlib.pyplot.contour#

matplotlib.pyplot.contour(*args,data=None,**kwargs)[source]#

Plot contour lines.

Call signature:

contour([X,Y,]Z,/,[levels],**kwargs)

The argumentsX,Y,Z are positional-only.

contour andcontourf draw contour lines and filled contours,respectively. Except as noted, function signatures and return valuesare the same for both versions.

Parameters:
X, Yarray-like, optional

The coordinates of the values inZ.

X andY must both be 2D with the same shape asZ (e.g.created vianumpy.meshgrid), or they must both be 1-D suchthatlen(X)==N is the number of columns inZ andlen(Y)==M is the number of rows inZ.

X andY must both be ordered monotonically.

If not given, they are assumed to be integer indices, i.e.X=range(N),Y=range(M).

Z(M, N) array-like

The height values over which the contour is drawn. Color-mapping iscontrolled bycmap,norm,vmin, andvmax.

levelsint or array-like, optional

Determines the number and positions of the contour lines / regions.

If an intn, useMaxNLocator, which triesto automatically choose no more thann+1 "nice" contour levelsbetween minimum and maximum numeric values ofZ.

If array-like, draw contour lines at the specified levels.The values must be in increasing order.

Returns:
QuadContourSet
Other Parameters:
corner_maskbool, default:rcParams["contour.corner_mask"] (default:True)

Enable/disable corner masking, which only has an effect ifZ isa masked array. IfFalse, any quad touching a masked point ismasked out. IfTrue, only the triangular corners of quadsnearest those points are always masked out, other triangularcorners comprising three unmasked points are contoured as usual.

colorscolor or list ofcolor, optional

The colors of the levels, i.e. the lines forcontour and theareas forcontourf.

The sequence is cycled for the levels in ascending order. If thesequence is shorter than the number of levels, it's repeated.

As a shortcut, a single color may be used in place of one-element lists, i.e.'red' instead of['red'] to color all levels with the same color.

Changed in version 3.10:Previously a single color had to be expressed as a string, but now anyvalid color format may be passed.

By default (valueNone), the colormap specified bycmapwill be used.

alphafloat, default: 1

The alpha blending value, between 0 (transparent) and 1 (opaque).

cmapstr orColormap, default:rcParams["image.cmap"] (default:'viridis')

The Colormap instance or registered colormap name used to map scalar datato colors.

This parameter is ignored ifcolors is set.

normstr orNormalize, optional

The normalization method used to scale scalar data to the [0, 1] rangebefore mapping to colors usingcmap. By default, a linear scaling isused, mapping the lowest value to 0 and the highest to 1.

If given, this can be one of the following:

This parameter is ignored ifcolors is set.

vmin, vmaxfloat, optional

When using scalar data and no explicitnorm,vmin andvmax definethe data range that the colormap covers. By default, the colormap coversthe complete value range of the supplied data. It is an error to usevmin/vmax when anorm instance is given (but using astrnormname together withvmin/vmax is acceptable).

Ifvmin orvmax are not given, the default color scaling is based onlevels.

This parameter is ignored ifcolors is set.

colorizerColorizer or None, default: None

The Colorizer object used to map color to data. If None, a Colorizerobject is created from anorm andcmap.

This parameter is ignored ifcolors is set.

origin{None, 'upper', 'lower', 'image'}, default: None

Determines the orientation and exact position ofZ by specifyingthe position ofZ[0,0]. This is only relevant, ifX,Yare not given.

  • None:Z[0,0] is at X=0, Y=0 in the lower left corner.

  • 'lower':Z[0,0] is at X=0.5, Y=0.5 in the lower left corner.

  • 'upper':Z[0,0] is at X=N+0.5, Y=0.5 in the upper leftcorner.

  • 'image': Use the value fromrcParams["image.origin"] (default:'upper').

extent(x0, x1, y0, y1), optional

Iforigin is notNone, thenextent is interpreted as inimshow: it gives the outer pixel boundaries. In this case, theposition of Z[0, 0] is the center of the pixel, not a corner. Iforigin isNone, then (x0,y0) is the position of Z[0, 0],and (x1,y1) is the position of Z[-1, -1].

This argument is ignored ifX andY are specified in the callto contour.

locatorticker.Locator subclass, optional

The locator is used to determine the contour levels if theyare not given explicitly vialevels.Defaults toMaxNLocator.

extend{'neither', 'both', 'min', 'max'}, default: 'neither'

Determines thecontourf-coloring of values that are outside thelevels range.

If 'neither', values outside thelevels range are not colored.If 'min', 'max' or 'both', color the values below, above or belowand above thelevels range.

Values belowmin(levels) and abovemax(levels) are mappedto the under/over values of theColormap. Note that mostcolormaps do not have dedicated colors for these by default, sothat the over and under values are the edge values of the colormap.You may want to set these values explicitly usingColormap.set_under andColormap.set_over.

Note

An existingQuadContourSet does not get notified ifproperties of its colormap are changed. Therefore, an explicitcallchanged() is needed after modifying thecolormap. The explicit call can be left out, if a colorbar isassigned to theQuadContourSet because it internally callschanged().

Example:

x=np.arange(1,10)y=x.reshape(-1,1)h=x*ycs=plt.contourf(h,levels=[10,30,50],colors=['#808080','#A0A0A0','#C0C0C0'],extend='both')cs.cmap.set_over('red')cs.cmap.set_under('blue')cs.changed()
xunits, yunitsregistered units, optional

Override axis units by specifying an instance of amatplotlib.units.ConversionInterface.

antialiasedbool, optional

Enable antialiasing, overriding the defaults. Forfilled contours, the default isFalse. For line contours,it is taken fromrcParams["lines.antialiased"] (default:True).

nchunkint >= 0, optional

If 0, no subdivision of the domain. Specify a positive integer todivide the domain into subdomains ofnchunk bynchunk quads.Chunking reduces the maximum length of polygons generated by thecontouring algorithm which reduces the rendering workload passedon to the backend and also requires slightly less RAM. It canhowever introduce rendering artifacts at chunk boundaries dependingon the backend, theantialiased flag and value ofalpha.

linewidthsfloat or array-like, default:rcParams["contour.linewidth"] (default:None)

Only applies tocontour.

The line width of the contour lines.

If a number, all levels will be plotted with this linewidth.

If a sequence, the levels in ascending order will be plotted withthe linewidths in the order specified.

If None, this falls back torcParams["lines.linewidth"] (default:1.5).

linestyles{None, 'solid', 'dashed', 'dashdot', 'dotted'}, optional

Only applies tocontour.

Iflinestyles isNone, the default is 'solid' unless the lines aremonochrome. In that case, negative contours will instead take theirlinestyle from thenegative_linestyles argument.

linestyles can also be an iterable of the above strings specifying a setof linestyles to be used. If this iterable is shorter than the number ofcontour levels it will be repeated as necessary.

negative_linestyles{None, 'solid', 'dashed', 'dashdot', 'dotted'}, optional

Only applies tocontour.

Iflinestyles isNone and the lines are monochrome, this argumentspecifies the line style for negative contours.

Ifnegative_linestyles isNone, the default is taken fromrcParams["contour.negative_linestyle"] (default:'dashed').

negative_linestyles can also be an iterable of the above stringsspecifying a set of linestyles to be used. If this iterable is shorter thanthe number of contour levels it will be repeated as necessary.

hatcheslist[str], optional

Only applies tocontourf.

A list of cross hatch patterns to use on the filled areas.If None, no hatching will be added to the contour.

algorithm{'mpl2005', 'mpl2014', 'serial', 'threaded'}, optional

Which contouring algorithm to use to calculate the contour lines andpolygons. The algorithms are implemented inContourPy, consult theContourPy documentation forfurther information.

The default is taken fromrcParams["contour.algorithm"] (default:'mpl2014').

clip_pathPatch orPath orTransformedPath

Set the clip path. Seeset_clip_path.

Added in version 3.8.

dataindexable object, optional

If given, all parameters also accept a strings, which isinterpreted asdata[s] ifs is a key indata.

rasterizedbool, optional

Only applies tocontourf.Rasterize the contour plot when drawing vector graphics. This canspeed up rendering and produce smaller files for large data sets.See alsoRasterization for vector graphics.

Notes

  1. contourf differs from the MATLAB version in that it does not drawthe polygon edges. To draw edges, add line contours with calls tocontour.

  2. contourf fills intervals that are closed at the top; that is, forboundariesz1 andz2, the filled region is:

    z1<Z<=z2

    except for the lowest interval, which is closed on both sides (i.e.it includes the lowest value).

  3. contour andcontourf use amarching squares algorithm tocompute contour locations. More information can be found inContourPy documentation.

Examples usingmatplotlib.pyplot.contour#

Interactive functions

Interactive functions

Contour corner mask

Contour corner mask

Contour Demo

Contour Demo

Contour image

Contour image

Contour Label Demo

Contour Label Demo

Contourf demo

Contourf demo

Contourf hatching

Contourf hatching

Blend transparency with color in 2D images

Blend transparency with color in 2D images

Contour plot of irregularly spaced data

Contour plot of irregularly spaced data