How to extract hexadecimal color codes from a matplotlib colormap ?

If you are using matplotlib, a popular Python plotting library, to create visuals for your projects, you may sometimes need to extract the hexadecimal color codes from the colormap. You can easily do this by following these steps:

Matplotlib get_cmap() function

First, import Matplotlib and create a colormap object. Make sure to include an array of values between 0 and 1 to sample from the colormap:

import matplotlib.pyplot as plt

cmap = plt.cm.get_cmap('Spectral', 10)

colors = cmap(np.linspace(0,1,10))

Create a list of hexadecimal values

Then you can loop through the array of colors to get the desired hexadecimal values:

hex_colors = []

for color in colors:

    hex_color = matplotlib.colors.to_hex(color)

    hex_colors.append(hex_color)

Get each hexadecimal values

Finally, you can access each value in the list of hexadecimal values:

for i in range(len(hex_colors)):

    print("Hex code for color ", i, " is:", hex_colors)

By following these steps, you can easily extract the hexadecimal color codes from a Matplotlib colormap. This can be a helpful tool for creating visuals that are more vibrant and eye-catching.

References

Links Site
Choosing Colormaps in Matplotlib matplotlib.org
matplotlib.cm matplotlib.org
How to create a discrete colorbar with matplotlib ? en.moonbooks.org
to_hex matplotlib.org
rgb2hex matplotlib.org