matplotlib.colorbar#

Colorbars are a visualization of the mapping from scalar values to colors.In Matplotlib they are drawn into a dedicatedAxes.

Note

Colorbars are typically created throughFigure.colorbar or its pyplotwrapperpyplot.colorbar, which internally useColorbar together withmake_axes_gridspec (forGridSpec-positioned Axes) ormake_axes (fornon-GridSpec-positioned Axes).

End-users most likely won't need to directly use this module's API.

classmatplotlib.colorbar.Colorbar(ax,mappable=None,*,alpha=None,location=None,extend=None,extendfrac=None,extendrect=False,ticks=None,format=None,values=None,boundaries=None,spacing='uniform',drawedges=False,label='',cmap=None,norm=None,orientation=None,ticklocation='auto')[source]#

Bases:object

Draw a colorbar in an existing Axes.

Typically, colorbars are created usingFigure.colorbar orpyplot.colorbar and associated withColorizingArtists (such as anAxesImage generated viaimshow).

In order to draw a colorbar not associated with other elements in thefigure, e.g. when showing a colormap by itself, one can create an emptyColorizingArtist, or directly passcmap andnorm instead ofmappabletoColorbar.

Useful public methods areset_label() andadd_lines().

Attributes:
axAxes

TheAxes instance in which the colorbar is drawn.

lineslist

A list ofLineCollection (empty if no lines were drawn).

dividersLineCollection

A LineCollection (empty ifdrawedges isFalse).

Parameters:
axAxes

TheAxes instance in which the colorbar is drawn.

mappableColorizingArtist

The mappable whose colormap and norm will be used.

To show the colors versus index instead of on a 0-1 scale, set themappable's norm tocolors.NoNorm().

alphafloat

The colorbar transparency between 0 (transparent) and 1 (opaque).

locationNone or {'left', 'right', 'top', 'bottom'}

Set the colorbar'sorientation andticklocation. Colorbars onthe left and right are vertical, colorbars at the top and bottomare horizontal. Theticklocation is the same aslocation, so iflocation is 'top', the ticks are on the top.orientation and/orticklocation can be provided as well and overrides the value set bylocation, but there will be an error for incompatible combinations.

Added in version 3.7.

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

Make pointed end(s) for out-of-range values (unless 'neither'). These areset for a given colormap using the colormap set_under and set_over methods.

extendfrac{None, 'auto', length, lengths}

If set toNone, both the minimum and maximum triangular colorbarextensions will have a length of 5% of the interior colorbar length (thisis the default setting).

If set to 'auto', makes the triangular colorbar extensions the same lengthsas the interior boxes (whenspacing is set to 'uniform') or the samelengths as the respective adjacent interior boxes (whenspacing is set to'proportional').

If a scalar, indicates the length of both the minimum and maximumtriangular colorbar extensions as a fraction of the interior colorbarlength. A two-element sequence of fractions may also be given, indicatingthe lengths of the minimum and maximum colorbar extensions respectively asa fraction of the interior colorbar length.

extendrectbool

IfFalse the minimum and maximum colorbar extensions will be triangular(the default). IfTrue the extensions will be rectangular.

ticksNone or list of ticks or Locator

If None, ticks are determined automatically from the input.

formatNone or str or Formatter

If None,ScalarFormatter is used.Format strings, e.g.,"%4.2e" or"{x:.2e}", are supported.An alternativeFormatter may be given instead.

drawedgesbool

Whether to draw lines at color boundaries.

labelstr

The label on the colorbar's long axis.

boundaries, valuesNone or a sequence

If unset, the colormap will be displayed on a 0-1 scale.If sequences,values must have a length 1 less thanboundaries. Foreach region delimited by adjacent entries inboundaries, the color mappedto the corresponding value invalues will be used. The size of eachregion is determined by thespacing parameter.Normally only useful for indexed colors (i.e.norm=NoNorm()) or otherunusual circumstances.

spacing{'uniform', 'proportional'}

For discrete colorbars (BoundaryNorm or contours), 'uniform' gives eachcolor the same space; 'proportional' makes the space proportional to thedata interval.

