Brendan Brendan - 1 year ago 114
Python Question

Create a color generator from given colormap in matplotlib

I have a series of lines that each need to be plotted with a separate colour. Each line is actually made up of several data sets (positive, negative regions etc.) and so I'd like to be able to create a generator that will feed one colour at a time across a spectrum, for example the

map shown here.

I have found the following works but it seems very complicated and more importantly difficult to remember,

from pylab import *


mp = cm.datad['gist_rainbow']
get_color = matplotlib.colors.LinearSegmentedColormap.from_list(mp, colors=['r', 'b'], N=NUM_COLORS)
# Then in a for loop
this_color = get_color(float(i)/NUM_COLORS)

Moreover, it does not cover the range of colours in the
map, I have to redefine a map.

Maybe a generator is not the best way to do this, if so what is the accepted way?

Answer Source

To index colors from a specific colormap you can use:

import pylab

cm = pylab.get_cmap('gist_rainbow')
for i in range(NUM_COLORS):
    color = cm(1.*i/NUM_COLORS)  # color will now be an RGBA tuple

# or if you really want a generator:
cgen = (cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download