Exemplo n.º 1
0
def photon_sf_plot(tag):

    for year in [2017, 2018]:
        opts = markers('data')
        # opts['markersize'] = 5
        # opts['fillstyle'] = 'none'
        opts.pop('emarker', '')

        fig = plt.gcf()
        ax = plt.gca()
        x, y, yerr = {}, {}, {}
        fnum = f'output/{tag}/table_g_HLT_PFHT1050_photon_pt0_JetHT_{year}.txt'
        fden = f'output/{tag}/table_g_HLT_PFHT590_photon_pt0_GJets_HT_MLM_{year}.txt'

        xnum, _, ynum, yerrnum = get_xy(fnum)
        xden, _, yden, yerrden = get_xy(fden)
        x = xnum
        y = ynum / yden
        dy = ratio_unc(ynum, yden, yerrnum, yerrden)

        ax.errorbar(x, y, yerr=dy, label=f'{year}', **opts)

        # for f in files: plot(f)
        outdir = f"./output/{tag}"
        # ax.set_ylim(0.9,1)
        ax.legend()
        ax.set_ylabel("Data / MC SF")
        ax.xaxis.set_major_locator(MultipleLocator(200))
        ax.xaxis.set_minor_locator(MultipleLocator(50))
        ax.yaxis.set_major_locator(MultipleLocator(0.05))
        ax.yaxis.set_minor_locator(MultipleLocator(0.01))
        ax.set_ylim(0.95, 1.02)
        ax.grid(1)
        # rax.set_ylim(0.95,1.05)
        # rax.yaxis.set_major_locator(MultipleLocator(0.05))
        # rax.yaxis.set_minor_locator(MultipleLocator(0.01))
        # rax.grid(1)
        # rax.set_xlabel("Recoil or $p_{T}^{miss}$ (GeV)")
        # rax.set_ylabel(r"Ratio to single-$\mu$")
        # rax.plot([0,1000],[0.99,0.99],color='blue')
        # rax.plot([0,1000],[1.01,1.01],color='blue')
        # rax.plot([250,250],[0.95,0.95],color='blue')
        ax.plot([215, 215], [0.9, 1.1], color='red', zorder=-1)
        plt.text(1.,
                 1.,
                 r"%.1f fb$^{-1}$ (13 TeV)" % lumi(year),
                 fontsize=16,
                 horizontalalignment='right',
                 verticalalignment='bottom',
                 transform=ax.transAxes)
        plt.text(0.,
                 1.,
                 f'{year}',
                 fontsize=16,
                 horizontalalignment='left',
                 verticalalignment='bottom',
                 transform=ax.transAxes)
        fig.savefig(pjoin(outdir, f'photon_sf_{year}.pdf'))
        fig.clear()
        plt.close(fig)
Exemplo n.º 2
0
def region_comparison_plot(tag):
    for year in [2017,2018]:
        regions = ['1m', '2m', '1e','1m_hlt','2m_hlt']
        opts = markers('data')
        opts['markersize'] = 5.
        opts['fillstyle'] = 'none'
        emarker = opts.pop('emarker', '')

        fig, ax, rax = fig_ratio()

        x, y, yerr = {}, {}, {}
        for region in regions:
            if region.endswith('e'):
                file = f'output/{tag}/table_{region}_EGamma_{year}.txt'
            else:
                file = f'output/{tag}/table_{region}_SingleMuon_{year}.txt'
            x[region], y[region], yerr[region] = get_xy(file)
            opts['color'] = colors[region]
            ax.errorbar(x[region], y[region], yerr=yerr[region],label=f'{region} region', **opts)

        # opts.pop('elinewidth')
            if region=='1m':
                continue

            rax.errorbar(x['1m'], y[region]/y['1m'], yerr[region]/y['1m'], **opts)

        # for f in files: plot(f)
        outdir = f"./output/{tag}"
        # ax.set_ylim(0.9,1)
        ax.legend()
        ax.set_ylabel("Efficiency")
        ax.xaxis.set_major_locator(MultipleLocator(200))
        ax.xaxis.set_minor_locator(MultipleLocator(50))
        ax.yaxis.set_major_locator(MultipleLocator(0.05))
        ax.yaxis.set_minor_locator(MultipleLocator(0.01))
        ax.set_ylim(0.9,1.02)
        ax.grid(1)
        rax.set_ylim(0.9,1.1)
        rax.grid(1)
        rax.set_xlabel("Recoil or $p_{T}^{miss}$ (GeV)")
        rax.set_ylabel(r"Ratio to single-$\mu$")
        plt.text(1., 1., r"$\approx$ %.1f fb$^{-1}$ (13 TeV)" % lumi(year),
                fontsize=16,
                horizontalalignment='right',
                verticalalignment='bottom',
                transform=ax.transAxes
               )
        plt.text(0., 1., f'{year}',
                fontsize=16,
                horizontalalignment='left',
                verticalalignment='bottom',
                transform=ax.transAxes
               )
        fig.savefig(pjoin(outdir, f'region_comparison_data_{year}.pdf'))
        fig.clear()
        plt.close(fig)
