Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range values to pseudocolor

I have a certain array of floats (in Python) that might range from 0 to 100. I want to create a pseudo-color image so that the colors vary from green (corresponding to 0) to red (100). This is similar to pcolor from matplotlib. However, I do not want to use pcolor.

Is there a function like pseudocolorForValue(val,(minval,maxval)) which returns an RGB triple corresponding to the pseudo-color value for val? Also, is there a flexibility in this function to choose whether to display colors from green-to-red or from red-to-green?

Thanks, Nik

like image 986
Nik Avatar asked Jun 05 '12 16:06

Nik


1 Answers

You can access matplolib's built-in colormaps directly, which are exactly what pcolor uses to determine its colormapping. Each map takes in a float in the range [0, 1] and returns a 4 element tuple of floats in the range [0, 1] with the components (R, G, B, A). Here is an example of a function which returns an RGBA tuple using the standard jet colormap:

from matplotlib import cm

def pseudocolor(val, minval, maxmal):
    # Scale val to be in the range [0, 1]
    val = (val - minval) / (maxval - minval)
    # Return RGBA tuple from jet colormap
    return cm.jet(val)

pseudocolor(20, 0, 100)
# Returns: (0.0, 0.3, 1.0, 1.0)

pseudocolor(80, 0, 100)
# Returns: (1.0, 0.4074, 0.0, 1.0)

This would map to the color range shown in the image below.

enter image description here

One of the convenient features about this method is that you can easily switch to any one of the matplotlib colormaps by changing cm.jet to cm.rainbow, cm.nipy_spectral, cm.Accent, etc.

like image 54
Chris Mueller Avatar answered Sep 23 '22 02:09

Chris Mueller