RGB and Color Maps

RGB Color

Look at color selector in Inkscape or other graphics program.

Hexadecimal representation of integers

python hex function to generate #XXXXXX representation

In [1]:
hex(11)
Out[1]:
'0xb'
In [2]:
hex(11)[2:]
Out[2]:
'b'

to get leading zero when needed

In [3]:
hex(11)[2:].zfill(2)
Out[3]:
'0b'
In [4]:
hex(67)[2:].zfill(2)
Out[4]:
'43'

To map real interval [0,1] to integers 0 to 255 ...

In [5]:
def foo(x): 
    return int(x*255)
foo(.75), foo(1), foo(0)
Out[5]:
(191, 255, 0)
In [6]:
def foo(x): return int(x*256)
foo(.75), foo(1), foo(0)
Out[6]:
(192, 256, 0)
In [7]:
def foo(x): return min(255,int(x*256))
foo(.75), foo(1), foo(0)
Out[7]:
(192, 255, 0)
In [8]:
def foo(x): return hex( min(255,int(x*256)) )[2:].zfill(2)
foo(.75), foo(1), foo(0)
Out[8]:
('c0', 'ff', '00')
In [9]:
def goo(r,g,b): return foo(r),foo(g),foo(b)
goo(.75,0,1)
Out[9]:
('c0', '00', 'ff')
In [10]:
def goo(r,g,b): return foo(r)+foo(g)+foo(b)
goo(.75,0,1)
Out[10]:
'c000ff'
In [11]:
def goo(r,g,b): return '#'+foo(r)+foo(g)+foo(b)
goo(.75,0,1)
Out[11]:
'#c000ff'
In [12]:
def goo(r,g,b): return '#'+foo(r)+foo(g)+foo(b)
goo(.8,1,.8)
Out[12]:
'#ccffcc'

Lets make a colormap

These are maps (functions) from your data space to color space.

Linear segmented (i.e. piecewise linear) color maps also widely used.

2D color maps (from 2D data to a 2D surface in color space) also possible.

In [13]:
from numpy import *
def foo(x): return hex( min(255,int(x*256)) )[2:].zfill(2)
def goo(r,g,b): return '#'+foo(r)+foo(g)+foo(b)

#this linear interpolates between two arrays
def makecm(xlo,xhi,c0,c1):
    
    def f(x):
        h = (x-xlo)/(xhi-xlo)
        nc0 = array(c0)
        nc1 = array(c1)
        c = (1-h)*nc0 + h*nc1
        return c
    
    return f
In [14]:
periwinkle = [1,.5,1]
mauve = [.5,0,1]
mycm = makecm(0,100,periwinkle,mauve)
In [15]:
mycm(2)
Out[15]:
array([ 0.99,  0.49,  1.  ])
In [16]:
mycm(100)
Out[16]:
array([ 0.5,  0. ,  1. ])
In [17]:
%pylab inline
for x in linspace(0,100,300):
    plot([x,x],[0,1],color=mycm(x),lw=3)
Populating the interactive namespace from numpy and matplotlib

Lets try another color pair

In [18]:
periwinkle = [1,.8,1]
mauve = [.5,0,1]
green = [0,.5,0]
mycm = makecm(0,100,periwinkle,green)
In [19]:
mycm(100)
Out[19]:
array([ 0. ,  0.5,  0. ])
In [20]:
for x in linspace(0,100,300):
    plot([x,x],[0,1],color=mycm(x),lw=3)
In [ ]: