Getting individual colors from a color map in matplotlib

matplotlib get color from colormap
matplotlib colormap example
matplotlib set colormap
matplotlib custom colormap
matplotlib colors
matplotlib colormap tutorial
matplotlib scatter colormap
3d color map python

If you have a Colormap cmap, for example:

cmap ='Spectral')

How can you get a particular colour out of it between 0 and 1, where 0 is the first colour in the map and 1 is the last colour in the map?

Ideally, I would be able to get the middle colour in the map by doing:

>>> do_some_magic(cmap, 0.5) # Return an RGBA tuple
(0.1, 0.2, 0.3, 1.0)

You can do this with the code below, and the code in your question was actually very close to what you needed, all you have to do is call the cmap object you have.

import matplotlib

cmap ='Spectral')

rgba = cmap(0.5)
print(rgba) # (0.99807766255210428, 0.99923106502084169, 0.74602077638401709, 1.0)

For values outside of the range [0.0, 1.0] it will return the under and over colour (respectively). This, by default, is the minimum and maximum colour within the range (so 0.0 and 1.0). This default can be changed with cmap.set_under() and cmap.set_over().

For "special" numbers such as np.nan and np.inf the default is to use the 0.0 value, this can be changed using cmap.set_bad() similarly to under and over as above.

Finally it may be necessary for you to normalize your data such that it conforms to the range [0.0, 1.0]. This can be done using matplotlib.colors.Normalize simply as shown in the small example below where the arguments vmin and vmax describe what numbers should be mapped to 0.0 and 1.0 respectively.

import matplotlib

norm = matplotlib.colors.Normalize(vmin=10.0, vmax=20.0)

print(norm(15.0)) # 0.5

A logarithmic normaliser (matplotlib.colors.LogNorm) is also available for data ranges with a large range of values.

(Thanks to both Joe Kington and tcaswell for suggestions on how to improve the answer.)

Grabbing individual colors from color maps in matplotlib, After looking at various matplotlib functions, Rob and I finally found that it's really simple (and apparently undocumented as far as we can tell). Just choose your colormap (e.g. 'jet') and call it like a function with a value between 0 and 1: e.g. pylab. cm. jet(. List of named colors¶ This plots a list of the named colors supported in matplotlib. Note that xkcd colors are supported as well, but are not listed here for brevity. For more information on colors in matplotlib see. the Specifying Colors tutorial; the matplotlib.colors API; the Color Demo.

In order to get rgba integer value instead of float value, we can do

rgba = cmap(0.5,bytes=True)

So to simplify the code based on answer from Ffisegydd, the code would be like this:

#import colormap
from matplotlib import cm

#normalize item number values to colormap
norm = matplotlib.colors.Normalize(vmin=0, vmax=1000)

#colormap possible values = viridis, jet, spectral
rgba_color = cm.jet(norm(400),bytes=True) 

#400 is one of value between 0 and 1000

Seaborn heatmap tutorial (Python Data Visualization), How do I change the color of a heatmap in Python? Choosing Colormaps in Matplotlib¶ Matplotlib has a number of built-in colormaps accessible via There are also external libraries like and that have many extra colormaps. Here we briefly discuss how to choose between the many options.

To build on the solutions from Ffisegydd and amaliammr, here's an example where we make CSV representation for a custom colormap:

#! /usr/bin/env python3
import matplotlib
import numpy as np 

vmin = 0.1
vmax = 1000

norm = matplotlib.colors.Normalize(np.log10(vmin), np.log10(vmax))
lognum = norm(np.log10([.5, 2., 10, 40, 150,1000]))