Exemplo n.º 3
0
def lumi_by_region(region, year):
    if 'HLT' not in region:
        return lumi(year)
    else:
        if year == 2017:
            if 'HLT_PFHT590' in region: return 0.445
            if 'HLT_PFHT680' in region: return 0.786
            if 'HLT_PFHT780' in region: return 1.462
            if 'HLT_PFHT890' in region: return 2.802
            if 'HLT_PFHT1050' in region: return 41.527
        elif year == 2018:
            if 'HLT_PFHT590' in region: return 0.467
            if 'HLT_PFHT680' in region: return 0.924
            if 'HLT_PFHT780' in region: return 1.838
            if 'HLT_PFHT890' in region: return 3.661
            if 'HLT_PFHT1050' in region: return 59.736
Exemplo n.º 4
0
def main():

    indir = "../lo_vs_nlo/input/2019-09-23_photon_overlap"

    acc = acc_from_dir(indir)

    for region in ['cr_2m_j', 'cr_2e_j', 'cr_1m_j', 'cr_1e_j', 'cr_g_j']:
        if '_1m_' in region or '_2m_' in region:
            sel_2017 = re.compile(f'MET_2017')
            sel_2018 = re.compile(f'MET_2018')
        else:
            sel_2017 = re.compile(f'EGamma_2017')
            sel_2018 = re.compile(f'EGamma_2018')

        for distribution in ['recoil']:
            # fig, ax, rax = make_plot(acc, region=region,distribution=distribution, year=2016, data=data, mc=mc, ylim=(1e-3,1e3), rylim=(0,2),outdir=f'./output/{os.path.basename(indir)}')
            fig, (ax,
                  rax) = plt.subplots(2,
                                      1,
                                      figsize=(7, 7),
                                      gridspec_kw={"height_ratios": (3, 1)},
                                      sharex=True)

            h = acc['recoil']
            h = merge_extensions(h, acc, reweight_pu=('nopu' in distribution))
            # scale_xs_lumi(h)
            h = merge_datasets(h)
            h = h.integrate(h.axis('region'), region)
            s = Style()
            try:
                newax = s.get_binning(distribution, region)
                h = h.rebin(h.axis(newax.name), newax)
            except KeyError:
                pass

            f = uproot.open('fitDiagnostics.root')
            h2016 = f['shapes_prefit'][regions[region]]['data']

            x, y = {}, {}
            # x[2016] = np.r_[0.5*(h2016.bins[:,0] + h2016.bins[:,1]),1500., 1700., 1900.]
            pprint(dir(h2016))
            x[2016] = np.r_[h2016.xvalues, 1500., 1700., 1900.]
            y[2016] = np.r_[h2016.yvalues / lumi(2016), 0, 0, 0]
            h2017 = h[sel_2017].integrate('dataset')
            h2018 = h[sel_2018].integrate('dataset')
            x[2017] = h2017.axis('recoil').centers()
            y[2017] = h2017.values()[()] / (np.diff(
                h2017.axis('recoil').edges())) / lumi(2017)
            x[2018] = h2018.axis('recoil').centers()
            y[2018] = h2018.values()[()] / (np.diff(
                h2018.axis('recoil').edges())) / lumi(2018)

            for year in x.keys():
                ax.plot(x[year], y[year], 'o-', label=f'{year}')
                rax.plot(x[year], y[year] / y[2016], '-o')

            ax.legend(title=region)
            ax.set_yscale('log')
            rax.set_xlabel(distribution)
            ax.set_xlabel(distribution)
            rax.set_ylabel('Ratio to 2016')
            ax.set_ylabel('Data cross section / bin')
            loc1 = matplotlib.ticker.MultipleLocator(base=0.2)
            loc2 = matplotlib.ticker.MultipleLocator(base=0.1)
            rax.yaxis.set_major_locator(loc1)
            rax.yaxis.set_minor_locator(loc2)
            rax.grid(axis='y', which='minor', linestyle='--')
            rax.grid(axis='y', which='major', linestyle='--')
            rax.set_ylim(0.5, 1.5)
            fig.savefig(f'output/{region}.pdf')
