','redshift'][x_ivar]
    y_var= ['dmag','chisq'][y_ivar]

    types= np.char.strip(dat.get('tractor_type'))
    use_types= ['PSF','SIMP','REX','EXP','DEV']
    if 'SIMP' in set(types):
        use_types.remove('REX')
    else:
        use_types.remove('SIMP')
    figs,axes= plt.subplots(4,1,figsize=(5,12))
    plt.subplots_adjust(hspace=0.2)

    ### 
    ratio_area= 1. 
    fix= ratio_area * np.average([dat.get('tractor_apflux_resid_'+band)[:,6],
                                      dat.get('tractor_apflux_resid_'+band)[:,7]],
                                    axis=0)
    assert(len(fix)) == len(dat)
    if y_var == 'dmag':
        _y_var= plots.flux2mag(dat.get('tractor_flux_'+band)) -\
                   plots.flux2mag(dat.get(band+'flux')+  fix)
        ylab= 'dmag (Tractor - True)'
        ylim=(-2,2)
    elif y_var == 'chisq':
        _y_var= dat.get('tractor_flux_'+band) -\
                   (dat.get(band+'flux')+  fix)
        _y_var *= np.sqrt(dat.get('tractor_flux_ivar_'+band))
        ylab= 'chiflux (Tractor - True) * sqrt(ivar)'
        ylim=(-10,10)

    if x_var == 'true_mag':
        _x_var= plots.flux2mag(dat.get(band+'flux')/\
                               dat.get('mw_transmission_'+band))
        xlab= 'true mag %s' % band
        xlim= dict(g=(21.6,23),
                   r=(20.75,22.5),
                   z=(19.5,22))
    elif x_var == 'galdepth':
        flux_for_depth= 5 / np.sqrt(dat.get('tractor_galdepth_'+band))
        _x_var= plots.flux2mag(flux_for_depth/\
                                 dat.get('mw_transmission_'+band))
        xlab= 'galdepth %s' % band
        xlim= dict(g=(21,24.5),
                   r=(21,24.5),
                   z=(21,24.5))
    elif x_var =='redshift':
        _x_var= dat.psql_redshift
        xlab='redshift'
        xlim= dict(g=(0,1.5),
                   r=(0,1.5),
                   z=(0,1.5))
    ###   

    for ax,typ in zip(axes,use_types):
        mytext(ax,0.9,0.9,typ, fontsize=12)
        #isPostiveFlux= ((np.isfinite(dmag)) &
        #                (np.isfinite(true_mag)))
        #isPostiveFlux= np.ones(len(dmag),bool)
        #print('true_mag=',true_mag[isPostiveFlux],'trac_mag=',dmag[isPostiveFlux])
        
        # Plot
        xlabel=ax.set_xlabel(xlab)
        for lab,color,keep in [('lost (recovered but fail TS)','g', (isRec) & (is_elg_input) & (~is_elg_trac)),
                               ('Tractor ELG','b', (isRec) & (is_elg_input) & (is_elg_trac)),
                               ('Tractor ELG (contamiation)', 'c',(isRec) & (~is_elg_input) & (is_elg_trac))]:
            subset= (keep) & (types == typ)
            if percentile_lines:
                binned= plots.bin_up(_x_var[subset],_y_var[subset], 
                                     bin_minmax=xlim[band],nbins=30)
                for perc in ['q25','q75']:
                    kw= dict(c=color,lw=2)
                    if perc == 'q25':
                        kw.update(label=lab)
                    ax.plot(binned['binc'],binned[perc],**kw)
            else:
                ax.scatter(_x_var[subset],_y_var[subset],
                           alpha=1,s=5,c=color,label=lab)
                #ax.scatter(true_mag[(isPostiveFlux) & (keep)],dmag[(isPostiveFlux) & (keep)],
                #           alpha=1,s=5,c=color,label=lab)
        
    for ax in axes:
        ax.axhline(0,c='k',ls='--')
        ax.set_ylim(ylim)
    ylabel=axes[-1].set_ylabel(ylab)
    leg=axes[0].legend(loc=(0,1.05),ncol=2,fontsize=10,markerscale=3)
    plt.savefig(fn,bbox_extra_artists=[xlabel,ylabel,leg], bbox_inches='tight')
    plt.close()
    print('Wrote %s' % fn)

def rec_lost_contam_input_elg_notelg(dat,fn='rec_lost_contam_input_elg_notelg.png'):
    fig,axes=plt.subplots(3,1,figsize=(6,12))
    plt.subplots_adjust(hspace=0.3)
    xlim= dict(g=(21.6,23),
               r=(20.75,22.5),
               z=(19.5,22))

    kw=dict(normed=True)
    for ax,band in zip(axes,'grz'):
        kw.update(bins=np.linspace(xlim[band][0],xlim[band][1],num=30),
                  range=xlim[band])
        myhist(ax,dat.get('psql_'+band)[is_elg_input],color='b',label='input, ELG',**kw)
        myhist(ax,dat.get('psql_'+band)[~is_elg_input],color='g',label='input, not ELG',**kw)

    for ax,band in zip(axes,'grz'):
        xlab=ax.set_xlabel(band)
        ylab=ax.set_ylabel('PDF')
    axes[0].legend(loc='upper left')
    plt.savefig(fn,bbox_extra_artists=[xlab,ylab], bbox_inches='tight')
    plt.close()
    print('Wrote %s' % fn)


def rec_lost_contam_fraction(dat,fn='rec_lost_contam_fraction.png'):
    fig,axes=plt.subplots(1,2,figsize=(10,5))
    plt.subplots_adjust(wspace=0.2)
    # xlim=(0,2.5)
    xlim=None
    kw=dict(range=(0,2),normed=False)

    # Left panel
    ax= axes[0]
    n_tot,bins= np.histogram(dat.psql_redshift,bins=30,**kw)

    lab,keep= 'is ELG', (is_elg_input)
    n_elg,bins= np.histogram(dat.psql_redshift[keep],bins=bins,**kw)
    my_step(ax,bins,n_elg/n_tot,color='b',label=lab)

    lab,keep= 'is ELG, recovered', (isRec) & (is_elg_input)
    n_elg_rec,_= np.histogram(dat.psql_redshift[keep],bins=bins,**kw)
    my_step(ax,bins,n_elg_rec/n_tot,color='g',label=lab)

    # Right panel
    ax= axes[1]
    lab,keep= 'is ELG, recovered ELG', (isRec) & (is_elg