This is an archival dump of old wiki content --- see scipy.org for current material.
Please see http://scipy-cookbook.readthedocs.org/

Attachment 'colored_line.py'

Download

   1 #/usr/bin/env python
   2 ''' Color parts of a line based on its properties, e.g., slope.
   3 
   4 This is a minimal LineCollection demo.
   5 With a bit more work we could use a colormap instead of
   6 the if/elif/else block.  It might make sense to simply modify
   7 LineCollection to inherit from ScalarMappable, like the other
   8 collections do.
   9 '''
  10 
  11 from pylab import *
  12 from matplotlib.collections import LineCollection
  13 from matplotlib.colors import colorConverter
  14 
  15 x = arange(0, 10, 0.1)
  16 y = sin(x)
  17 z = cos(0.5 * (x[:-1] + x[1:]))  # first derivative
  18 
  19 rr = colorConverter.to_rgba('r')
  20 gg = colorConverter.to_rgba('g')
  21 bb = colorConverter.to_rgba('b')
  22 colors = list()
  23 for zz in z:
  24     if zz < -.5:
  25         colors.append(rr)
  26     elif zz < .5:
  27         colors.append(gg)
  28     else:
  29         colors.append(bb)
  30 
  31 points = zip(x, y)
  32 segments = zip(points[:-1], points[1:])
  33 
  34 ax = axes(frameon=True)
  35 
  36 
  37 LC = LineCollection(segments, colors = colors)
  38 LC.set_linewidth(3)
  39 ax.add_collection(LC)
  40 axis([0, 10, -1.1, 1.1])
  41 savefig('colored_line.png', dpi=70)
  42 show()

New Attachment

File to upload
Rename to
Overwrite existing attachment of same name

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.