piRSquared
piRSquared

Reputation: 294516

Color lookup with a matplotlib colormap

I need to look up the RGB values for arbitrary numbers from a colormap.

Assume I have a colormap 'spring'

from matplotlib import cm

c = cm.get_cmap('spring')

And now suppose I have a value from 0 to 1, I want to pluck the RGB values from c

import numpy as np

np.random.seed([3, 1415])
v = np.random.rand(1)

v

0.4449393091533107

How do map that to get the corresponding RGB?

If I look at

c._segmentdata

{'blue': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0)),
 'green': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)),
 'red': ((0.0, 1.0, 1.0), (1.0, 1.0, 1.0))}

... I'm at a loss as to what to do.

I've looked up this link https://matplotlib.org/users/colormapnorms.html

But this tells me how to do it for a whole 2d matrix.

Upvotes: 1

Views: 875

Answers (1)

sacuL
sacuL

Reputation: 51425

Unless I misunderstand what you're asking, you can do the following:

c(v[0])

This will give you the following RGBA array:

(1.0, 0.44313725490196076, 0.55686274509803924, 1.0)

So if you just want the RGB, you can just index it as necessary:

>>> c(v[0])[:3]
(1.0, 0.44313725490196076, 0.55686274509803924)

More info in the docs

Upvotes: 2

Related Questions