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 = matplotlib.cm.get_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.)

Answer from Ffisegydd on Stack Overflow
🌐
Matplotlib
matplotlib.org › stable › users › explain › colors › colormaps.html
Choosing Colormaps in Matplotlib — Matplotlib 3.11.2 documentation
# Default is 6 colormaps per subplot. dsub = _DSUBS.get(cmap_category, 6) nsubplots = int(np.ceil(len(cmap_list) / dsub)) # squeeze=False to handle similarly the case of a single subplot fig, axs = plt.subplots(nrows=nsubplots, squeeze=False, figsize=(7, 2.6*nsubplots)) for i, ax in enumerate(axs.flat): locs = [] # locations for text labels for j, cmap in enumerate(cmap_list[i*dsub:(i+1)*dsub]): # Get RGB values for colormap and convert the colormap in # CAM02-UCS colorspace.
🌐
Matplotlib
matplotlib.org › stable › gallery › color › colormap_reference.html
Colormap reference — Matplotlib 3.11.2 documentation
import matplotlib.pyplot as plt import numpy as np cmaps = [('Perceptually Uniform Sequential', [ 'viridis', 'plasma', 'inferno', 'magma', 'cividis']), ('Sequential', [ 'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu', 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']), ('Sequential (2)', [ 'gray', 'bone', 'pink', 'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia', 'hot', 'afmhot', 'gist_heat', 'copper']), ('Diverging', [ 'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismi
Discussions

python - Getting individual colors from a color map in matplotlib - Stack Overflow
If you have a Colormap cmap, for example: cmap = matplotlib.cm.get_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 More on stackoverflow.com
🌐 stackoverflow.com
Colormaps explained courtesy of matplotlib. You spend a lot of time on your simulations, make sure you spend a little bit of time selecting the correct colormap for your figures.
Id actually suggest this video: https://youtu.be/xAoljeRJ3lU More than that website. Since this gives a better explanation of which colormap to use More on reddit.com
🌐 r/CFD
17
45
October 30, 2020
How does color mapping in Matplotlib work?
Normally "c=" is used to assign a color, which makes perfect sense as that's what even documentation says, but why in the example below we can assign an array of numbers to "c=" and it does't throw an error, since array is not a color obviously? It's also clear in the documentation if c is an array of numbers. c: array-like or list of colors or color, optional The marker colors. Possible values: - A scalar or sequence of n numbers to be mapped to colors using cmap and norm. - A 2-D array in which the rows are RGB or RGBA. - A sequence of colors of length n. - A single color format string. (...) cmap: str or Colormap , default: rcParams["image.cmap"] (default: 'viridis') A Colormap instance or registered colormap name. cmap is only used if c is an array of floats. (...) norm: Normalize , default: None If c is an array of floats, norm is used to scale the color data, c**, in the range 0** to 1, in order to map into the colormap cmap. If None, use the default colors.Normalize . Basically cmap maps each value of c to a given color. For that, first it normalizes those values between [0,1], and then makes the correspondence, where 0 corresponds first color of the chosen color scheme, and 1 to the last one. More on reddit.com
🌐 r/learnpython
4
3
November 15, 2020
python - Defining the midpoint of a colormap in matplotlib - Stack Overflow
Input ----- cmap : The matplotlib colormap to be altered start : Offset from lowest point in the colormap's range. Defaults to 0.0 (no lower offset). Should be between 0.0 and `midpoint`. midpoint : The new center of the colormap. Defaults to 0.5 (no shift). Should be between 0.0 and 1.0. More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
github.com › pyapp-kit › cmap
GitHub - pyapp-kit/cmap: Scientific colormaps for python, with only numpy dependency · GitHub
With cmap, you can use any of the colormaps from matplotlib, cmocean, colorbrewer, crameri, seaborn, and a host of other collections in your python code, without having to install matplotlib or any other dependencies beyond numpy.
🌐
Matplotlib
matplotlib.org › stable › api › _as_gen › matplotlib.colors.Colormap.html
matplotlib.colors.Colormap — Matplotlib 3.11.2 documentation
Deprecated since version 3.11: Use cmap.with_extremes(bad=..., under=..., over=...) or Colormap(bad=..., under=..., over=...) instead.
Top answer
1 of 9
415

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 = matplotlib.cm.get_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.)

2 of 9
24

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
🌐
Bids
bids.github.io › colormap
matplotlib colormaps
To visualize matplotlib built-in colormaps: python -m viscm view jet · To visualize one of our colormaps: python -m viscm view path/to/colormap_script.py · To make a nice screenshot like the ones above: python -m viscm view CMAP --save MYFILE.png --quit · If you want to access the editor interface we used to make these colormaps and play around with designing your own variants: python -m viscm edit path/to/colormap_script.py ·
Find elsewhere
🌐
Matplotlib
matplotlib.org › stable › users › explain › colors › colormap-manipulation.html
Creating Colormaps in Matplotlib — Matplotlib 3.11.2 documentation
colors = ["darkorange", "gold", "lawngreen", "lightseagreen"] cmap1 = LinearSegmentedColormap.from_list("mycmap", colors)
🌐
Chrisholdgraf
chrisholdgraf.com › matplotlib › tutorials › colors › colormaps.html
Colormaps in Matplotlib — Matplotlib 2.0.0b1.post7580.dev0+ge487118 documentation
cmaps['Miscellaneous'] = [ 'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg', 'hsv', 'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar']
🌐
Purdue
docs.rcac.purdue.edu › workshops › matplotlib › colormaps
Colormaps - RCAC Documentation
April 9, 2026 - MatPlotLib has a great writeup ... looks like in greyscale. Using colormaps is quite simple: add the cmap='CMAP_NAME' option to the plotting function you are using and MatPlotLib will handle the rest....
🌐
Readthedocs
cmap-docs.readthedocs.io › en › latest › catalog
Colormap Catalog - cmap
We test against all of the named colormaps in matplotlib, so any 'name' that you can use with matplotlib.colormaps['name'] can also be passed to cmap.Colormap.
🌐
Reddit
reddit.com › r/learnpython › how does color mapping in matplotlib work?
r/learnpython on Reddit: How does color mapping in Matplotlib work?
November 15, 2020 -

I'm still a beginner therefore don't want to be getting too deep into this subject, but can someone explain what's happening with c=point_numbers, cmap=plt.get_cmap("Reds") in the below code?

Normally "c=" is used to assign a color, which makes perfect sense as that's what even documentation says, but why in the example below we can assign an array of numbers to "c=" and it does't throw an error, since array is not a color obviously?

Help on clearing this up would be much appreciated as I've spent quite few hours yesterday and today trying to look it up...

import matplotlib.pyplot as plt
from random import choice

class RandomWalk:

    '''A class to generate random walks'''

    def __init__(self, num_points=5000):
        '''Initialize attributes of walk'''

        self.num_points = num_points

        #All walks start from (0, 0).
        self.x_values = [0]
        self.y_values = [0]

        #Keep taking steps until the walk reaches the desired length (5000)
        while len(self.x_values) < self.num_points:

            #Decide in which direction and how far to go
            x_direction = choice([-1, 1])
            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_direction * x_distance

            y_direction = choice([-1, 1])
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_direction * y_distance

            #Reject moves that go nowhere
            if x_step == 0 and y_step == 0:
                continue
            
            #Calculate new position
            x = self.x_values[-1] + x_step
            y = self.y_values[-1] + y_step

            self.x_values.append(x)
            self.y_values.append(y)

my_first_rw = RandomWalk()

plt.style.use("classic")
fig, ax = plt.subplots()
point_numbers = range(my_first_rw.num_points)
ax.scatter(my_first_rw.x_values, my_first_rw.y_values,c=point_numbers, cmap=plt.get_cmap("Reds"), edgecolors="none", s=5)
plt.show()
Top answer
1 of 2
2
Normally "c=" is used to assign a color, which makes perfect sense as that's what even documentation says, but why in the example below we can assign an array of numbers to "c=" and it does't throw an error, since array is not a color obviously? It's also clear in the documentation if c is an array of numbers. c: array-like or list of colors or color, optional The marker colors. Possible values: - A scalar or sequence of n numbers to be mapped to colors using cmap and norm. - A 2-D array in which the rows are RGB or RGBA. - A sequence of colors of length n. - A single color format string. (...) cmap: str or Colormap , default: rcParams["image.cmap"] (default: 'viridis') A Colormap instance or registered colormap name. cmap is only used if c is an array of floats. (...) norm: Normalize , default: None If c is an array of floats, norm is used to scale the color data, c**, in the range 0** to 1, in order to map into the colormap cmap. If None, use the default colors.Normalize . Basically cmap maps each value of c to a given color. For that, first it normalizes those values between [0,1], and then makes the correspondence, where 0 corresponds first color of the chosen color scheme, and 1 to the last one.
2 of 2
1
A colormap is a map from from some set of numbers (in general integers [0,256] or reals on the interval [0,1]) to a colorspace, usually a subset of 3- or 4-dimensional space. Those are usually your reds, greens, and blues, and sometimes an alpha channel attached. So, if you specify a cmap, you can pass a sequence of numbers that all get mapped to actual colors in the form of RGBA arrays or whatever. cmap = plt.get_cmap(‘jet’) print(cmap(1)) # (0,0,.5178..., 1) print(cmap(256)) # (0.5, 0, 0, 1) print(cmap(257)) # (0.5, 0, 0, 1) The point of doing it this way is that if I’m plotting 20 lines, I want a systematic way to select colors that are all as distinguishable as possible without sitting down and manually writing blue, cyan, black, red, etc. so instead I pick a colormap and pass a sequence of numbers to it.
🌐
Matplotlib
matplotlib.org › stable › users › explain › colors › colormapnorms.html
Colormap normalization — Matplotlib 3.11.2 documentation
N = 100 X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] Z1 = np.exp(-X**2 - Y**2) Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) Z = (Z1 - Z2) * 2 fig, ax = plt.subplots(2, 1) pcm = ax[0].pcolormesh(X, Y, Z, norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03, vmin=-1.0, vmax=1.0, base=10), cmap='RdBu_r', shading='auto') fig.colorbar(pcm, ax=ax[0], extend='both') pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z), shading='auto') fig.colorbar(pcm, ax=ax[1], extend='both') plt.show()
🌐
Pythoncharts
pythoncharts.com › matplotlib › matplotlib-colors-colormaps
Python Charts - Colors and Color Maps in Matplotlib
import matplotlib as mpl from matplotlib import pyplot as plt import numpy as np cmaps = {} gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) def plot_color_gradients(category, cmap_list): # Create figure and adjust figure height to number of colormaps nrows = len(cmap_list) figh = 0.35 + 0.15 + (nrows + (nrows - 1) * 0.1) * 0.22 fig, axs = plt.subplots(nrows=nrows + 1, figsize=(6.4, figh)) fig.subplots_adjust(top=1 - 0.35 / figh, bottom=0.15 / figh, left=0.2, right=0.99) axs[0].set_title(f'{category} colormaps', fontsize=14) for ax, name in zip(axs, cmap_list): ax.imshow(gradient, aspect='auto', cmap=mpl.colormaps[name]) ax.text(-0.01, 0.5, name, va='center', ha='right', fontsize=10, transform=ax.transAxes) # Turn off *all* ticks & spines, not just the ones with colormaps.
Top answer
1 of 11
101

