Getting individual colors from a color map in matplotlib

If you have a Colormap from

    cmap = matplotlib.cm.get_cmap('Spectral')

how can you get a particular colour out of it between 0 and 1, where 0.0 is the first colour in the map and 1.0 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 tuplet
    (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 = 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 bothJoe Kington and tcaswell for suggestions on how to improve the answer.)

From: stackoverflow.com/q/25408393

Back to homepage or read more recommendations: