Movatterモバイル変換


[0]ホーム

URL:


You are reading an old version of the documentation (v2.0.0). For the latest version seehttps://matplotlib.org/stable/api/colors_api.html
matplotlib

Navigation


Travis-CI:

Table Of Contents

Related Topics

This Page

Quick search

colors

For a visual representation of the matplotlib colormaps, see the“Color” section in the gallery.

matplotlib.colors

A module for converting numbers or color arguments toRGB orRGBA

RGB andRGBA are sequences of, respectively, 3 or 4 floats in therange 0-1.

This module includes functions and classes for color specificationconversions, and for mapping numbers to colors in a 1-D array of colors calleda colormap. Colormapping typically involves two steps: a data array is firstmapped onto the range 0-1 using an instance ofNormalize or of asubclass; then this number in the 0-1 range is mapped to a color using aninstance of a subclass ofColormap. Two are provided here:LinearSegmentedColormap, which is used to generate all the built-incolormap instances, but is also useful for making custom colormaps, andListedColormap, which is used for generating a custom colormap from alist of color specifications.

The module also provides functions for checking whether an object can beinterpreted as a color (is_color_like()), for converting such an objectto an RGBA tuple (to_rgba()) or to an HTML-like hex string in the#rrggbb format (to_hex()), and a sequence of colors to an(n,4)RGBA array (to_rgba_array()). Caching is used for efficiency.

Commands which take color arguments can use several formats to specifythe colors. For the basic built-in colors, you can use a single letter

  • b: blue
  • g: green
  • r: red
  • c: cyan
  • m: magenta
  • y: yellow
  • k: black
  • w: white

To use the colors that are part of the active color cycle in the current style,useC followed by a digit. For example:

  • C0: The first color in the cycle
  • C1: The second color in the cycle

Gray shades can be given as a string encoding a float in the 0-1 range, e.g.:

color='0.75'

For a greater range of colors, you have two options. You can specify thecolor using an html hex string, as in:

color='#eeefff'

(possibly specifying an alpha value as well), or you can pass an(r,g,b)or(r,g,b,a) tuple, where each ofr,g,b anda are in the range[0,1].

Finally, legal html names for colors, like ‘red’, ‘burlywood’ and ‘chartreuse’are supported.

classmatplotlib.colors.BoundaryNorm(boundaries,ncolors,clip=False)

Bases:matplotlib.colors.Normalize

Generate a colormap index based on discrete intervals.

UnlikeNormalize orLogNorm,BoundaryNorm maps values to integers instead of to theinterval 0-1.

Mapping to the 0-1 interval could have been done viapiece-wise linear interpolation, but using integers seemssimpler, and reduces the number of conversions back and forthbetween integer and floating point.

boundaries
a monotonically increasing sequence
ncolors
number of colors in the colormap to be used

If:

b[i]<=v<b[i+1]

then v is mapped to color j;as i varies from 0 to len(boundaries)-2,j goes from 0 to ncolors-1.

Out-of-range values are mappedto -1 if low and ncolors if high; these are convertedto valid indices byColormap.__call__() .If clip == True, out-of-range valuesare mapped to 0 if low and ncolors-1 if high.

inverse(value)
classmatplotlib.colors.Colormap(name,N=256)

Bases:object

Baseclass for all scalar to RGBA mappings.

Typically Colormap instances are used to convert data values (floats) fromthe interval[0,1] to the RGBA color that the respective Colormaprepresents. For scaling of data into the[0,1] interval seematplotlib.colors.Normalize. It is worth noting thatmatplotlib.cm.ScalarMappable subclasses make heavy use of thisdata->normalize->map-to-color processing chain.

Parameters:

name : str

The name of the colormap.

N : int

The number of rgb quantization levels.

colorbar_extend = None

When this colormap exists on a scalar mappable and colorbar_extendis not False, colorbar creation will pick upcolorbar_extend asthe default value for theextend keyword in thematplotlib.colorbar.Colorbar constructor.

is_gray()
set_bad(color='k',alpha=None)