I know this is late to the game, but I just went through this process and came up with a solution that perhaps less robust than subclassing normalize, but much simpler. I thought it'd be good to share it here for posterity.

The function

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid

def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):
    '''
    Function to offset the "center" of a colormap. Useful for
    data with a negative min and positive max and you want the
    middle of the colormap's dynamic range to be at zero.

    Input
    -----
      cmap : The matplotlib colormap to be altered
      start : Offset from lowest point in the colormap's range.
          Defaults to 0.0 (no lower offset). Should be between
          0.0 and `midpoint`.
      midpoint : The new center of the colormap. Defaults to 
          0.5 (no shift). Should be between 0.0 and 1.0. In
          general, this should be  1 - vmax / (vmax + abs(vmin))
          For example if your data range from -15.0 to +5.0 and
          you want the center of the colormap at 0.0, `midpoint`
          should be set to  1 - 5/(5 + 15)) or 0.75
      stop : Offset from highest point in the colormap's range.
          Defaults to 1.0 (no upper offset). Should be between
          `midpoint` and 1.0.
    '''
    cdict = {
        'red': [],
        'green': [],
        'blue': [],
        'alpha': []
    }

    # regular index to compute the colors
    reg_index = np.linspace(start, stop, 257)

    # shifted index to match the data
    shift_index = np.hstack([
        np.linspace(0.0, midpoint, 128, endpoint=False), 
        np.linspace(midpoint, 1.0, 129, endpoint=True)
    ])

    for ri, si in zip(reg_index, shift_index):
        r, g, b, a = cmap(ri)

        cdict['red'].append((si, r, r))
        cdict['green'].append((si, g, g))
        cdict['blue'].append((si, b, b))
        cdict['alpha'].append((si, a, a))

    newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict)
    plt.register_cmap(cmap=newcmap)

    return newcmap