Exemplo n.º 5
0
def plot_recoil(acc, region_tag="1m", dataset='SingleMuon', year=2018, tag="test", distribution="recoil"):
    h = acc[distribution]
    h = merge_extensions(h)
    # h = scale_to_xs(h, acc)
    h = merge_datasets(h)

    newbin = hist.Bin(distribution,f"{distribution} (GeV)",np.array(list(range(0,400,20)) + list(range(400,1100,100))))
    h = h.rebin(h.axis(distribution), newbin)
    ds = f'{dataset}_{year}'
    h = h.project(h.axis('dataset'), ds)
    # print(h)
    hnum = h.project(h.axis('region'),f'tr_{region_tag}_num')
    hden = h.project(h.axis('region'),f'tr_{region_tag}_den')

    # print(hden, hnum)

    # Recoil plot
    try:
        fig, ax,_ = hist.plot1d(hnum, binwnorm=True)
    except KeyError:
        print(f'ERROR: {region_tag}, {dataset}, {year}')
        return
    hist.plot1d(hden, ax=ax, clear=False, binwnorm=True)
    plt.yscale('log')
    plt.gca().set_ylim(0.1,1e6)
    outdir = f"./output/{tag}"
    if not os.path.exists(outdir):
        os.makedirs(outdir)
    fig.savefig(pjoin(outdir, f'{distribution}_{region_tag}_{dataset}_{year}.pdf'))
    with open(pjoin(outdir,f'table_{region_tag}_{dataset}_{year}.txt'),"w") as f:
        f.write(content_table(hnum, hden) + "\n")
    plt.close(fig)

    # Efficiency
    fig, ax,_ = hist.plotratio(hnum, hden,
                guide_opts={},
                unc='clopper-pearson',
                error_opts=markers('data')
                )
    ax.set_ylim(0,1.1)
    ax.set_xlim(0,xmax)
    ax.set_ylabel("Efficiency")

    plt.text(1., 1., r"$\approx$ %.1f fb$^{-1}$ (13 TeV)" % lumi(year),
                fontsize=16,
                horizontalalignment='right',
                verticalalignment='bottom',
                transform=ax.transAxes
               )
    plt.text(0., 1., f'{region_tag}, {year}',
                fontsize=16,
                horizontalalignment='left',
                verticalalignment='bottom',
                transform=ax.transAxes
               )
    plt.text(1., 0., f'{trgname(year, tag)}',
                fontsize=10,
                horizontalalignment='right',
                verticalalignment='bottom',
                transform=ax.transAxes
               )

    plt.plot([0,xmax],[0.95,0.95],'r-')
    fig.savefig(pjoin(outdir, f'eff_{region_tag}_{dataset}_{year}.pdf'))
    plt.close(fig)
