pythonmatplotlibcolormap

How to extract RGB values for LinearSegmentedColormap


I'm trying to find the RGB values for the different matplotlib colormaps. This is relatively straightforward when the colormap is a ListedColorMap using the colors attribute:

for idd in range(0, 255, 1):
    value1 = int(255*col_map.colors[idd][0])
    value2 = int(255*col_map.colors[idd][1])
    value3 = int(255*col_map.colors[idd][2])

However, several colormaps (e.g. PiYG or hsv) are objects created from the class 'matplotlib.colors.LinearSegmentedColormap' that doesn't have the colors attribute. My question is whether there is any specific attribute or method able to extract the sought RGBs.


Solution

  • There aren't any attributes nor methods for LinearSegmentedColormap pertaining to RGB colors like ListedColormap, but you can extract it and retrieve as many samples as you'd like coming from the LinearSegmentedColormap. You would need numpy for this.

    import matplotlib.pyplot as plt # Assuming you already have it imported somewhere
    import numpy as np
    # The specified colormap, it can be any from the name argument
    ColorMap = plt.get_cmap("PiYG")
    Samples = 256 # Amount of samples you require
    Values = [ColorMap(i)[:3] for i in np.linspace(0,1,Samples)] # Retrieves 0-1 scale
    # Converts to 0–255 RGB integer tuples
    Rgb = [(int(r*255),int(g*255),int(b*255)) for r,g,b in Values]