Other Parameters:
cmapColormap, default:rcParams["image.cmap"] (default:'viridis')

The colormap to use. This parameter is ignored, unlessmappable isNone.

normNormalize

The normalization to use. This parameter is ignored, unlessmappableis None.

orientationNone or {'vertical', 'horizontal'}

If None, use the value determined bylocation. If bothorientation andlocation are None then defaults to 'vertical'.

ticklocation{'auto', 'left', 'right', 'top', 'bottom'}

The location of the colorbar ticks. Theticklocation must matchorientation. For example, a horizontal colorbar can only have ticksat the top or the bottom. If 'auto', the ticks will be the same aslocation, so a colorbar to the left will have ticks to the left. Iflocation is None, the ticks will be at the bottom for a horizontalcolorbar and at the right for a vertical.

add_lines(*args,**kwargs)[source]#

Draw lines on the colorbar.

The lines are appended to the listlines.

Parameters:
levelsarray-like

The positions of the lines.

colorscolor or list ofcolor

Either a single color applying to all lines or one color value foreach line.

linewidthsfloat or array-like

Either a single linewidth applying to all lines or one linewidthfor each line.

erasebool, default: True

Whether to remove any previously added lines.

Notes

Alternatively, this method can also be called with the signaturecolorbar.add_lines(contour_set,erase=True), in which caselevels,colors, andlinewidths are taken fromcontour_set.

drag_pan(button,key,x,y)[source]#
propertyformatter#

Major tick labelFormatter for the colorbar.

get_ticks(minor=False)[source]#

Return the ticks as a list of locations.

Parameters:
minorboolean, default: False

if True return the minor ticks.

propertylocator#

Major tickLocator for the colorbar.

propertylong_axis#

Axis that has decorations (ticks, etc) on it.

propertyminorformatter#

Minor tickFormatter for the colorbar.

propertyminorlocator#

Minor tickLocator for the colorbar.

minorticks_off()[source]#

Turn the minor ticks of the colorbar off.

minorticks_on()[source]#

Turn on colorbar minor ticks.

n_rasterize=50#
remove()[source]#

Remove this colorbar from the figure.

If the colorbar was created withuse_gridspec=True the previousgridspec is restored.

set_alpha(alpha)[source]#

Set the transparency between 0 (transparent) and 1 (opaque).

If an array is provided,alpha will be set to None to use thetransparency values associated with the colormap.

set_label(label,*,loc=None,**kwargs)[source]#

Add a label to the long axis of the colorbar.

Parameters:
labelstr

The label text.

locstr, optional

The location of the label.

  • For horizontal orientation one of {'left', 'center', 'right'}

  • For vertical orientation one of {'bottom', 'center', 'top'}

Defaults torcParams["xaxis.labellocation"] (default:'center') orrcParams["yaxis.labellocation"] (default:'center')depending on the orientation.

**kwargs

Keyword arguments are passed toset_xlabel /set_ylabel.Supported keywords arelabelpad andText properties.

set_ticklabels(ticklabels,*,minor=False,**kwargs)[source]#

[Discouraged] Set tick labels.

Discouraged

The use of this method is discouraged, because of the dependencyon tick positions. In most cases, you'll want to useset_ticks(positions,labels=labels) instead.

If you are using this method, you should always fix the tickpositions before, e.g. by usingColorbar.set_ticks or byexplicitly setting aFixedLocator on the long axisof the colorbar. Otherwise, ticks are free to move and thelabels may end up in unexpected positions.

Parameters:
ticklabelssequence of str or ofText

Texts for labeling each tick location in the sequence set byColorbar.set_ticks; the number of labels must match the numberof locations.

update_ticksbool, default: True

This keyword argument is ignored and will be removed.Deprecated

minorbool

If True, set minor ticks instead of major ticks.

**kwargs

Text properties for the labels.

set_ticks(ticks,*,labels=None,minor=False,**kwargs)[source]#

Set tick locations.

Parameters:
ticks1D array-like

List of tick locations.

labelslist of str, optional

List of tick labels. If not set, the labels show the data value.

minorbool, default: False

IfFalse, set the major ticks; ifTrue, the minor ticks.

