title: Matplotlib - add colorbar to a sequence of line plots
body: <p>I have a sequence of line plots for two variables (x,y) for a number of different values of a variable z. I would normally add the line plots with legends like this:</p>
  
  <pre><code>import matplotlib.pyplot as plt
  
  fig = plt.figure()
  ax  = fig.add_subplot(111)
  # suppose mydata is a list of tuples containing (xs, ys, z) 
  # where xs and ys are lists of x's and y's and z is a number. 
  legns = []
  for(xs,ys,z) in mydata:
     pl = ax.plot(xs,ys,color = (z,0,0))
     legns.append("z = %f"%(z))
  ax.legends(legns) 
  plt.show()
  </code></pre>
  
  <p>But I have too many graphs and the legends will cover the graph. I'd rather have a colorbar indicating the value of z corresponding to the color. I can't find anything like that in the galery and all my attempts do deal with the colorbar failed. Apparently I must create a collection of plots before trying to add a colorbar. </p>
  
  <p>Is there an easy way to do this? Thanks.</p>
  
  <p>EDIT (clarification):</p>
  
  <p>I wanted to do something like this:</p>
  
  <pre><code>import matplotlib.pyplot as plt
  import matplotlib.cm     as cm
  
  fig = plt.figure()
  ax  = fig.add_subplot(111)
  mycmap = cm.hot
  # suppose mydata is a list of tuples containing (xs, ys, z) 
  # where xs and ys are lists of x's and y's and z is a number between 0 and 1
  plots = []
  for(xs,ys,z) in mydata:
     pl = ax.plot(xs,ys,color = mycmap(z))
     plots.append(pl)
  fig.colorbar(plots)
  plt.show()
  </code></pre>
  
  <p>But this won't work according to the Matplotlib reference because a list of plots is not a "mappable", whatever this means. </p>
  
  <p>I've created an alternative plot function using <code>LineCollection</code>:</p>
  
  <pre><code>def myplot(ax,xs,ys,zs, cmap):
      plot = lc([zip(x,y) for (x,y) in zip(xs,ys)], cmap = cmap)
      plot.set_array(array(zs))
      x0,x1 = amin(xs),amax(xs)
      y0,y1 = amin(ys),amax(ys)
      ax.add_collection(plot)
      ax.set_xlim(x0,x1)
      ax.set_ylim(y0,y1)
      return plot
  </code></pre>
  
  <p><code>xs</code> and <code>ys</code> are lists of lists of x and y coordinates and <code>zs</code> is a list of the different conditions to colorize each line. It feels a bit like a cludge though... I thought that there would be a more neat way to do this. I like the flexibility of the <code>plt.plot()</code> function. </p>