matplotlib.colorbar#
Colorbars are a visualization of the mapping from scalar values to colors.
In Matplotlib they are drawn into a dedicated Axes.
Note
Colorbars are typically created through Figure.colorbar or its pyplot
wrapper pyplot.colorbar, which internally use Colorbar together with
make_axes_gridspec (for GridSpec-positioned Axes) or make_axes (for
non-GridSpec-positioned Axes).
End-users most likely won't need to directly use this module's API.
- class matplotlib.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:
objectDraw a colorbar in an existing Axes.
Typically, colorbars are created using
Figure.colorbarorpyplot.colorbarand associated withScalarMappables (such as anAxesImagegenerated viaimshow).In order to draw a colorbar not associated with other elements in the figure, e.g. when showing a colormap by itself, one can create an empty
ScalarMappable, or directly pass cmap and norm instead of mappable toColorbar.Useful public methods are
set_label()andadd_lines().- Attributes:
- ax
Axes The
Axesinstance in which the colorbar is drawn.- lineslist
A list of
LineCollection(empty if no lines were drawn).- dividers
LineCollection A LineCollection (empty if drawedges is
False).
- ax
- Parameters:
- ax
Axes The
Axesinstance in which the colorbar is drawn.- mappable
ScalarMappable The mappable whose colormap and norm will be used.
To show the colors versus index instead of on a 0-1 scale, set the mappable's norm to
colors.NoNorm().- alphafloat
The colorbar transparency between 0 (transparent) and 1 (opaque).
- locationNone or {'left', 'right', 'top', 'bottom'}
Set the colorbar's orientation and ticklocation. Colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal. The ticklocation is the same as location, so if location is 'top', the ticks are on the top. orientation and/or ticklocation can be provided as well and overrides the value set by location, 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 are set for a given colormap using the colormap set_under and set_over methods.
- extendfrac{None, 'auto', length, lengths}
If set to None, both the minimum and maximum triangular colorbar extensions will have a length of 5% of the interior colorbar length (this is the default setting).
If set to 'auto', makes the triangular colorbar extensions the same lengths as the interior boxes (when spacing is set to 'uniform') or the same lengths as the respective adjacent interior boxes (when spacing is set to 'proportional').
If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length.
- extendrectbool
If False the minimum and maximum colorbar extensions will be triangular (the default). If True 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,
ScalarFormatteris used. Format strings, e.g.,"%4.2e"or"{x:.2e}", are supported. An alternativeFormattermay 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 than boundaries. For each region delimited by adjacent entries in boundaries, the color mapped to the corresponding value in values will be used. The size of each region is determined by the spacing parameter. Normally only useful for indexed colors (i.e.
norm=NoNorm()) or other unusual circumstances.- spacing{'uniform', 'proportional'}
For discrete colorbars (
BoundaryNormor contours), 'uniform' gives each color the same space; 'proportional' makes the space proportional to the data interval.
- ax
- Other Parameters:
- cmap
Colormap, default:rcParams["image.cmap"](default:'viridis') The colormap to use. This parameter is ignored, unless mappable is None.
- norm
Normalize The normalization to use. This parameter is ignored, unless mappable is None.
- orientationNone or {'vertical', 'horizontal'}
If None, use the value determined by location. If both orientation and location are None then defaults to 'vertical'.
- ticklocation{'auto', 'left', 'right', 'top', 'bottom'}
The location of the colorbar ticks. The ticklocation must match orientation. For example, a horizontal colorbar can only have ticks at the top or the bottom. If 'auto', the ticks will be the same as location, so a colorbar to the left will have ticks to the left. If location is None, the ticks will be at the bottom for a horizontal colorbar and at the right for a vertical.
- cmap
- add_lines(*args, **kwargs)[source]#
Draw lines on the colorbar.
The lines are appended to the list
lines.- Parameters:
- levelsarray-like
The positions of the lines.
- colorscolor or list of color
Either a single color applying to all lines or one color value for each line.
- linewidthsfloat or array-like
Either a single linewidth applying to all lines or one linewidth for each line.
- erasebool, default: True
Whether to remove any previously added lines.
Notes
Alternatively, this method can also be called with the signature
colorbar.add_lines(contour_set, erase=True), in which case levels, colors, and linewidths are taken from contour_set.
- get_ticks(minor=False)[source]#
Return the ticks as a list of locations.
- Parameters:
- minorboolean, default: False
if True return the minor ticks.
- property long_axis#
Axis that has decorations (ticks, etc) on it.
- n_rasterize = 50#
- remove()[source]#
Remove this colorbar from the figure.
If the colorbar was created with
use_gridspec=Truethe previous gridspec 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 the transparency 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 to
rcParams["xaxis.labellocation"](default:'center') orrcParams["yaxis.labellocation"](default:'center') depending on the orientation.- **kwargs
Keyword arguments are passed to
set_xlabel/set_ylabel. Supported keywords are labelpad andTextproperties.
- set_ticklabels(ticklabels, *, minor=False, **kwargs)[source]#
[Discouraged] Set tick labels.
Discouraged
The use of this method is discouraged, because of the dependency on tick positions. In most cases, you'll want to use
set_ticks(positions, labels=labels)instead.If you are using this method, you should always fix the tick positions before, e.g. by using
Colorbar.set_ticksor by explicitly setting aFixedLocatoron the long axis of the colorbar. Otherwise, ticks are free to move and the labels may end up in unexpected positions.- Parameters:
- ticklabelssequence of str or of
Text Texts for labeling each tick location in the sequence set by
Colorbar.set_ticks; the number of labels must match the number of 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
Textproperties for the labels.
- ticklabelssequence of str or of
- 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
If
False, set the major ticks; ifTrue, the minor ticks.- **kwargs
Textproperties for the labels. These take effect only if you pass labels. 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 plot to which this colorbar belongs changes.
If the norm on the mappable is different than before, this resets the locator and formatter for the axis, so if these have been customized, they will need to be customized again. However, if the norm only changes values of vmin, vmax or cmap then the old formatter and locator will be preserved.
- matplotlib.colorbar.make_axes(parents, location=None, orientation=None, fraction=0.15, shrink=1.0, aspect=20, **kwargs)[source]#
Create an
Axessuitable for a colorbar.The Axes is placed in the figure of the parents Axes, by resizing and repositioning parents.
- Parameters:
- parents
Axesor iterable ornumpy.ndarrayofAxes 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 Axes is created. It also determines the orientation of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal). If None, the location will come from the orientation if it is set (vertical colorbars on the right, horizontal ones at the bottom), or default to 'right' if orientation is unset.
- orientationNone or {'vertical', 'horizontal'}
The orientation of the colorbar. It is preferable to set the location of the colorbar, as that also determines the orientation; passing incompatible values for location and orientation 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), or False, optional
The anchor point of the colorbar parent Axes. If False, the parent axes' anchor will be unchanged. Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.
- parents
- Returns:
- cax
Axes The child Axes.
- kwargsdict
The reduced keyword dictionary to be passed when creating the colorbar instance.
- cax
- matplotlib.colorbar.make_axes_gridspec(parent, *, location=None, orientation=None, fraction=0.15, shrink=1.0, aspect=20, **kwargs)[source]#
Create an
Axessuitable for a colorbar.The Axes is placed in the figure of the parent Axes, by resizing and repositioning parent.
This function is similar to
make_axesand mostly compatible with it. Primary differences aremake_axes_gridspecrequires the parent to have a subplotspec.make_axespositions the Axes in figure coordinates;make_axes_gridspecpositions it using a subplotspec.make_axesupdates the position of the parent.make_axes_gridspecreplaces the parent gridspec with a new one.
- Parameters:
- parent
Axes 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 Axes is created. It also determines the orientation of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal). If None, the location will come from the orientation if it is set (vertical colorbars on the right, horizontal ones at the bottom), or default to 'right' if orientation is unset.
- orientationNone or {'vertical', 'horizontal'}
The orientation of the colorbar. It is preferable to set the location of the colorbar, as that also determines the orientation; passing incompatible values for location and orientation 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), or False, optional
The anchor point of the colorbar parent Axes. If False, the parent axes' anchor will be unchanged. Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.
- parent
- Returns:
- cax
Axes The child Axes.
- kwargsdict
The reduced keyword dictionary to be passed when creating the colorbar instance.
- cax