**kwargs

Text properties for the labels. These take effect only if youpasslabels. In other cases, please usetick_params.

update_normal(mappable=None)[source]#

Update solid patches, lines, etc.

This is meant to be called when the norm of the image or contour plotto which this colorbar belongs changes.

If the norm on the mappable is different than before, this resets thelocator and formatter for the axis, so if these have been customized,they will need to be customized again. However, if the norm onlychanges values ofvmin,vmax orcmap then the old formatterand locator will be preserved.

update_ticks()[source]#

Set up the ticks and ticklabels. This should not be needed by users.

matplotlib.colorbar.ColorbarBase[source]#

alias ofColorbar

matplotlib.colorbar.make_axes(parents,location=None,orientation=None,fraction=0.15,shrink=1.0,aspect=20,**kwargs)[source]#

Create anAxes suitable for a colorbar.

The Axes is placed in the figure of theparents Axes, by resizing andrepositioningparents.

Parameters:
parentsAxes or iterable ornumpy.ndarray ofAxes

The Axes to use as parents for placing the colorbar.

locationNone or {'left', 'right', 'top', 'bottom'}

The location, relative to the parent Axes, where the colorbar Axesis created. It also determines theorientation of the colorbar(colorbars on the left and right are vertical, colorbars at the topand bottom are horizontal). If None, the location will come from theorientation if it is set (vertical colorbars on the right, horizontalones at the bottom), or default to 'right' iforientation is unset.

orientationNone or {'vertical', 'horizontal'}

The orientation of the colorbar. It is preferable to set thelocationof the colorbar, as that also determines theorientation; passingincompatible values forlocation andorientation raises an exception.

fractionfloat, default: 0.15

Fraction of original Axes to use for colorbar.

shrinkfloat, default: 1.0

Fraction by which to multiply the size of the colorbar.

aspectfloat, default: 20

Ratio of long to short dimensions.

padfloat, default: 0.05 if vertical, 0.15 if horizontal

Fraction of original Axes between colorbar and new image Axes.

anchor(float, float), optional

The anchor point of the colorbar Axes.Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal.

panchor(float, float), orFalse, optional

The anchor point of the colorbar parent Axes. IfFalse, the parentaxes' anchor will be unchanged.Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.

Returns:
caxAxes

The child Axes.

kwargsdict

The reduced keyword dictionary to be passed when creating the colorbarinstance.

matplotlib.colorbar.make_axes_gridspec(parent,*,location=None,orientation=None,fraction=0.15,shrink=1.0,aspect=20,**kwargs)[source]#

Create anAxes suitable for a colorbar.

The Axes is placed in the figure of theparent Axes, by resizing andrepositioningparent.

This function is similar tomake_axes and mostly compatible with it.Primary differences are

Parameters:
parentAxes

The Axes to use as parent for placing the colorbar.

locationNone or {'left', 'right', 'top', 'bottom'}

The location, relative to the parent Axes, where the colorbar Axesis created. It also determines theorientation of the colorbar(colorbars on the left and right are vertical, colorbars at the topand bottom are horizontal). If None, the location will come from theorientation if it is set (vertical colorbars on the right, horizontalones at the bottom), or default to 'right' iforientation is unset.

orientationNone or {'vertical', 'horizontal'}

The orientation of the colorbar. It is preferable to set thelocationof the colorbar, as that also determines theorientation; passingincompatible values forlocation andorientation raises an exception.

fractionfloat, default: 0.15

Fraction of original Axes to use for colorbar.

shrinkfloat, default: 1.0

Fraction by which to multiply the size of the colorbar.

aspectfloat, default: 20

Ratio of long to short dimensions.

padfloat, default: 0.05 if vertical, 0.15 if horizontal

Fraction of original Axes between colorbar and new image Axes.

anchor(float, float), optional

The anchor point of the colorbar Axes.Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal.

panchor(float, float), orFalse, optional

The anchor point of the colorbar parent Axes. IfFalse, the parentaxes' anchor will be unchanged.Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.

Returns:
caxAxes

The child Axes.

kwargsdict

The reduced keyword dictionary to be passed when creating the colorbarinstance.