matplotlibcolor-mapping

Set color limits for matplotlib colormap


I made a function to get the hex code given to a set of data as follows:

from matplotlib import cm, colors
def get_color(series_data, cmap='Reds'):
    color_map = cm.get_cmap(cmap, 20)
    f = lambda x: colors.rgb2hex(color_map(x/series_data.max())[:3])
    return series_data.apply(f)

The cm.get_cmap(cmap, 20) generates a matplotlib.colors.LinearSegmentedColormap object that is ranged from the minimum value of the input series_data to its maximum.

I cannot see how could I define the color limits for the data to be evaluated. For instance, what if I wanted to set constant color limits, defining as the minimum the value 0 and the maximum 100? How could I do that within my function?

I tried to substitute series_data.max() to 100 to control the max equivalent color (max), but I couldn't control the cmin.


Solution

  • The parameter of color_map needs to be scaled to the [0.,1.) range. For instance, if the minimum (maximum) color value needs to be obtained for the lo (hi) value:

    from matplotlib import cm, colors
    import pandas as pd
    
    def get_color(series_data, cmap='Reds', lo=None, hi=None):
        if lo is None:
            lo = series_data.min()
        if hi is None:
            hi = series_data.max()
        if lo == hi:
            raise Exception('Invalid range.')
        color_map = cm.get_cmap(cmap, 20)
        f = lambda x: colors.rgb2hex(color_map((x-lo)/(hi-lo))[:3])
        return series_data.apply(f)
    
    s = pd.Series(np.linspace(0,3,16))
    colz = get_color(s, lo=1, hi=2)
    for x, c in zip(s, colz):
        print('{:.2f} {}'.format(x,c))
    

    The sample output is

    0.00 #fff5f0
    0.20 #fff5f0
    0.40 #fff5f0
    0.60 #fff5f0
    0.80 #fff5f0
    1.00 #fff5f0
    1.20 #fdc7b0
    1.40 #fc8363
    1.60 #ed392b
    1.80 #af1117
    2.00 #67000d
    2.20 #67000d
    2.40 #67000d
    2.60 #67000d
    2.80 #67000d
    3.00 #67000d