An example

biased_data = np.random.random_integers(low=-15, high=5, size=(37,37))

orig_cmap = matplotlib.cm.coolwarm
shifted_cmap = shiftedColorMap(orig_cmap, midpoint=0.75, name='shifted')
shrunk_cmap = shiftedColorMap(orig_cmap, start=0.15, midpoint=0.75, stop=0.85, name='shrunk')

fig = plt.figure(figsize=(6,6))
grid = AxesGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=0.5,
                label_mode="1", share_all=True,
                cbar_location="right", cbar_mode="each",
                cbar_size="7%", cbar_pad="2%")

# normal cmap
im0 = grid[0].imshow(biased_data, interpolation="none", cmap=orig_cmap)
grid.cbar_axes[0].colorbar(im0)
grid[0].set_title('Default behavior (hard to see bias)', fontsize=8)

im1 = grid[1].imshow(biased_data, interpolation="none", cmap=orig_cmap, vmax=15, vmin=-15)
grid.cbar_axes[1].colorbar(im1)
grid[1].set_title('Centered zero manually,\nbut lost upper end of dynamic range', fontsize=8)

im2 = grid[2].imshow(biased_data, interpolation="none", cmap=shifted_cmap)
grid.cbar_axes[2].colorbar(im2)
grid[2].set_title('Recentered cmap with function', fontsize=8)