Exemplo n.º 6
0
def sf_comparison_plot(tag):
    for year in [2017,2018]:
        regions = ['1m', '2m', '1m_hlt', '2m_hlt']
        opts = markers('data')
        opts['markersize'] = 5
        opts['fillstyle'] = 'none'
        emarker = opts.pop('emarker', '')

        fig, ax, rax = fig_ratio()

        x, y, yerr = {}, {}, {}
        for region in regions:
            if '1e' in region:
                fnum = f'output/{tag}/table_{region}_EGamma_{year}.txt'
                fden = f'output/{tag}/table_{region}_WJetsToLNu-MLM_{year}.txt'
            elif '1m' in region:
                fnum = f'output/{tag}/table_{region}_SingleMuon_{year}.txt'
                fden = f'output/{tag}/table_{region}_WJetsToLNu-MLM_{year}.txt'
            elif '2m' in region:
                fnum = f'output/{tag}/table_{region}_SingleMuon_{year}.txt'
                fden = f'output/{tag}/table_{region}_DYNJetsToLL_M-50-MLM_{year}.txt'


            xnum, ynum, yerrnum = get_xy(fnum)
            xden, yden, yerrden = get_xy(fden)
            x[region] = xnum
            y[region] = ynum / yden
            yerr[region] = ratio_unc(ynum, yden, yerrnum, yerrden)
            opts['color'] = colors[region]
            opts['marker'] = region_marker[region]
            ax.errorbar(x[region], y[region], yerr=yerr[region],label=f'{region} region', **opts)

        # opts.pop('elinewidth')
            if region=='1m':
                continue

            rax.errorbar(x['1m'], y[region]/y['1m'], ratio_unc(y[region],y['1m'],yerr[region],yerr['1m']), **opts)

        # for f in files: plot(f)
        outdir = f"./output/{tag}"
        # ax.set_ylim(0.9,1)
        ax.legend()
        ax.set_ylabel("Data / MC SF")
        ax.xaxis.set_major_locator(MultipleLocator(200))
        ax.xaxis.set_minor_locator(MultipleLocator(50))
        ax.yaxis.set_major_locator(MultipleLocator(0.05))
        ax.yaxis.set_minor_locator(MultipleLocator(0.01))
        ax.set_ylim(0.9,1.1)
        ax.grid(1)
        rax.set_ylim(0.95,1.05)
        rax.yaxis.set_major_locator(MultipleLocator(0.05))
        rax.yaxis.set_minor_locator(MultipleLocator(0.01))
        rax.grid(1)
        rax.set_xlabel("Recoil or $p_{T}^{miss}$ (GeV)")
        rax.set_ylabel(r"Ratio to single-$\mu$")
        plt.text(1., 1., r"$\approx$ %.1f fb$^{-1}$ (13 TeV)" % lumi(year),
                fontsize=16,
                horizontalalignment='right',
                verticalalignment='bottom',
                transform=ax.transAxes
               )
        plt.text(0., 1., f'{year}',
                fontsize=16,
                horizontalalignment='left',
                verticalalignment='bottom',
                transform=ax.transAxes
               )
        fig.savefig(pjoin(outdir, f'sf_comparison_{year}.pdf'))
        fig.clear()
        plt.close(fig)
