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
First, we'll show the range of each colormap. Note that some seem to change more "quickly" than others. 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 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
Discussions

python - How to map number to color using matplotlib's colormap? - Stack Overflow
This way of using the API certainly looks much cleaner. 2019-12-11T05:50:44.713Z+00:00 ... Save this answer. ... Show activity on this post. ... Copyimport matplotlib.cm as cm import matplotlib as matplotlib def color_map_color(value, cmap_name='Wistia', vmin=0, vmax=1): # norm = ... More on stackoverflow.com
🌐 stackoverflow.com
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
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
Legend in matplotlib scatterplot doesn't match colormap of the plot
So there is a couple things. I'm not 100% sure what you are trying to do with the color. (I'm not familiar with what you were trying to do, so maybe it does work) but you have a qualitative color scheme that has 20 distinct colors, but you want to graph 25 items with it. When I have had to do this, I usually pick a continuous color scheme and just chop it in even parts. Maybe there is a more elegant way though! Your area calculation here: area = [10*n for n in range(len(points))] Would just return a list of [0,10,20,30....240] . Is that what you wanted? I'm thinking maybe you wanted it to be 10* how many points they had or something? Unsure exactly what you want, so I didn't touch it. But this just makes the size incrementally bigger as you go down the list(as they scored less points) so like a reverse ranking or something? Seems odd. If I was doing this quickly, I would just do: from bs4 import BeautifulSoup import requests import pandas as pd import matplotlib.pyplot as plt import numpy as np # scrape total stats url = 'https://www.basketball-reference.com/leagues/NBA_2020_totals.html#totals_stats::pts' response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') stats = soup.find_all('table') # convert table to dataframe data = pd.read_html(str(stats)) df = pd.DataFrame(data[0]) df['PTS'] = pd.to_numeric(df['PTS'], errors='coerce') df['FG'] = pd.to_numeric(df['FG'], errors='coerce') df['FG%'] = pd.to_numeric(df['FG%'], errors='coerce') df_sorted = df.sort_values(by=['PTS'], ascending=False) # data needed from dataframe df_graph = df_sorted.head(25).reset_index() df_graph['color'] = df_graph.index/len(df_graph.index) df_graph['area'] = 10* df_graph.index # visualise data fig, ax = plt.subplots(figsize=(14,6)) cmap = plt.get_cmap('gist_ncar') for index, row in df_graph.iterrows(): ax.scatter(row['FG'], row['FG%'], row['area'], c = cmap(row['color']), label = row['Player']) ax.legend(loc=5, bbox_to_anchor=(1.2, .5), fontsize=9) fig.tight_layout() plt.title('Top 25 Total Points Players FG/FG%/PTS Distribution') plt.show() A lot of times with a graph like this I'll see people have 2 legends, one for the color, and another for the size of the bubble. I tried a couple color schemes, but its really tough to have 25 qualitative colors. Can try a few more, maybe find some better ones. I'm not an expert so maybe not most efficient solution, but it works :) More on reddit.com
🌐 r/learnpython
1
3
October 30, 2019
🌐
Chrisholdgraf
chrisholdgraf.com › matplotlib › tutorials › colors › colormaps.html
Colormaps in Matplotlib — Matplotlib 2.0.0b1.post7580.dev0+ge487118 documentation
Those that have a smaller range of will accordingly have a smaller perceptual range. Note also that the function varies amongst the colormaps: some are approximately linear in and others are more curved. cmaps['Perceptually Uniform Sequential'] = ['viridis', 'plasma', 'inferno', 'magma'] cmaps['Sequential'] = [ 'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu', 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']
🌐
DataCamp
datacamp.com › tutorial › matplotlib-colormaps
Matplotlib Colormaps: Customizing Your Color Schemes | DataCamp
November 9, 2024 - Here, I am also specifying the number of intervals I want for my visual. from matplotlib.colors import LinearSegmentedColormap # Create a grid of values for a 2D Gaussian function x = np.linspace(-2, 2, 500) y = np.linspace(-2, 2, 500) X, Y = np.meshgrid(x, y) Z = np.exp(- (X**2 + Y**2)) # Define a custom colormap that transitions from blue to white to red colors = ['blue', 'white', 'red'] custom_cmap = LinearSegmentedColormap.from_list('blue_white_red', colors) # Adjust the number of color classes (discrete levels) # Specify the number of levels (e.g., 10 for 10 distinct color bands) num_clas
🌐
Matplotlib
matplotlib.org › 3.1.0 › tutorials › colors › colormap-manipulation.html
Creating Colormaps in Matplotlib — Matplotlib 3.1.0 documentation
May 18, 2019 - The second argument gives the size of the list of colors used to define the colormap, and below we use a modest value of 12 so there are not a lot of values to look at. import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap viridis = cm.get_cmap('viridis', 12) print(viridis)
🌐
Python Graph Gallery
python-graph-gallery.com › the python graph gallery › colors › how to use colormap in matplotlib
How to use Colormap in Matplotlib
1 week ago - Create a list of integers of the same length as the number of categories · Use the cmap object to map these integers to colors · In practice, we establish a mapping between the categories and the integers, then utilize the cmap object to translate ...
Find elsewhere
🌐
Matplotlib
matplotlib.org › stable › tutorials › colors › colormap-manipulation.html
Creating Colormaps in Matplotlib — Matplotlib 3.7.2 documentation
May 1, 2020 - colors = ["darkorange", "gold", "lawngreen", "lightseagreen"] cmap1 = LinearSegmentedColormap.from_list("mycmap", colors) If desired, the nodes of the colormap can be given as numbers between 0 and 1.
🌐
Matplotlib
matplotlib.org › 2.0.2 › examples › color › colormaps_reference.html
color example code: colormaps_reference.py — Matplotlib 2.0.2 documentation
For example:: color_list = plt.cm.Set3(np.linspace(0, 1, 12)) gives a list of RGB colors that are good for plotting a series of lines on a dark background. Miscellaneous: Colormaps that don't fit into the categories above. """ import numpy as np import matplotlib.pyplot as plt # Have colormaps separated into categories: # http://matplotlib.org/examples/color/colormaps_reference.html cmaps = [('Perceptually Uniform Sequential', [ 'viridis', 'plasma', 'inferno', 'magma']), ('Sequential', [ 'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu
🌐
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
🌐
Pythoncharts
pythoncharts.com › matplotlib › matplotlib-colors-colormaps
Python Charts - Colors and Color Maps in Matplotlib
You can also plot each of them out if you'd like, using a helper function like the below: 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]
🌐
Matplotlib
matplotlib.org › stable › users › explain › colors › colormap-manipulation.html
Creating Colormaps in Matplotlib — Matplotlib 3.11.2 documentation
First, getting a named colormap, most of which are listed in Choosing Colormaps in Matplotlib, may be done using matplotlib.colormaps, which returns a colormap object. The length of the list of colors used internally to define the colormap can be adjusted via Colormap.resampled.
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › matplotlib-colors-colormap-class-in-python
Matplotlib Colormaps - GeeksforGeeks
December 23, 2024 - This enhances the clarity and depth of your data representation, making it easier to interpret complex data patterns through effective color coding. To illustrate the core concept, here's a simple example that creates a colormap and applies it to a scatter plot: ... import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import ListedColormap x = np.random.rand(50) y = np.random.rand(50) colors = np.random.rand(50) cmap = ListedColormap(['red', 'green', 'blue']) plt.scatter(x, y, c=colors, cmap=cmap) plt.colorbar() plt.show()
🌐
Matplotlib
matplotlib.org › stable › gallery › color › custom_cmap.html
Create a colormap from a list of colors — Matplotlib 3.11.2 documentation
colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] # R -> G -> B n_bins = [3, 6, 10, 100] # Discretizes the interpolation into bins cmap_name = 'my_list' fig, axs = plt.subplots(2, 2, figsize=(6, 9)) fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05) for n_bin, ax in zip(n_bins, ...
🌐
Matplotlib
matplotlib.org › stable › tutorials › colors › colormaps.html
Matplotlib
May 25, 2022 - Matplotlib has support for visualizing information with a wide array of colors and colormaps.
🌐
Matplotlib
matplotlib.org › 3.1.1 › gallery › color › colormap_reference.html
Colormap reference — Matplotlib 3.1.2 documentation
May 1, 2020 - import numpy as np import ... np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) def plot_color_gradients(cmap_category, cmap_list): # Create figure and adjust figure height to number of colormaps nrows = len(cmap_list) figh = 0.35 + 0.15 + (nrows + ...
🌐
Medium
samjdedes.medium.com › exploring-matplotlibs-colormaps-65f216103277
Exploring Matplotlib's Colormaps - Sam Dedes - Medium
February 12, 2021 - Here I’ve added get_cmap , this function is an easy way to fetch information about Matplotlib colormaps. If you don’t have your own, make some dummy data to plot: labels = [‘One’, ‘Two’, ‘Three’, ‘Four’, ‘Five’, ‘Six’, ‘Seven’, ‘Eight’, ‘Nine’] data = [i for i in range(1,10)] Now scale the data, this determines the colors that correspond to the values in your data.
🌐
Scaler
scaler.com › home › topics › matplotlib › colormaps in matplotlib
Adding colormaps in matplotlib - Scaler Topics
November 9, 2022 - We can access these distinctive names using the get_cmap() function in matplotlib. name: The name of the colormap in a string format. Its default value is "viridis". lut: If lut isn’t None, it should be an integer that specifies the number of colors in the list used to define the colormap.