def plot_spectral(n, stats, data, link):
    ''' The spectral variable plot of central tendency and members of a given cluster.'''
    
    #from scipy.stats import scoreatpercentile

    max_points = amax(data, axis=0)
    min_points = amin(data, axis=0)
    data = ainsert(data, norm[0], norm[1], axis=1)
    
    x, y = deque(), deque()
    x_out, y_out = deque(), deque()
    
    plt.figure(figsize=(10,9))
    plt.ylim(ylim[0],ylim[1])
    plt.xlim(axis[0]-0.1, axis[-1]+0.1)
    plt.xlabel(*xtitle)
    plt.ylabel(*ytitle)
    plt.title('Clump '+str(n)+' Na='+str(data.shape[0]))

    for item in data:
            
        if any([True for I, Q in izip(item,max_points) if I == Q]) or any([True for I, Q in izip(item,min_points) if I == Q]):
            for xy in izip(pairwise(item),pairwise(axis)):
               y_out.extend(xy[0])
               y_out.append(None)
               x_out.extend(xy[1])
               x_out.append(None)
        else:
           for xy in izip(pairwise(item),pairwise(axis)):
              y.extend(xy[0])
              y.append(None)
              x.extend(xy[1])
              x.append(None)

    plt.plot(x, y, 'k-', alpha=0.5)
    plt.plot(x_out, y_out, 'go-', linewidth=2)
    #plt.plot(axis, min_points, 'k-')

    #Cluster boxplot:
    ct, dev = stats[0], stats[1]

    axis_box = list()
    axis_box.extend(axis)
    axis_box.pop(norm[0])
    
    plt.errorbar(axis_box,ct,yerr = dev,fmt='o',color='r',ecolor='r', linewidth= 2, elinewidth=3)
    #plt.boxplot(data, notch=True, positions=axis_box) #, usermedians=stats[0])
    

    # Save figures:
    if n == 0:
       plt.show()
    else:
       try:
          plt.savefig(pathjoin("TESTS",link,"plots",'clump'+str(n)+'_'+link+'.png'),format='png', dpi=60)
          #plt.savefig(pathjoin("TESTS",label,'Graph'+str(n)+'.png'),format='png')
       except OverflowError:
          pass
    
    plt.clf()
def mosaic(cluster_members, data, link):
    ''' Make a boxplot of central tendency and members of each cluster.'''
  
    import matplotlib.gridspec as gridspec
    from math import sqrt, ceil
    
    kwargs = {'markersize':0.7, 'linestyle':'-','linewidth':0.5} 

    data = ainsert(data, norm[0], norm[1], axis=1)
    
    grid = int(ceil(sqrt(len(cluster_members))))
    
    fig = plt.figure(figsize=(10,10))
    plt.subplots_adjust(wspace=0.0, hspace=0.0)
    gs = gridspec.GridSpec(grid, grid)
    xy = list(product(range(grid), range(grid)))
    
    for n, members in enumerate(cluster_members):
        sub = plt.subplot(gs[xy[n][0],xy[n][1]])

        meas = data[members]
        
        x, y = deque(), deque()
        for item in meas:
            for line in izip(pairwise(item),pairwise(axis)):
                y.extend(line[0])
                y.append(None)
                x.extend(line[1])
                x.append(None)       

        plt.plot(x, y, 'k-', alpha=0.5, **kwargs)
        plt.errorbar(axis, median(meas, axis=0), fmt='bo-', yerr=std(meas, axis=0), label=str(len(members)), **kwargs)
        
        if xy[n][0] == int((grid-1)/2) and xy[n][1] == 0:
           plt.ylabel('Normalized Reflectance',fontsize=10,fontweight='black')         

        if xy[n][1] == 0:
           vis1 = True
        else:
           vis1 = False
        
        plt.setp(sub.get_yticklabels(), fontsize=6, visible=vis1)
        plt.setp(sub.get_xticklabels(), fontsize=6, visible=True)
        plt.ylim(ylim[0],ylim[1])
        plt.xlim(axis[0]-0.1, axis[-1]+0.1)
        plt.legend(loc=4, title=str(n+1), prop={'size':5,'weight':'black'}, numpoints=1,frameon=False)

    plt.suptitle('Wavelength ($microns$)',fontsize=10,fontweight='black')

    try:
        plt.savefig(pathjoin("TESTS",link,"plots","mosaic_"+link+".png"),format='png', dpi=300)
    except OverflowError:
        pass