Exemplo n.º 7
0
def fit(tag, year):
    outdir = './output/gamma/fit/'
    try:
        os.makedirs(outdir)
    except FileExistsError:
        pass

    x, eff, eff_up, eff_down = {}, {}, {}, {}
    x['data'], eff['data'], eff_up['data'], eff_down['data'] = load(tag, 'JetHT', year)
    x['mc'], eff['mc'], eff_up['mc'], eff_down['mc'] = load(tag, 'GJets_HT_MLM', year)

    pars = {}
    cross = {}
    for key in ['data','mc']:
        pars[key], _ = curve_fit(sigmoid, x[key], eff[key], sigma=0.5*(eff_up[key]-eff_down[key]), p0=[1e-3,200,0.1,1])    
        cross[key] = minimize( lambda x: np.abs(sigmoid(x, *pars[key]) - 0.95),x0=230)

    fig, ax, rax = fig_ratio()

    xinterp = np.linspace(min(x['data']), max(x['data']), 1000)

    handles = []
    ax.errorbar(x['data'], eff['data'], 0.5*(eff_up['data']-eff_down['data']),fmt='o',label='Data',color=colors["data"])
    ax.errorbar(x['mc'], eff['mc'], 0.5*(eff_up['mc']-eff_down['mc']),fmt='s',label='MC',fillstyle='none',color=colors["mc"])
    ax.plot(xinterp, sigmoid(xinterp, *pars['data']), label='Data fit',color=colors["data"],zorder=-1)
    ax.plot(xinterp, sigmoid(xinterp, *pars['mc']), label='MC fit',color=colors["mc"],zorder=-1,linestyle='--')

    ax.set_ylim(0.,1.1)
    ax.set_xlim(100,1100)
    ax.legend()


    ax.text(350,.4,'f(x) = c + (d-c) / (1 + exp(-a * (x-b)))')
    ax.text(
            300,
            0.1,
            '\n'.join([
                f"a = {pars['data'][0]:.3f} / GeV",
                f"b = {pars['data'][1]:.2f} GeV",
                f"c = {pars['data'][2]:.3f}",
                f"d = {pars['data'][3]:.3f}"
            ]),
            color=colors['data']
            )
    ax.text(
            600,
            0.1,
            '\n'.join([
                f"a = {pars['mc'][0]:.3f} / GeV",
                f"b = {pars['mc'][1]:.2f} GeV",
                f"c = {pars['mc'][2]:.3f}",
                f"d = {pars['mc'][3]:.3f}"
            ]),
            color=colors['mc']
            )

    ax.text(700,0.8, 
                    "\n".join([
                              f"Data > 95% @ {cross['data'].x[0]:.0f} GeV",
                              f"MC > 95% @ {cross['mc'].x[0]:.0f} GeV",
                    ])
                              )
    ax.text(1., 1., r"%.1f fb$^{-1}$ (13 TeV)" % lumi(year),
                fontsize=16,
                horizontalalignment='right',
                verticalalignment='bottom',
                transform=ax.transAxes
                )
    rax.set_ylim(0.95,1.1)
    rax.grid()
    # rax.plot([cross['data'].x[0],cross['data'].x[0]], [0.8,1.05],color='k',)
    # ax.plot([cross['data'].x[0],cross['data'].x[0]], [0.,1.05],color='k',linestyle='--')
    # ax.plot([cross['mc'].x[0],cross['mc'].x[0]], [0.9,1.05],color='r')


    # ax.plot([215,215],[0.9,1.05])

    rax.errorbar(x["data"], eff["data"] / eff["mc"], 0.5*(eff_up["data"] - eff_down["data"]) / eff["mc"],fmt='o',label='Data / MC',color=colors['data'])
    rxinterp = np.linspace(cross['data'].x[0], max(xinterp),1000)

    
    rax.plot(rxinterp, sigmoid(rxinterp, *pars['data']) / sigmoid(rxinterp, *pars['mc']),label=f"Data / MC fit ratio, plateau at {100*(sigmoid(rxinterp, *pars['data']) / sigmoid(rxinterp, *pars['mc']))[-1]:.1f} %",color='k')
    rax.plot(rxinterp, 0.99*sigmoid(rxinterp, *pars['data']) / sigmoid(rxinterp, *pars['mc']), label='1% uncertainty on fit',linestyle='--',color='gray')
    rax.plot(rxinterp, 1.01*sigmoid(rxinterp, *pars['data']) / sigmoid(rxinterp, *pars['mc']),linestyle='--',color='gray')
    # rxinterp2 = np.linspace(min(xinterp),cross['data'].x[0], 1000)
    # rax.plot(rxinterp2, sigmoid(rxinterp2, *pars['data']) / sigmoid(rxinterp2, *pars['mc']),color='k',linestyle=':')

    rax.legend()
    rax.set_ylabel("Ratio")
    ax.set_ylabel("Trigger efficiency")
    ax.set_xlabel("Photon $p_{T}$ (GeV)")
    rax.set_xlabel("Photon $p_{T}$ (GeV)")
    ax.figure.savefig(pjoin(outdir, f'fit_{tag}_{year}.pdf'))
    ax.figure.clf()
