How can I get the matplotlib rgb color, given the colormap name, BoundryNorm, and 'c='?
Got it. I created a colormap helper object containing a "get_rgb" function:
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
class MplColorHelper:
def __init__(self, cmap_name, start_val, stop_val):
self.cmap_name = cmap_name
self.cmap = plt.get_cmap(cmap_name)
self.norm = mpl.colors.Normalize(vmin=start_val, vmax=stop_val)
self.scalarMap = cm.ScalarMappable(norm=self.norm, cmap=self.cmap)
def get_rgb(self, val):
return self.scalarMap.to_rgba(val)
And example usage:
import numpy as np
# setup the plot
fig, ax = plt.subplots(1,1, figsize=(6,6))
# define the data between 0 and 20
NUM_VALS = 20
x = np.random.uniform(0, NUM_VALS, size=NUM_VALS)
y = np.random.uniform(0, NUM_VALS, size=NUM_VALS)
# define the color chart between 2 and 10 using the 'autumn_r' colormap, so
# y <= 2 is yellow
# y >= 10 is red
# 2 < y < 10 is between from yellow to red, according to its value
COL = MplColorHelper('autumn_r', 2, 10)
scat = ax.scatter(x,y,s=300, c=COL.get_rgb(y))
ax.set_title('Well defined discrete colors')
plt.show()
This would suffice.
In [22]:
def cstm_autumn_r(x):
return plt.cm.autumn_r((np.clip(x,2,10)-2)/8.)
In [23]:
cstm_autumn_r(1.4)
Out[23]:
(1.0, 1.0, 0.0, 1.0) #rgba yellow
In [24]:
cstm_autumn_r(10.5) #rgba red
Out[24]:
(1.0, 0.0, 0.0, 1.0)
In [25]:
%matplotlib inline
x = np.linspace(0, 15)
plt.scatter(x,x, c=cstm_autumn_r(x))