cdict = {
        (0., 0, 0),
        (lognum[0], 0, 0),
        (lognum[1], 0, 0),
        (lognum[2], 1, 1),
        (lognum[3], 0.8, 0.8),
        (lognum[4], .7, .7),
    (lognum[5], .7, .7)
        (0., .6, .6),
        (lognum[0], 0.8, 0.8),
        (lognum[1], 1, 1),
        (lognum[2], 1, 1),
        (lognum[3], 0, 0),
        (lognum[4], 0, 0),
    (lognum[5], 0, 0)
        (0., 0, 0),
        (lognum[0], 0, 0),
        (lognum[1], 0, 0),
        (lognum[2], 0, 0),
        (lognum[3], 0, 0),
        (lognum[4], 0, 0),
    (lognum[5], 1, 1)

mycmap = matplotlib.colors.LinearSegmentedColormap('my_colormap', cdict, 256)   
norm = matplotlib.colors.LogNorm(vmin, vmax)
colors = {}
count = 0
step_size = 0.001
for value in np.arange(vmin, vmax+step_size, step_size):
    count += 1
    print("%d/%d %f%%" % (count, vmax*(1./step_size), 100.*count/(vmax*(1./step_size))))
    rgba = mycmap(norm(value), bytes=True)
    color = (rgba[0], rgba[1], rgba[2])
    if color not in colors.values():
        colors[value] = color

print ("value, red, green, blue")
for value in sorted(colors.keys()):
    rgb = colors[value]
    print("%s, %s, %s, %s" % (value, rgb[0], rgb[1], rgb[2]))

Matplotlib : What is the function of cmap in imshow?, is that each row contains three elements (red, green, blue) and the lower color limit is mapped to the first entry, the upper color limit is mapped to the last and data is mapped linearly to all colors that may appear in between the two. Getting colormaps and accessing their values¶ First, getting a named colormap, most of which are listed in Choosing Colormaps in Matplotlib requires the use of, which returns a matplotlib.colors.ListedColormap object. The second argument gives the size of the list of colors used to define the colormap, and below we use a

For completeness these are the cmap choices I encountered so far:

Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spring, spring_r, summer, summer_r, tab10, tab10_r, tab20, tab20_r, tab20b, tab20b_r, tab20c, tab20c_r, terrain, terrain_r, twilight, twilight_r, twilight_shifted, twilight_shifted_r, viridis, viridis_r, winter, winter_r

How does colormap work, For many applications, a perceptually uniform colormap is the best choice --- one in lightness and often saturation of color incrementally, often using a single hue​; Diverging: change in lightness and possibly saturation of two different colors that Default is 6 colormaps per subplot. dsub = _DSUBS.get(cmap_category,  import matplotlib.pyplot as plt colormapList = [0,5,10,12,10,8,14,15] plt.plot(colormapList) Expected outcome. I wish I can create different colormap like this to be able to use the imshow method for plotting image later. Matplotlib version. Operating System: Windows 7 Pro; Matplotlib Version: 2.0.2 (from source) Python Version: 3.6

Choosing Colormaps in Matplotlib, First, getting a named colormap, most of which are listed in Choosing Matplotlib requires the use of , which returns a matplotlib.​colors. Creating a colormap from a list of colors¶. Creating a colormap from a list of colors can be done with the from_list() method of LinearSegmentedColormap.You must pass a list of RGB tuples that define the mixture of colors from 0 to 1.

Creating Colormaps in Matplotlib, First, getting a named colormap, most of which are listed in Choosing matplotlib.colors import ListedColormap, LinearSegmentedColormap  matplotlib.colors ¶. A module for converting numbers or color arguments to RGB or RGBA. RGB and RGBA are sequences of, respectively, 3 or 4 floats in the range 0-1.. This module includes functions and classes for color specification conversions, and for mapping numbers to colors in a 1-D array of colors called a colormap.

Creating Colormaps in Matplotlib, Then, we will see how to extract individual colors (e.g., in RGB) from the colormap itself. Let us first creat an image. from matplotlib import imshow  Color maps in Matplotlib. Matplotlib provides colour maps to change the range of colours used in a plot. Changing the range of colours on a plot can be useful to show patterns within the data being displayed. Also, while the default colormap is functional, it's not particularly aesthetically pleasing.

  • Actually, for values less than 0 or more than 1 it will return the "over" or "under" color. By default it's the color at the bottom/top of the colormap, but that's changable. For example: cmap.set_under('red'); print cmap(0.0), cmap(-0.01)
  • Hi @Joe, thanks for the correction, I've modified my answer :)
  • There is also set_bad which define what in does for np.nan and np.inf iirc. You should mention the Normalize methods here as well.
  • Very useful information and why on earth is it impossible to find this in the documentation!?!
  • If this isn't working for anyone, and you see module 'matplotlib' has no attribute 'cm', try replacing the first two lines with import matplotlib.pyplot as plt; cmap ='Spectral')