Oops. I meant to reply to the list.
-Tony
---------- Forwarded message ----------
From: Tony Yu <tsy...@gmail.com>
Date: Sat, Jul 30, 2011 at 10:46 AM
Subject: Re: [Matplotlib-users] parametric line color
To: Alan G Isaac <alan.is...@gmail.com>
On Sat, Jul 30, 2011 at 12:03 AM, Alan G Isaac <alan.is...@gmail.com> 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.
>
> Hints?
>
> Thanks,
> Alan Isaac
>
>
Here's a function to do what you want. (I haven't tested it much so it could
be buggy)
Best,
-Tony
#----
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.
Parameters
----------
parameter_range : 2-tuple
minimum and maximum value of parameter
cmap : str
name of a matplotlib colormap (see matplotlib.pyplot.cm)
start, stop: int
limit colormap to this range (0 <= start < stop <= 255)
"""
colormap = getattr(plt.cm, 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'))
plt.show()
------------------------------------------------------------------------------
Got Input? Slashdot Needs You.
Take our quick survey online. Come on, we don't ask for help often.
Plus, you'll get a chance to win $100 to spend on ThinkGeek.
http://p.sf.net/sfu/slashdot-survey
_______________________________________________
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users