Exemplo n.º 8
0
def main():

    indir = "../lo_vs_nlo/input/2019-09-26_checks/"

    acc = acc_from_dir(indir)

    for region in [
            'cr_2m_j', 'cr_1m_j', 'cr_2m_j_noveto_tau', 'cr_1m_j_noveto_tau',
            'cr_2m_j_noveto_photon', 'cr_1m_j_noveto_photon'
    ]:
        sel_2016 = re.compile(f'MET_2016')
        sel_2017 = re.compile(f'MET_2017')
        sel_2018 = re.compile(f'MET_2018')

        for distribution in axes.keys():
            # fig, ax, rax = make_plot(acc, region=region,distribution=distribution, year=2016, data=data, mc=mc, ylim=(1e-3,1e3), rylim=(0,2),outdir=f'./output/{os.path.basename(indir)}')
            fig, (ax,
                  rax) = plt.subplots(2,
                                      1,
                                      figsize=(7, 7),
                                      gridspec_kw={"height_ratios": (3, 1)},
                                      sharex=True)

            h = acc[distribution]
            h = merge_extensions(h, acc, reweight_pu=('nopu' in distribution))
            # scale_xs_lumi(h)
            h = merge_datasets(h)
            h = h.integrate(h.axis('region'), region)
            s = Style()
            try:
                newax = s.get_binning(distribution, region)
                h = h.rebin(h.axis(newax.name), newax)
            except KeyError:
                pass

            x, y = {}, {}
            h2016 = h[sel_2016].integrate('dataset')
            h2017 = h[sel_2017].integrate('dataset')
            h2018 = h[sel_2018].integrate('dataset')
            try:
                x[2016] = h2016.axis(axes[distribution]).centers()
                y[2016] = h2016.values()[()] / (np.diff(
                    h2016.axis(axes[distribution]).edges())) / lumi(2016)
                x[2017] = h2017.axis(axes[distribution]).centers()
                y[2017] = h2017.values()[()] / (np.diff(
                    h2017.axis(axes[distribution]).edges())) / lumi(2017)
                x[2018] = h2018.axis(axes[distribution]).centers()
                y[2018] = h2018.values()[()] / (np.diff(
                    h2018.axis(axes[distribution]).edges())) / lumi(2018)
            except KeyError:
                continue

            for year in x.keys():
                ax.plot(x[year],
                        y[year],
                        'o-',
                        label=f'{year} / {lumi(year)} fb-1')
                rax.plot(x[year], y[year] / y[2016], '-o')

            ax.legend(title=region)
            ax.set_yscale('log')
            rax.set_xlabel(distribution)
            ax.set_xlabel(distribution)
            rax.set_ylabel('Ratio to 2016')
            ax.set_ylabel('Data cross section / bin')
            loc1 = matplotlib.ticker.MultipleLocator(base=0.2)
            loc2 = matplotlib.ticker.MultipleLocator(base=0.1)
            rax.yaxis.set_major_locator(loc1)
            rax.yaxis.set_minor_locator(loc2)
            rax.grid(axis='y', which='minor', linestyle='--')
            rax.grid(axis='y', which='major', linestyle='--')
            rax.set_ylim(0.5, 1.5)
            outname = f'output/bu/{region}_{distribution}.pdf'
            fig.savefig(outname)
            print(f"Saved {outname}")
            plt.close(fig)
