Py淡

Python, Python, Python! In the spirit of "import antigravity"

One liner for choosing a nice matplotlib colormap

Memo for myself...

Since jet is becoming less and less popular these days and the default color styles will be revamped in the comming release of MPL, I also tend to avoid jet. When choosing a nice colormap for data that needs only several color levels, this one liner comes in handy.

val=range(10); imshow(np.vstack([val,val]), interpolation='none', cmap=cm.gist_rainbow)

This needs pylab environment, so just do from pylab import * or %pylab magic in IPython.

f:id:i-namekawa:20150812203733p:plain

just change the range and colormap as needed. For colormap, we can choose from this list I took from the official doc:

cmaps = [('Sequential',     ['Blues', 'BuGn', 'BuPu',
                             'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd',
                             'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu',
                             'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd']),
         ('Sequential (2)', ['afmhot', 'autumn', 'bone', 'cool', 'copper',
                             'gist_heat', 'gray', 'hot', 'pink',
                             'spring', 'summer', 'winter']),
         ('Diverging',      ['BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'PuOr',
                             'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral',
                             'seismic']),
         ('Qualitative',    ['Accent', 'Dark2', 'Paired', 'Pastel1',
                             'Pastel2', 'Set1', 'Set2', 'Set3']),
         ('Miscellaneous',  ['gist_earth', 'terrain', 'ocean', 'gist_stern',
                             'brg', 'CMRmap', 'cubehelix',
                             'gnuplot', 'gnuplot2', 'gist_ncar',
                             'nipy_spectral', 'jet', 'rainbow',
                             'gist_rainbow', 'hsv', 'flag', 'prism'])]

To get the RGB values for 4 levels of gist_rainbow,

[map(int, [255*r,255*g,255*b]) for r,g,b,a in cm.gist_rainbow(np.linspace(0,255,4).astype(int))]

As the default color space in OpenCV is BGR, the above code should be

[map(int, [255*b,255*g,255*r]) for r,g,b,a in cm.gist_rainbow(np.linspace(0,255,4).astype(int))]

to work with OpenCV.

val=range(3); imshow(np.vstack([val,val]), interpolation='none', cmap=cm.bwr)

f:id:i-namekawa:20150821063739p:plain