im3 = grid[3].imshow(biased_data, interpolation="none", cmap=shrunk_cmap)
grid.cbar_axes[3].colorbar(im3)
grid[3].set_title('Recentered cmap with function\nand shrunk range', fontsize=8)

for ax in grid:
    ax.set_yticks([])
    ax.set_xticks([])

Results of the example:

2 of 11
61

Note that in matplotlib version 3.2+ the TwoSlopeNorm class was added. I think it covers your use case. It can be used like this:

from matplotlib import colors
divnorm=colors.TwoSlopeNorm(vmin=-5., vcenter=0., vmax=10)
pcolormesh(your_data, cmap="coolwarm", norm=divnorm)

In matplotlib 3.1 the class was called DivergingNorm.

🌐
Medium
medium.com › @stacyfuende › colormaps-in-python-faecd8010f6c
Colormaps in Python. Here are some alternative color maps… | by Stacy M | Medium
September 6, 2025 - Here are some alternative color maps (cmaps) you can use in your maps to convey different visual styles or highlight specific features. These are built into Matplotlib, and you can specify them in the cmap parameter:
🌐
Medium
medium.com › data-science › beautiful-custom-colormaps-with-matplotlib-5bab3d1f0e72
Beautiful custom colormaps with Matplotlib | by Kerry Halupka | TDS Archive | Medium
July 28, 2020 - Let’s create a continuous colormap containing all of the colors above. We’ll be using the matplotlib.colors function called LinearSegmentedColormap. This function accepts a dictionary with a red, green and blue entries. Each entry should be a list of x, y0, y1 tuples, forming rows in a table.
🌐
Python Graph Gallery
python-graph-gallery.com › the python graph gallery › colors › create and customise palettes in matplotlib
Create and customise palettes in Matplotlib
2 weeks ago - from matplotlib.colors import ListedColormap # Define your custom color palette custom_colors = ['#264653', '#2a9d8f', '#e9c46a', '#f4a261', '#e76f51'] # Create a ListedColormap custom_cmap = ListedColormap(custom_colors) custom_cmap
🌐
Python Graph Gallery
python-graph-gallery.com › the python graph gallery › colors › how to use colormap in matplotlib
How to use Colormap in Matplotlib
2 weeks ago - In practice, we establish a mapping between the categories and the integers, then utilize the cmap object to translate these integers into colors. ... import matplotlib.pyplot as plt import numpy as np import matplotlib.colors as mcolors # Generate sample data np.random.seed(0) x = np.random.rand(100) * 100 y = np.random.rand(100) * 100 categories = np.random.choice(["A", "B", "C", "D"], size=100) # Categorical data # Map categories to numbers category_mapping = {category: idx for idx, category in enumerate(np.unique(categories))} category_numbers = [category_mapping[cat] for cat in categories] # load the colormap cmap = load_cmap( "Acanthurus_triostegus", # Name of the palette keep_first_n=len(category_mapping), # Number of colors to keep ) # Plot the scatter plot fig, ax = plt.subplots(figsize=(8, 6)) ax.scatter(x, y, s=200, c=category_numbers, cmap=cmap) plt.show()