Exemplo n.º 9
0
def main():

    for mode in ['monojet', 'zpt']:
        if mode == 'monojet':
            regions = {
                # 'ch1' : 'sr_j',
                'ch2': 'cr_2m_j',
                'ch3': 'cr_1m_j',
                # # 'ch4' : 'cr_g_j',
                # # 'ch5' : 'cr_2e_j',
                'ch6': 'cr_1e_j'
            }
            fitfile = 'fitDiagnostics.root'
            bins = [
                250, 280, 310, 340, 370, 400, 430, 470, 510, 550, 590, 640,
                690, 740, 790, 840, 900, 960, 1020, 1090, 1160, 1250, 1400
            ]
        elif mode == 'zpt':
            regions = {
                # 'ch1' : 'sr_j',
                'monojet_singlemu': 'cr_1m_j',
                # 'ch4' : 'cr_g_j',
                # 'ch5' : 'cr_2e_j',
                'monojet_singleel': 'cr_1e_j'
            }
            fitfile = 'fitDiagnostics_zpt.root'
            bins = [250, 275, 300, 350, 400, 450, 500, 650, 800, 1150, 1400]
        tmp = {}
        for k, v in regions.items():
            tmp[v] = k
        regions.update(tmp)

        inpath = "input/2020-01-07_fine_recoil_bins_v4"

        acc = dir_archive(
            inpath,
            serialized=True,
            compression=0,
            memsize=1e3,
        )
        acc.load('recoil')
        acc.load('sumw')
        acc.load('sumw_pileup')
        acc.load('nevents')
        for region in [x for x in regions.keys() if 'r_' in x]:
            if '_1m_' in region or '_2m_' in region:
                sel_2016 = re.compile(f'MET_2016')
                sel_2017 = re.compile(f'MET_2017')
                sel_2018 = re.compile(f'MET_2018')
            else:
                sel_2016 = re.compile(f'EGamma_2016')
                sel_2017 = re.compile(f'EGamma_2017')
                sel_2018 = re.compile(f'EGamma_2018')

            for distribution in ['recoil']:
                # fig, ax, rax = make_plot(acc, region=region,distribution=distribution, year=2016, data=data, mc=mc, ylim=(1e-3,1e3), rylim=(0,2),outdir=f'./output/{os.path.basename(indir)}')
                fig, (ax, rax) = plt.subplots(
                    2,
                    1,
                    figsize=(7, 7),
                    gridspec_kw={"height_ratios": (3, 1)},
                    sharex=True)

                h = acc['recoil']
                h = merge_extensions(h,
                                     acc,
                                     reweight_pu=('nopu' in distribution))
                # scale_xs_lumi(h)
                h = merge_datasets(h)
                h = h.integrate(h.axis('region'), region)
                s = Style()

                # Rebin
                newax = hist.Bin('recoil', 'Recoil (GeV)', bins)
                h = h.rebin(h.axis(newax.name), newax)

                # Retrieve input from fit diagnostics
                f = uproot.open(fitfile)
                tg2016 = f['shapes_prefit'][regions[region]]['data']

                # Prepare x and y values for easy plotting
                x, y = {}, {}
                # x[2016] = np.r_[0.5*(h2016.bins[:,0] + h2016.bins[:,1]),1500., 1700., 1900.]
                x['2016orig'] = np.r_[tg2016.xvalues]
                y['2016orig'] = np.r_[tg2016.yvalues / lumi(2016)]
                h2016 = h[sel_2016].integrate('dataset')
                h2017 = h[sel_2017].integrate('dataset')
                h2018 = h[sel_2018].integrate('dataset')

                x[2016] = h2016.axis('recoil').centers()
                y[2016] = h2016.values()[()] / (np.diff(
                    h2016.axis('recoil').edges())) / lumi(2016)
                x[2017] = h2017.axis('recoil').centers()
                y[2017] = h2017.values()[()] / (np.diff(
                    h2017.axis('recoil').edges())) / lumi(2017)
                x[2018] = h2018.axis('recoil').centers()
                y[2018] = h2018.values()[()] / (np.diff(
                    h2018.axis('recoil').edges())) / lumi(2018)

                # Actual plotting
                for year in x.keys():
                    print(x[year])
                    ax.plot(x[year],
                            y[year],
                            'o-',
                            label=f'{year} ({sum(y[year]*np.diff(bins)):.2e})')
                    rax.plot(x[year], y[year] / y['2016orig'], '-o')

                ax.legend(title=region)
                ax.set_yscale('log')
                rax.set_xlabel(distribution)
                ax.set_xlabel(distribution)
                rax.set_ylabel('Ratio to 2016')
                ax.set_ylabel('Data cross section / bin')
                loc1 = matplotlib.ticker.MultipleLocator(base=0.2)
                loc2 = matplotlib.ticker.MultipleLocator(base=0.1)
                rax.yaxis.set_major_locator(loc1)
                rax.yaxis.set_minor_locator(loc2)
                rax.grid(axis='y', which='minor', linestyle='--')
                rax.grid(axis='y', which='major', linestyle='--')
                rax.set_ylim(0.5, 1.5)
                fig.savefig(f'output/{mode}_{region}.pdf')