Set color to be used for masked values.

set_over(color='k',alpha=None)

Set color to be used for high out-of-range values.Requires norm.clip = False

set_under(color='k',alpha=None)

Set color to be used for low out-of-range values.Requires norm.clip = False

classmatplotlib.colors.LightSource(azdeg=315,altdeg=45,hsv_min_val=0,hsv_max_val=1,hsv_min_sat=1,hsv_max_sat=0)

Bases:object

Create a light source coming from the specified azimuth and elevation.Angles are in degrees, with the azimuth measuredclockwise from north and elevation up from the zero plane of the surface.

Theshade() is used to produce “shaded” rgb values for a data array.shade_rgb() can be used to combine an rgb image withTheshade_rgb()Thehillshade() produces an illumination map of a surface.

Specify the azimuth (measured clockwise from south) and altitude(measured up from the plane of the surface) of the light sourcein degrees.

Parameters:

azdeg : number, optional

The azimuth (0-360, degrees clockwise from North) of the lightsource. Defaults to 315 degrees (from the northwest).

altdeg : number, optional

The altitude (0-90, degrees up from horizontal) of the lightsource. Defaults to 45 degrees from horizontal.

Notes

For backwards compatibility, the parametershsv_min_val,hsv_max_val,hsv_min_sat, andhsv_max_sat may be supplied atinitialization as well. However, these parameters will only be used if“blend_mode=’hsv’” is passed intoshade() orshade_rgb().See the documentation forblend_hsv() for more details.

blend_hsv(rgb,intensity,hsv_max_sat=None,hsv_max_val=None,hsv_min_val=None,hsv_min_sat=None)

Take the input data array, convert to HSV values in the given colormap,then adjust those color values to give the impression of a shadedrelief map with a specified light source. RGBA values are returned,which can then be used to plot the shaded image with imshow.

The color of the resulting image will be darkened by moving the (s,v)values (in hsv colorspace) toward (hsv_min_sat, hsv_min_val) in theshaded regions, or lightened by sliding (s,v) toward (hsv_max_sathsv_max_val) in regions that are illuminated. The default extremes arechose so that completely shaded points are nearly black (s = 1, v = 0)and completely illuminated points are nearly white (s = 0, v = 1).

Parameters:

rgb : ndarray

An MxNx3 RGB array of floats ranging from 0 to 1 (color image).

intensity : ndarray

An MxNx1 array of floats ranging from 0 to 1 (grayscale image).

hsv_max_sat : number, optional

The maximum saturation value that theintensity map can shift theoutput image to. Defaults to 1.

hsv_min_sat : number, optional

The minimum saturation value that theintensity map can shift theoutput image to. Defaults to 0.

hsv_max_val : number, optional

The maximum value (“v” in “hsv”) that theintensity map can shiftthe output image to. Defaults to 1.

hsv_min_val: number, optional

The minimum value (“v” in “hsv”) that theintensity map can shiftthe output image to. Defaults to 0.

Returns:

rgb : ndarray

An MxNx3 RGB array representing the combined images.

blend_overlay(rgb,intensity)

Combines an rgb image with an intensity map using “overlay” blending.

Parameters:

rgb : ndarray

An MxNx3 RGB array of floats ranging from 0 to 1 (color image).

intensity : ndarray

An MxNx1 array of floats ranging from 0 to 1 (grayscale image).

Returns:

rgb : ndarray

An MxNx3 RGB array representing the combined images.

blend_soft_light(rgb,intensity)

Combines an rgb image with an intensity map using “soft light”blending. Uses the “pegtop” formula.

Parameters:

rgb : ndarray

An MxNx3 RGB array of floats ranging from 0 to 1 (color image).

intensity : ndarray

An MxNx1 array of floats ranging from 0 to 1 (grayscale image).

Returns:

rgb : ndarray

An MxNx3 RGB array representing the combined images.

hillshade(elevation,vert_exag=1,dx=1,dy=1,fraction=1.0)

Calculates the illumination intensity for a surface using the definedazimuth and elevation for the light source.

