Write a hex formatter

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 [6]:
def foo(x): return int(x*255)
foo(.75), foo(1), foo(0)

Out[6]:
(191, 255, 0)
In [7]:
def foo(x): return int(x*256)
foo(.75), foo(1), foo(0)

Out[7]:
(192, 256, 0)
In [8]:
def foo(x): return min(255,int(x*256))
foo(.75), foo(1), foo(0)

Out[8]:
(192, 255, 0)
In [10]:
def foo(x): return hex( min(255,int(x*256)) )[2:].zfill(2)
foo(.75), foo(1), foo(0)

Out[10]:
('c0', 'ff', '00')
In [11]:
def goo(r,g,b): return foo(r),foo(g),foo(b)
goo(.75,0,1)

Out[11]:
('c0', '00', 'ff')
In [12]:
def goo(r,g,b): return foo(r)+foo(g)+foo(b)
goo(.75,0,1)

Out[12]:
'c000ff'
In [14]:
def goo(r,g,b): return '#'+foo(r)+foo(g)+foo(b)
goo(.75,0,1)

Out[14]:
'#c000ff'
In [16]:
def goo(r,g,b): return '#'+foo(r)+foo(g)+foo(b)
goo(.8,1,.8)

Out[16]:
'#ccffcc'

Goal: make a color-map maker

In [24]:
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)
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 [21]:
periwinkle = [1,.5,1]
mauve = [.5,0,1]
mycm = makecm(0,100,periwinkle,mauve)

In [22]:
mycm(0)

Out[22]:
array([ 1. ,  0.5,  1. ])
In [23]:
mycm(100)

Out[23]:
array([ 0.5,  0. ,  1. ])
In [27]:
from numpy import *
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)
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 goo(*c)

return f

In [33]:
periwinkle = [1,.8,1]
mauve = [.5,0,1]
green = [0,.5,0]
mycm = makecm(0,100,periwinkle,green)

In [34]:
mycm(100)

Out[34]:
'#008000'
In [35]:
%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

In [40]:
header = '''<svg
xmlns="http://www.w3.org/2000/svg"
width="1000" height="800">
'''
footer = '</svg>'
ncircles = 80
r = random.rand
with open('circles.svg','w') as f:

# write circles
for i in range(ncircles):

circle  = '<circle cx="'
circle += str(r()*1000)
circle += '" cy="'
circle += str(r()*800)
circle += '" r="'
circle += str(r()*100)
circle += '" stroke="gray" stroke-width="3" fill-opacity="0.3" fill="'
circle += goo(*r(3))
circle += '" />'
print(circle,file=f)

print(footer,file=f)


In [ ]: