code: def add_scalebar(ax, matchx=True, matchy=True, hidex=True, hidey=True, unitsx='', unitsy='', scalex=1, scaley=1, **kwargs):
      
      def f(axis):
          l = axis.get_majorticklocs()
          return len(l)>1 and (l[1] - l[0])
      
      if matchx: kwargs['sizex'] = f(ax.xaxis)      
      if matchy: kwargs['sizey'] = f(ax.yaxis)
  
      if 'labelx' not in kwargs or kwargs['labelx'] is None:
          kwargs['labelx'] = '%.3g %s'%(kwargs['sizex']*scalex,unitsx)
      if 'labely' not in kwargs or kwargs['labely'] is None:
          kwargs['labely'] = '%.3g %s'%(kwargs['sizey']*scaley,unitsy)
  
      sb = AnchoredScaleBar(ax.transData, **kwargs)
      ax.add_artist(sb)
  
      if hidex : ax.xaxis.set_visible(False)
      if hidey : ax.yaxis.set_visible(False)
      if hidex and hidey: ax.set_frame_on(False)
  
      return sb
docs: Add scalebars to axes
      Adds a set of scale bars to *ax*, matching the size to the ticks of the plot
      and optionally hiding the x and y axes
      - ax : the axis to attach ticks to
      - matchx,matchy : if True, set size of scale bars to spacing between ticks
                      if False, size should be set using sizex and sizey params
      - hidex,hidey : if True, hide x-axis and y-axis of parent
      - **kwargs : additional arguments passed to AnchoredScaleBars
      Returns created scalebar object