Imagine an artificial sun placed at infinity in some azimuth andelevation position illuminating our surface. The parts of the surfacethat slope toward the sun should brighten while those sides facing awayshould become darker.

Parameters:

elevation : array-like

A 2d array (or equivalent) of the height values used to generate anillumination map

vert_exag : number, optional

The amount to exaggerate the elevation values by when calculatingillumination. This can be used either to correct for differences inunits between the x-y coordinate system and the elevationcoordinate system (e.g. decimal degrees vs meters) or to exaggerateor de-emphasize topographic effects.

dx : number, optional

The x-spacing (columns) of the inputelevation grid.

dy : number, optional

The y-spacing (rows) of the inputelevation grid.

fraction : number, optional

Increases or decreases the contrast of the hillshade. Valuesgreater than one will cause intermediate values to move closer tofull illumination or shadow (and clipping any values that movebeyond 0 or 1). Note that this is not visually or mathematicallythe same as vertical exaggeration.

Returns

——-

intensity : ndarray

A 2d array of illumination values between 0-1, where 0 iscompletely in shadow and 1 is completely illuminated.

shade(data,cmap,norm=None,blend_mode='overlay',vmin=None,vmax=None,vert_exag=1,dx=1,dy=1,fraction=1,**kwargs)

Combine colormapped data values with an illumination intensity map(a.k.a. “hillshade”) of the values.

Parameters:

data : array-like

A 2d array (or equivalent) of the height values used to generate ashaded map.

cmap :Colormap instance

The colormap used to color thedata array. Note that this must beaColormap instance. For example, rather thanpassing incmap='gist_earth', usecmap=plt.get_cmap('gist_earth') instead.

norm :Normalize instance, optional

The normalization used to scale values before colormapping. IfNone, the input will be linearly scaled between its min and max.

blend_mode : {‘hsv’, ‘overlay’, ‘soft’} or callable, optional

The type of blending used to combine the colormapped datavalues with the illumination intensity. Default is“overlay”. Note that for most topographic surfaces,“overlay” or “soft” appear more visually realistic. If auser-defined function is supplied, it is expected tocombine an MxNx3 RGB array of floats (ranging 0 to 1) withan MxNx1 hillshade array (also 0 to 1). (Call signaturefunc(rgb,illum,**kwargs)) Additional kwargs suppliedto this function will be passed on to theblend_modefunction.

vmin : scalar or None, optional

The minimum value used in colormappingdata. IfNone theminimum value indata is used. Ifnorm is specified, then thisargument will be ignored.

vmax : scalar or None, optional

The maximum value used in colormappingdata. IfNone themaximum value indata is used. Ifnorm is specified, then thisargument will be ignored.

vert_exag : number, optional

The amount to exaggerate the elevation values by when calculatingillumination. This can be used either to correct for differences inunits between the x-y coordinate system and the elevationcoordinate system (e.g. decimal degrees vs meters) or to exaggerateor de-emphasize topography.

dx : number, optional

The x-spacing (columns) of the inputelevation grid.

dy : number, optional

The y-spacing (rows) of the inputelevation grid.

fraction : number, optional

Increases or decreases the contrast of the hillshade. Valuesgreater than one will cause intermediate values to move closer tofull illumination or shadow (and clipping any values that movebeyond 0 or 1). Note that this is not visually or mathematicallythe same as vertical exaggeration.

Additional kwargs are passed on to the *blend_mode* function.

Returns:

rgba : ndarray

An MxNx4 array of floats ranging between 0-1.

shade_rgb(rgb,elevation,fraction=1.0,blend_mode='hsv',vert_exag=1,dx=1,dy=1,**kwargs)

Take the input RGB array (ny*nx*3) adjust their color valuesto given the impression of a shaded relief map with aspecified light source using the elevation (ny*nx).A new RGB array ((ny*nx*3)) is returned.

Parameters:

rgb : array-like

An MxNx3 RGB array, assumed to be in the range of 0 to 1.

elevation : array-like

A 2d array (or equivalent) of the height values used to generate ashaded map.

