title: color coding using scalar mappable in matplotlib
body: <p><a href="https://i.stack.imgur.com/3POE7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3POE7.png" alt="Here"></a> is a subplot I created using matplotlib. Is it possible to code the colors on the basis of a pre-defined range? I want to pass an additional parameter, <em>voltage</em> to the function <em>drawLoadDuration</em> and define a scale (using if-else construct?) that sets the color. Higher the voltage, darker the shade. Also, for some reason, the y-tick labels for the colorbar are not showing.
  Any lead is most welcome...Thanks!</p>
  
  <pre><code>import matplotlib.cm
  from pylab import *
  import numpy as np
  
  f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=False)
  
  #other subplots
  
  ax3.set_title('Load Profile')
  ax3.patch.set_facecolor('silver')
  ax3.grid(True)
  
  cmap= plt.cm.bone_r   
  barHeight = 3
  ticklist = []
  def drawLoadDuration(period, starty, opacity):
      ax3.broken_barh((period), (starty, barHeight), alpha=opacity, facecolors=cmap(opacity), lw=0.5, zorder=2)
      ticklist.append(starty+barHeight/2.0)
      return 0
  
  drawLoadDuration([(0, 5), (13, 4), (19, 3), (23, 1)], 3, 0.5)   #Fan
  drawLoadDuration([(19, 1)], 9, 0.65)    #Tube Light
  drawLoadDuration([(19, 5)], 15, 0.35)   #Bulb
  drawLoadDuration([(7, 2), (16, 1)], 21, 0.28)   #Charger
  drawLoadDuration([(15, 0.5), (20, 1)], 27, 0.7) #Television
  drawLoadDuration([(9, 1), (17, 1)], 33, 1)  #Pump
  drawLoadDuration([(2,4)], 39, 0.8)    #Scooter
  
  ax3.set_ylim(0, 45)
  ax3.set_xlim(0, 24)
  ax3.set_xlabel('Time (Hours)')
  ax3.set_yticks(ticklist)
  
  xticklist = np.linspace(0.5, 24, 48)
  ax3.set_xticks(xticklist)
  
  ax3.set_xticklabels(["{}{}m".format(int(h%12+12*(h%12==0)),
                       {0:"p",1:"a"}[(h%24)&lt;12]) if ((h*10)%10)==0 \
                      else "" for h in xticklist], fontsize='9', rotation=90)
  
  ax3.tick_params('x', colors=cmap(1.0), tick1On=True)
  ax3.set_yticklabels(['Fan', 'Tube light', 'Bulb', 'Cellphone Charger', 'Television', 'Pump', 'Scooter'])
  
  ######################### Code Block for Colorbar
  sm = matplotlib.cm.ScalarMappable(cmap=cmap)    # create a scalarmappable from the colormap
  sm.set_array([])
  
  cbar = f.colorbar(sm, ticks=[-3, -2, -1, 0, 1, 2, 3], aspect=10, orientation='vertical', ax=ax3)  # using scalarmappable to create colorbar
  
  cbar.ax.text(3, 0.65, 'Power', rotation=90)
  cbar.ax.set_yticklabels(['&gt;1000', '&gt;800', '&gt;500', '&gt;200', '&gt;100', '&lt;10'])       #not working!!!
  
  plt.show()
  </code></pre>