Skip to main content

Custom colormaps

From an excellent post here , we have a clear explanation of how to make custom colormaps. Under matplotlib there is a colors module which has a method called LinearSegmentedColormap that can create a colormap for your use.

First you need to make a color dictionary which looks like this:
cdict = {
'red' : ((0., 0., 0.), (0.5, 0.25, 0.25), (1., 1., 1.)),
'green': ((0., 1., 1.), (0.7, 0.0, 0.5), (1., 1., 1.)),
'blue' : ((0., 1., 1.), (0.5, 0.0, 0.0), (1., 1., 1.))
}
For each 'primary' additive color (rgb) you have to specify a tuple (...) which inturn is a collection of triples. Each triple defines a pivot point for that color in your color map.

The triple (0.7, 0.0, 0.5) for instance, means for 'green' when the normalized value is just below 0.7 the green component should be 0.0, and just above 0.7 the green component should be 0.5. This of course creates a discontinuity in the map at 0.7. To make a continuous map all the pivot points should have the same value above and below. So the triple (0.5, 0.25, 0.25) for 'red' means for values just above and below .5 the 'red' component will be .25 .

Values in between pivot points are linearly interpolated by the function matplotlib.colors.LinearSegmentedColormap.

A complete (and ugly) example is given below:



import pylab as m

cdict = {
'red' : ((0., 0., 0.), (0.5, 0.25, 0.25), (1., 1., 1.)),
'green': ((0., 1., 1.), (0.7, 0.0, 0.5), (1., 1., 1.)),
'blue' : ((0., 1., 1.), (0.5, 0.0, 0.0), (1., 1., 1.))
}
#generate the colormap with 1024 interpolated values
my_cmap = m.matplotlib.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)

#create a gaussian
x = m.arange(0, 50 , 1 , m.Float)
y = x[:,m.NewAxis]
x0 = y0 = x.size // 2
fwhm= x0/1.2
z = m.exp(-4*m.log(2)*((x-x0)**2+(y-y0)**2)/fwhm**2)

pcolormesh(z, cmap = my_cmap)
colorbar()
The api is more for reference, rather than learning.

Comments

  1. Thank you very much...you have very clearly explained what I was struggling to learn from terser sources.

    Paul

    ReplyDelete

Post a Comment

Popular posts from this blog

A note on Python's __exit__() and errors

Python's context managers are a very neat way of handling code that needs a teardown once you are done. Python objects have do have a destructor method ( __del__ ) called right before the last instance of the object is about to be destroyed. You can do a teardown there. However there is a lot of fine print to the __del__ method. A cleaner way of doing tear-downs is through Python's context manager , manifested as the with keyword. class CrushMe: def __init__(self): self.f = open('test.txt', 'w') def foo(self, a, b): self.f.write(str(a - b)) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.f.close() return True with CrushMe() as c: c.foo(2, 3) One thing that is important, and that got me just now, is error handling. I made the mistake of ignoring all those 'junk' arguments ( exc_type, exc_val, exc_tb ). I just skimmed the docs and what popped out is that you need to return True or...

Store numpy arrays in sqlite

Use numpy.getbuffer (or sqlite3.Binary ) in combination with numpy.frombuffer to lug numpy data in and out of the sqlite3 database: import sqlite3, numpy r1d = numpy.random.randn(10) con = sqlite3.connect(':memory:') con.execute("CREATE TABLE eye(id INTEGER PRIMARY KEY, desc TEXT, data BLOB)") con.execute("INSERT INTO eye(desc,data) VALUES(?,?)", ("1d", sqlite3.Binary(r1d))) con.execute("INSERT INTO eye(desc,data) VALUES(?,?)", ("1d", numpy.getbuffer(r1d))) res = con.execute("SELECT * FROM eye").fetchall() con.close() #res -> #[(1, u'1d', <read-write buffer ptr 0x10371b220, size 80 at 0x10371b1e0>), # (2, u'1d', <read-write buffer ptr 0x10371b190, size 80 at 0x10371b150>)] print r1d - numpy.frombuffer(res[0][2]) #->[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] print r1d - numpy.frombuffer(res[1][2]) #->[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] Note that for work where data ty...