fraction : number

Increases or decreases the contrast of the hillshade. Valuesgreater than one will cause intermediate values to move closer tofull illumination or shadow (and clipping any values that movebeyond 0 or 1). Note that this is not visually or mathematicallythe same as vertical exaggeration.

blend_mode : {‘hsv’, ‘overlay’, ‘soft’} or callable, optional

The type of blending used to combine the colormapped data valueswith the illumination intensity. For backwards compatibility, thisdefaults to “hsv”. Note that for most topographic surfaces,“overlay” or “soft” appear more visually realistic. If auser-defined function is supplied, it is expected to combine anMxNx3 RGB array of floats (ranging 0 to 1) with an MxNx1 hillshadearray (also 0 to 1). (Call signaturefunc(rgb,illum,**kwargs))Additional kwargs supplied to this function will be passed on totheblend_mode function.

vert_exag : number, optional

The amount to exaggerate the elevation values by when calculatingillumination. This can be used either to correct for differences inunits between the x-y coordinate system and the elevationcoordinate system (e.g. decimal degrees vs meters) or to exaggerateor de-emphasize topography.

dx : number, optional

The x-spacing (columns) of the inputelevation grid.

dy : number, optional

The y-spacing (rows) of the inputelevation grid.

Additional kwargs are passed on to the *blend_mode* function.

Returns:

shaded_rgb : ndarray

An MxNx3 array of floats ranging between 0-1.

classmatplotlib.colors.LinearSegmentedColormap(name,segmentdata,N=256,gamma=1.0)

Bases:matplotlib.colors.Colormap

Colormap objects based on lookup tables using linear segments.

The lookup table is generated using linear interpolation for eachprimary color, with the 0-1 domain divided into any number ofsegments.

Create color map from linear mapping segments

segmentdata argument is a dictionary with a red, green and blueentries. Each entry should be a list ofx,y0,y1 tuples,forming rows in a table. Entries for alpha are optional.

Example: suppose you want red to increase from 0 to 1 overthe bottom half, green to do the same over the middle half,and blue over the top half. Then you would use:

cdict={'red':[(0.0,0.0,0.0),(0.5,1.0,1.0),(1.0,1.0,1.0)],'green':[(0.0,0.0,0.0),(0.25,0.0,0.0),(0.75,1.0,1.0),(1.0,1.0,1.0)],'blue':[(0.0,0.0,0.0),(0.5,0.0,0.0),(1.0,1.0,1.0)]}

Each row in the table for a given color is a sequence ofx,y0,y1 tuples. In each sequence,x must increasemonotonically from 0 to 1. For any input valuez fallingbetweenx[i] andx[i+1], the output value of a given colorwill be linearly interpolated betweeny1[i] andy0[i+1]:

rowi:xy0y1//rowi+1:xy0y1

Hence y0 in the first row and y1 in the last row are never used.

See also

LinearSegmentedColormap.from_list()Static method; factory function for generating asmoothly-varying LinearSegmentedColormap.

makeMappingArray()For information about making a mapping array.

staticfrom_list(name,colors,N=256,gamma=1.0)

Make a linear segmented colormap withname from a sequenceofcolors which evenly transitions from colors[0] at val=0to colors[-1] at val=1.N is the number of rgb quantizationlevels.Alternatively, a list of (value, color) tuples can be givento divide the range unevenly.

set_gamma(gamma)

Set a new gamma value and regenerate color map.

classmatplotlib.colors.ListedColormap(colors,name='from_list',N=None)

Bases:matplotlib.colors.Colormap

Colormap object generated from a list of colors.

This may be most useful when indexing directly into a colormap,but it can also be used to generate special colormaps for ordinarymapping.

Make a colormap from a list of colors.

colors
a list of matplotlib color specifications,or an equivalent Nx3 or Nx4 floating point array(N rgb or rgba values)
name
a string to identify the colormap
N

the number of entries in the map. The default isNone,in which case there is one colormap entry for eachelement in the list of colors. If:

N<len(colors)

the list will be truncated atN. If:

N>len(colors)

the list will be extended by repetition.

classmatplotlib.colors.LogNorm(vmin=None,vmax=None,clip=False)

Bases:matplotlib.colors.Normalize

Normalize a given value to the 0-1 range on a log scale

Ifvmin orvmax is not given, they are initialized from theminimum and maximum value respectively of the first inputprocessed. That is,__call__(A) callsautoscale_None(A).Ifclip isTrue and the given value falls outside the range,the returned value will be 0 or 1, whichever is closer.Returns 0 if:

vmin==vmax

Works with scalars or arrays, including masked arrays. Ifclip isTrue, masked values are set to 1; otherwise theyremain masked. Clipping silently defeats the purpose of settingthe over, under, and masked colors in the colormap, so it islikely to lead to surprises; therefore the default isclip =False.

autoscale(A)

Setvmin,vmax to min, max ofA.

autoscale_None(A)

autoscale only None-valued vmin or vmax

inverse(value)
classmatplotlib.colors.NoNorm(vmin=None,vmax=None,clip=False)

Bases:matplotlib.colors.Normalize

Dummy replacement for Normalize, for the case where wewant to use indices directly in aScalarMappable .

Ifvmin orvmax is not given, they are initialized from theminimum and maximum value respectively of the first inputprocessed. That is,__call__(A) callsautoscale_None(A).Ifclip isTrue and the given value falls outside the range,the returned value will be 0 or 1, whichever is closer.Returns 0 if:

vmin==vmax

Works with scalars or arrays, including masked arrays. Ifclip isTrue, masked values are set to 1; otherwise theyremain masked. Clipping silently defeats the purpose of settingthe over, under, and masked colors in the colormap, so it islikely to lead to surprises; therefore the default isclip =False.

inverse(value)
classmatplotlib.colors.Normalize(vmin=None,vmax=None,clip=False)

Bases:object

A class which, when called, can normalize data intothe[0.0,1.0] interval.

Ifvmin orvmax is not given, they are initialized from theminimum and maximum value respectively of the first inputprocessed. That is,__call__(A) callsautoscale_None(A).Ifclip isTrue and the given value falls outside the range,the returned value will be 0 or 1, whichever is closer.Returns 0 if:

vmin==vmax

Works with scalars or arrays, including masked arrays. Ifclip isTrue, masked values are set to 1; otherwise theyremain masked. Clipping silently defeats the purpose of settingthe over, under, and masked colors in the colormap, so it islikely to lead to surprises; therefore the default isclip =False.

autoscale(A)

Setvmin,vmax to min, max ofA.

autoscale_None(A)

autoscale only None-valued vmin or vmax

inverse(value)
staticprocess_value(value)

Homogenize the inputvalue for easy and efficient normalization.

value can be a scalar or sequence.

Returnsresult,is_scalar, whereresult is amasked array matchingvalue. Float dtypes are preserved;integer types with two bytes or smaller are converted tonp.float32, and larger types are converted to np.float.Preserving float32 when possible, and using in-place operations,can greatly improve speed for large arrays.

Experimental; we may want to add an option to force theuse of float32.

scaled()

return true if vmin and vmax set

classmatplotlib.colors.PowerNorm(gamma,vmin=None,vmax=None,clip=False)

Bases:matplotlib.colors.Normalize

Normalize a given value to the[0,1] interval with a power-lawscaling. This will clip any negative data points to 0.

autoscale(A)

Setvmin,vmax to min, max ofA.

autoscale_None(A)

autoscale only None-valued vmin or vmax

inverse(value)
classmatplotlib.colors.SymLogNorm(linthresh,linscale=1.0,vmin=None,vmax=None,clip=False)

Bases:matplotlib.colors.Normalize

The symmetrical logarithmic scale is logarithmic in both thepositive and negative directions from the origin.

Since the values close to zero tend toward infinity, there is aneed to have a range around zero that is linear. The parameterlinthresh allows the user to specify the size of this range(-linthresh,linthresh).

