parametric line color

Oops. I meant to reply to the list.


---------- Forwarded message ----------
From: Tony Yu <tsyu80@…287…>

Date: Sat, Jul 30, 2011 at 10:46 AM
Subject: Re: [Matplotlib-users] parametric line color
To: Alan G Isaac <alan.isaac@…287…>

On Sat, Jul 30, 2011 at 12:03 AM, Alan G Isaac <alan.isaac@…287…> wrote:

I have many lines to plot.

Each line has an associated parameter value.

I’d like to pick the color for each line

based on its parameter value by mapping

possible parameter values to the colors

in a color map (e.g., gist_rainbow),

retrieving colors one at a time (based

on the parameter value for a line).

If two lines have the same parameter value,

I need them to have exactly the same color.



Alan Isaac

Here’s a function to do what you want. (I haven’t tested it much so it could be buggy)



import matplotlib.pyplot as plt

def make_color_manager(parameter_range, cmap=‘YlOrBr’, start=0, stop=255):

"""Return color manager, which returns color based on parameter value.

parameter_range : 2-tuple
    minimum and maximum value of parameter
cmap : str

    name of a matplotlib colormap (see [](
start, stop: int
    limit colormap to this range (0 <= start < stop <= 255)


colormap = getattr([](, cmap)
pmin, pmax = parameter_range
def color_manager(val):
    """Return color based on parameter value `val`."""

    assert pmin <= val <= pmax
    val_norm = (val - pmin) * float(stop - start) / (pmax - pmin)
    idx = int(val_norm) + start
    return colormap(idx)
return color_manager

if name == ‘main’:
cm = make_color_manager((5, 10), start=100)
plt.plot([0, 1], color=cm(5))
plt.plot([0.5, 0.5], color=cm(7.5))
plt.plot([1, 0], color=cm(10))
plt.legend((‘val = 5’, ‘val = 7.5’, ‘val = 10’))