linthresh:The range within which the plot is linear (toavoid having the plot go to infinity around zero).

linscale:This allows the linear range (-linthresh tolinthresh)to be stretched relative to the logarithmic range. Itsvalue is the number of decades to use for each half of thelinear range. For example, whenlinscale == 1.0 (thedefault), the space used for the positive and negativehalves of the linear range will be equal to one decade inthe logarithmic range. Defaults to 1.

autoscale(A)

Setvmin,vmax to min, max ofA.

autoscale_None(A)

autoscale only None-valued vmin or vmax

inverse(value)
matplotlib.colors.from_levels_and_colors(levels,colors,extend='neither')

A helper routine to generate a cmap and a norm instance whichbehave similar to contourf’s levels and colors arguments.

Parameters:

levels : sequence of numbers

The quantization levels used to construct theBoundaryNorm.Valuesv are quantizized to leveli iflev[i]<=v<lev[i+1].

colors : sequence of colors

The fill color to use for each level. Ifextend is “neither” theremust ben_level-1 colors. For anextend of “min” or “max” addone extra color, and for anextend of “both” add two colors.

extend : {‘neither’, ‘min’, ‘max’, ‘both’}, optional

The behaviour when a value falls out of range of the given levels.Seecontourf() for details.

Returns:

(cmap, norm) : tuple containing aColormap and aNormalize instance

matplotlib.colors.get_named_colors_mapping()

Return the global mapping of names to named colors.

matplotlib.colors.hsv_to_rgb(hsv)

convert hsv values in a numpy array to rgb valuesall values assumed to be in range [0, 1]

Parameters:

hsv : (..., 3) array-like

All values assumed to be in range [0, 1]

Returns:

rgb : (..., 3) ndarray

Colors converted to RGB values in range [0, 1]

matplotlib.colors.is_color_like(c)

Return whetherc can be interpreted as an RGB(A) color.

matplotlib.colors.makeMappingArray(N,data,gamma=1.0)

Create anN -element 1-d lookup table

data represented by a list of x,y0,y1 mapping correspondences.Each element in this list represents how a value between 0 and 1(inclusive) represented by x is mapped to a corresponding valuebetween 0 and 1 (inclusive). The two values of y are to allowfor discontinuous mapping functions (say as might be found in asawtooth) where y0 represents the value of y for values of x<= to that given, and y1 is the value to be used for x > thanthat given). The list must start with x=0, end with x=1, andall values of x must be in increasing order. Values betweenthe given mapping points are determined by simple linear interpolation.

Alternatively, data can be a function mapping values between 0 - 1to 0 - 1.

The function returns an array “result” whereresult[x*(N-1)]gives the closest value for values of x between 0 and 1.

matplotlib.colors.rgb_to_hsv(arr)

convert float rgb values (in the range [0, 1]), in a numpy array to hsvvalues.

Parameters:

arr : (..., 3) array-like

All values must be in the range [0, 1]

Returns:

hsv : (..., 3) ndarray

Colors converted to hsv values in range [0, 1]

matplotlib.colors.to_hex(c,keep_alpha=False)

Convertc to a hex color.

Uses the #rrggbb format ifkeep_alpha is False (the default),#rrggbbaaotherwise.

matplotlib.colors.to_rgb(c)

Convertc to an RGB color, silently dropping the alpha channel.

matplotlib.colors.to_rgba(c,alpha=None)

Convertc to an RGBA color.

Ifalpha is notNone, it forces the alpha value, except ifc is“none” (case-insensitive), which always maps to(0,0,0,0).

matplotlib.colors.to_rgba_array(c,alpha=None)

Convertc to a (n, 4) array of RGBA colors.

Ifalpha is notNone, it forces the alpha value. Ifc is “none”(case-insensitive) or an empty list, an empty array is returned.

© Copyright 2002 - 2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the Matplotlib development team; 2012 - 2016 The Matplotlib development team. Last updated on Feb 20, 2017. Created usingSphinx 1.5.2.

[8]ページ先頭

©2009-2025 Movatter.jp