Exemplo n.º 1
0
 def doHistFunc(self, name, hist, varlist, interpolate=0):
     "method to conveniently create a RooHistFunc from a TH1/TH2 input"
     print 'Doing histFunc %s...' % name
     if self.dbg_file:
         self.dbg_file.WriteTObject(hist, name)
     if self.mk_plots:
         canv = ROOT.TCanvas(name, name)
         pads = plot.OnePad()
         hist.GetXaxis().SetTitle(varlist[0].GetTitle())
         hist.GetYaxis().SetTitle(varlist[1].GetTitle())
         hist.Draw('COLZ')
         plot.DrawTitle(pads[0], name, 3)
         canv.Print('model_' + name + '.pdf')
         canv.Print('model_' + name + '.png')
         pads[0].SetLogz(True)
         canv.Print('model_' + name + '_log.pdf')
         canv.Print('model_' + name + '_log.png')
     dh = ROOT.RooDataHist('dh_%s' % name, 'dh_%s' % name,
                           ROOT.RooArgList(*varlist),
                           ROOT.RooFit.Import(hist))
     hfunc = ROOT.RooHistFunc(name, name, ROOT.RooArgSet(*varlist), dh)
     hfunc.setInterpolationOrder(interpolate)
     self.modelBuilder.out._import(hfunc,
                                   ROOT.RooFit.RecycleConflictNodes())
     return self.modelBuilder.out.function(name)
Exemplo n.º 2
0
def Compare(w, output, fn1, fn2, bins, var, other_vars= {}, line_pos=None):
    label_vars = []
    for key, val in other_vars.iteritems():
        w.var(key).setVal(val)
        label_vars.append('%s=%g' % (key, val))
    h1 = w.function(fn1).createHistogram(fn1, w.var(var),
            ROOT.RooFit.Binning(*bins),
            ROOT.RooFit.Scaling(False)
        )
    h2 = w.function(fn2).createHistogram(fn2, w.var(var),
            ROOT.RooFit.Binning(*bins),
            ROOT.RooFit.Scaling(False)
        )
    canv = ROOT.TCanvas(output, output)
    pads = plot.TwoPadSplit(0.30, 0.01, 0.01)
    pads[0].cd()
    pads[0].SetGrid(1, 1)
    plot.Set(h1, LineColor=ROOT.kBlack, LineWidth=2)
    plot.Set(h1.GetYaxis(), Title='Efficiency')
    plot.Set(h2, LineColor=ROOT.kRed, LineWidth=2)

    for i in xrange(1, h1.GetNbinsX()+1):
        h1.SetBinError(i, 0.)
    for i in xrange(1, h2.GetNbinsX()+1):
        h2.SetBinError(i, 0.)
    h1.Draw('L')
    h2.Draw('LSAME')
    ratio = h1.Clone()
    ratio.Divide(h2)


    legend = ROOT.TLegend(0.18, 0.82, 0.6, 0.93, '', 'NBNDC')
    legend.AddEntry(h1, fn1, 'L')
    legend.AddEntry(h2, fn2, 'L')
    legend.Draw()
    print plot.GetPadYMax(pads[0])
    plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.25)
    plot.DrawTitle(pads[0], ','.join(label_vars), 1)

    line = ROOT.TLine()
    plot.Set(line, LineColor=12, LineStyle=4, LineWidth=2)
    if line_pos is not None:
        plot.DrawVerticalLine(pads[0], line, line_pos)

    pads[1].cd()
    pads[1].SetGrid(1, 1)
    ratio.Draw('L')
    plot.SetupTwoPadSplitAsRatio(
        pads, plot.GetAxisHist(
            pads[0]), plot.GetAxisHist(pads[1]), 'Ratio', True, 0.91, 1.09)
    if line_pos is not None:
        plot.DrawVerticalLine(pads[1], line, line_pos)
    canv.Print('.pdf')
    canv.Print('.png')
Exemplo n.º 3
0
    else: 
        latex.DrawLatex(0.65,0.56,"#sigma(gg#phi)=%(r_ggH)s pb,"%vars())
        latex.DrawLatex(0.65,0.52,"#sigma(bb#phi)=%(r_bbH)s pb"%vars())
if not args.bkg_fractions: legend.Draw("same")
latex2 = ROOT.TLatex()
latex2.SetNDC()
latex2.SetTextAngle(0)
latex2.SetTextColor(ROOT.kBlack)
latex2.SetTextSize(0.028)
latex2.DrawLatex(0.145,0.955,channel_label)


#CMS and lumi labels
plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), extra_pad if extra_pad>0 else 0.30)
plot.DrawCMSLogo(pads[0], 'CMS', 'Preliminary', 11, 0.045, 0.05, 1.0, '', 1.0)
plot.DrawTitle(pads[0], args.lumi, 3)

#Add ratio plot if required
if args.ratio and not soverb_plot and not fractions:
  ratio_bkghist = plot.MakeRatioHist(bkghist,bkghist,True,False)
  blind_datahist = plot.MakeRatioHist(blind_datahist,bkghist,True,False)
  pads[1].cd()
  pads[1].SetGrid(0,1)
  axish[1].Draw("axis")
  axish[1].SetMinimum(float(args.ratio_range.split(',')[0]))
  axish[1].SetMaximum(float(args.ratio_range.split(',')[1]))
  ratio_bkghist.SetMarkerSize(0)
  ratio_bkghist.Draw("e2same")
  blind_datahist.DrawCopy("e0same")
  pads[1].RedrawAxis("G")
Exemplo n.º 4
0
def MakeMultiHistPlot(name, outdir, hists, cfg, layout, ratios=None):
    js_workaround = False
    copyhists = {}
    for hname, h in hists.iteritems():
        if len(cfg['rebinvar']):
            copyhists[hname] = VariableRebin(h, cfg['rebinvar'])
        else:
            copyhists[hname] = h.Clone()
        if cfg['norm_to'] > 0.:
            copyhists[hname].Scale(cfg['norm_to'] /
                                   copyhists[hname].Integral())
        if cfg['divwidth']:
            copyhists[hname].Scale(1., 'width')

    hists = copyhists

    # Canvas and pads
    if cfg['pads'] is not None:
        pads = cfg['pads']
    elif cfg['ratio'] or cfg['fraction']:
        canv = ROOT.TCanvas(name, name)
        if cfg['purity']:
            pads = plot.MultiRatioSplit([0.27, 0.13], [0.005, 0.005],
                                        [0.005, 0.005])
        else:
            # if js_workaround:
            #     upper = ROOT.TPad('upper', 'upper', 0., cfg['ratio_pad_frac'], 1., 1.)
            #     upper.SetBottomMargin(0.01)
            #     # upper.SetFillStyle(4000)
            #     upper.Draw()
            #     lower = ROOT.TPad('lower', 'lower', 0., 0., 1., cfg['ratio_pad_frac'])
            #     lower.SetTopMargin(0.01)
            #     # lower.SetFillStyle(4000)
            #     lower.Draw()
            #     upper.cd()
            #     pads = [upper, lower]
            # else:
            #     pads = plot.TwoPadSplit(cfg['ratio_pad_frac'], 0.01, 0.01)
            pads = plot.TwoPadSplit(cfg['ratio_pad_frac'], 0.01, 0.01)

    else:
        canv = ROOT.TCanvas(name, name)
        pads = plot.OnePad()

    # Allow the user to skip specifying a list of entries for a given plot element.
    # If it's not been specified then we will add it manually
    for info in layout:
        if 'entries' not in info:
            info['entries'] = [info['name']]
        for opt in cfg['global_hist_opts']:
            if opt not in info:
                info[opt] = cfg['global_hist_opts'][opt]

    h_data = None
    if cfg['type'] == 'datamc':
        # Get the data and create axis hist
        h_data = hists[cfg['data_name']]
    else:
        h_data = hists[layout[0]['entries'][0]]

    if isinstance(h_data, ROOT.TH2):
        print 'TH2: aborting!'
        return

    h_axes = [h_data.Clone() for x in pads]
    for h in h_axes:
        h.SetTitle("")
        if len(cfg['x_range']):
            h.GetXaxis().SetRangeUser(*cfg['x_range'])
        h.Reset()

    build_h_tot = True
    h_tot = None
    if 'TotalProcs' in hists:
        h_tot = hists['TotalProcs']
        build_h_tot = False
    if cfg['type'] != 'datamc':
        build_h_tot = False

    if isinstance(cfg['x_title'], list) or isinstance(cfg['x_title'], tuple):
        x_title = cfg['x_title'][0]
        units = cfg['x_title'][1]
    else:
        x_title = cfg['x_title']
        units = ''

    if x_title == '' and h_data.GetXaxis().GetTitle() != '':
        x_title = h_data.GetXaxis().GetTitle()

    if ':' in x_title:
        units = x_title.split(':')[1]
        x_title = x_title.split(':')[0]

    if cfg['logy']:
        pads[0].SetLogy()
        h_axes[0].SetMinimum(cfg['logy_min'])

    rpad_idx = len(pads) - 1

    if cfg['ratio'] or cfg['fraction']:
        plot.StandardAxes(h_axes[rpad_idx].GetXaxis(), h_axes[0].GetYaxis(),
                          x_title, units)
    else:
        plot.StandardAxes(h_axes[0].GetXaxis(), h_axes[0].GetYaxis(), x_title,
                          units)
    h_axes[0].Draw()

    # A dict to keep track of the hists
    h_store = {}
    p_store = {}

    legend = ROOT.TLegend(*(cfg['legend_pos'] + ['', 'NBNDC']))
    stack = ROOT.THStack()
    purity_stack = ROOT.THStack()

    curr_auto_colour = 0
    for info in layout:
        hist = hists[info['entries'][0]]
        if 'color' in info:
            col = info['color']
        else:
            col = AUTO_COLOURS[curr_auto_colour]
            if curr_auto_colour == (len(AUTO_COLOURS) - 1):
                curr_auto_colour = 0
            else:
                curr_auto_colour += 1
        # col = info['color']
        if isinstance(col, list):
            col = ROOT.TColor.GetColor(*col)
        # print info['line_width']
        if cfg['type'] == 'multihist':
            plot.Set(hist,
                     FillColor=col,
                     MarkerColor=col,
                     LineColor=col,
                     Title=info['legend'],
                     MarkerSize=info['marker_size'],
                     LineWidth=info['line_width'])
        else:
            plot.Set(hist,
                     FillColor=col,
                     MarkerColor=col,
                     Title=info['legend'],
                     MarkerSize=info['marker_size'],
                     LineWidth=info['line_width'])
        if len(info['entries']) > 1:
            for other in info['entries'][1:]:
                hist.Add(hists[other])
        h_store[info['name']] = hist
        p_store[info['name']] = hist.Clone()
        if build_h_tot:
            if h_tot is None:
                h_tot = hist.Clone()
            else:
                h_tot.Add(hist)
        if cfg['type'] == 'datamc':
            stack.Add(hist)
        else:
            hist.Draw('SAME%s' % info['draw_opts'])

    # h_tot_purity = h_tot.Clone()
    for info in layout:
        p_store[info['name']].Divide(h_tot)
        purity_stack.Add(p_store[info['name']])

    if cfg['type'] == 'datamc':
        h_tot.SetFillColor(plot.CreateTransparentColor(12, 0.3))
        h_tot.SetMarkerSize(0)
        legend.AddEntry(h_data, 'Observed', 'PL')

    # Build overlays
    for info in cfg['overlays']:
        hist = None
        input_list = []
        if isinstance(info['entries'], str):
            input_list = list(all_input_hists)
        else:
            input_list = list(info['entries'])
        updated_list = []
        for xh in input_list:
            if xh + info['hist_postfix'] in hists:
                updated_list.append(xh + info['hist_postfix'])
            else:
                updated_list.append(xh)
        print updated_list
        hist = HistSum(hists, updated_list)
        col = info['color']
        if isinstance(col, list):
            col = ROOT.TColor.GetColor(*col)
        plot.Set(hist,
                 LineColor=col,
                 LineWidth=1,
                 MarkerSize=0,
                 Title=info['legend'])
        for ib in xrange(1, hist.GetNbinsX() + 1):
            hist.SetBinError(ib, 1E-7)
        h_store[info['name']] = hist

    if cfg['type'] == 'datamc':
        for ele in reversed(layout):
            legend.AddEntry(h_store[ele['name']], ele['legend'],
                            ele['legend_opts'])
    else:
        for ele in layout:
            leg_extra = ''
            if cfg['legend_show_yields']:
                leg_extra = ' (%.1f)' % h_store[ele['name']].Integral(
                    'width' if cfg['divwidth'] else '')
            legend.AddEntry(h_store[ele['name']], ele['legend'] + leg_extra,
                            ele['legend_opts'])

    if cfg['type'] == 'datamc':
        bkg_uncert_label = 'Stat. Uncertainty'
        if not build_h_tot:
            bkg_uncert_label = 'Uncertainty'
        legend.AddEntry(h_tot, bkg_uncert_label, 'F')

        stack.Draw('HISTSAME')
        h_tot.Draw("E2SAME")

        for info in cfg['overlays']:
            h_store[info['name']].Draw('HISTSAME')

        if not cfg['hide_data']:
            h_data.Draw('E0SAME')

    for info in cfg['overlays']:
        legend.AddEntry(h_store[info['name']], info['legend'], 'L')

    plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.35)
    legend.Draw()
    # if cfg['legend_padding'] > 0.:
    #     plot.FixBoxPadding(pads[0], legend, cfg['legend_padding'])

    # Do the ratio plot
    r_store = {}
    r_data = None
    r_tot = None
    if cfg['ratio'] or cfg['fraction']:
        pads[rpad_idx].cd()
        pads[rpad_idx].SetGrid(0, 1)
        h_axes[rpad_idx].Draw()

        if cfg['type'] == 'datamc' and cfg['ratio']:
            r_data = plot.MakeRatioHist(h_data, h_tot, True, False)
            r_tot = plot.MakeRatioHist(h_tot, h_tot, True, False)
            r_tot.Draw('E2SAME')
            for info in cfg['overlays']:
                r_store[info['name']] = plot.MakeRatioHist(
                    h_store[info['name']], h_tot, False, False)
                r_store[info['name']].Draw('SAME')
            if not cfg['hide_data']:
                r_data.Draw('SAME')

        if cfg['type'] == 'datamc' and cfg['fraction']:
            r_frac = plot.MakeRatioHist(h_tot, h_data, True, True)
            r_frac.Draw('SAME')
            plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]),
                                         plot.GetAxisHist(pads[rpad_idx]),
                                         'Exp/Obs', True, 0.0, 0.5)

        if ratios is not None:
            for info in ratios:
                if 'type' in info and info['type'] == 'binomial':
                    rhist = h_store[info['num']].Clone()
                    rhist.Divide(h_store[info['num']], h_store[info['den']],
                                 1., 1., "B")
                elif 'type' in info and info['type'] == 'noerror':
                    rhist = plot.MakeRatioHist(h_store[info['num']],
                                               h_store[info['den']], True,
                                               False)
                else:
                    rhist = plot.MakeRatioHist(h_store[info['num']],
                                               h_store[info['den']], True,
                                               True)
                r_store['%s_%s' % (info['num'], info['den'])] = rhist
                rhist.Draw('SAMEE0')

        plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]),
                                     plot.GetAxisHist(pads[rpad_idx]),
                                     cfg['ratio_y_title'], True,
                                     *(cfg['ratio_y_range']))
        if js_workaround:
            # This makes the ticks way too large
            plot.GetAxisHist(pads[rpad_idx]).GetYaxis().SetTickLength(
                ROOT.gStyle.GetTickLength())

    if cfg['purity']:
        pads[1].cd()
        h_axes[1].Draw()
        plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]),
                                     plot.GetAxisHist(pads[1]), 'f', True, 0,
                                     1)
        plot.Set(h_axes[1].GetXaxis(), TitleSize=0, LabelSize=0)
        plot.Set(h_axes[1].GetYaxis(), Ndivisions=(502, False))
        purity_stack.Draw('HISTSAME')
        # purity_stack.Print()
        h_axes[1].SetMinimum(0)
        h_axes[1].SetMaximum(1)
        pads[1].RedrawAxis()

    # Go back and tidy up the axes and frame
    pads[0].cd()
    if not js_workaround:
        pads[0].GetFrame().Draw()
        pads[0].RedrawAxis()

    # CMS logo
    plot.DrawCMSLogo(pads[0], cfg['main_logo'], cfg['sub_logo'], 11, 0.045,
                     0.05, 1.0, '', 1.0)
    plot.DrawTitle(pads[0], cfg['top_title_left'], 1)
    if cfg['auto_top_title_right']:
        title_right = h_data.GetTitle()
        if title_right.startswith('lumi:'):
            plot.DrawTitle(pads[0], title_right.replace('lumi:', ''), 3)

    latex = ROOT.TLatex()
    plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03)
    # latex.DrawLatex(0.20, 0.75, args.title)
    # plot.DrawTitle(pads[0], args.title, 1)

    # ... and we're done
    if cfg['pads'] is None:
        canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] +
                   '.png')
        canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] +
                   '.pdf')
        # canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.root')
        # canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.svg')
        # canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.json')

    outobjs = {}
    outobjs['axes'] = h_axes
    outobjs['hists'] = hists
    outobjs['stack'] = stack
    outobjs['purity_stack'] = purity_stack
    outobjs['h_tot'] = h_tot
    outobjs['legend'] = legend
    outobjs['r_store'] = r_store
    outobjs['p_store'] = p_store
    outobjs['r_data'] = r_data
    outobjs['r_tot'] = r_tot
    return outobjs
Exemplo n.º 5
0
        for name, h in color_group_hists.iteritems():
            legend2.AddEntry(h, Translate(name, translate), 'F')
        legend2.Draw()
    elif len(seen_types) > 1:
        legend2 = ROOT.TLegend(0.01, 0.94, 0.30, 0.99, '', 'NBNDC')
        legend2.SetNColumns(2)
        for name, h in color_hists.iteritems():
            if name == 'Unrecognised': continue
            legend2.AddEntry(h, name, 'F')
        legend2.Draw()

    #plot.DrawCMSLogo(pads[0], 'CMS', args.cms_label, 0, 0.25, 0.00, 0.00)
    if args.POI == "MT":
        if args.splitUnc or args.uncDisplay == "syststat":
            plot.DrawTitle(pads[1], "#hat{%s} = %.2f #pm %.2f(stat) #pm %.2f(syst)%s" % (
                Translate("m_{ t}", translate), POI_fit[1], statUnc, systUnc,
                '' if args.units is None else ' '+args.units),3)
        elif args.uncDisplay == "both":
            plot.DrawTitle(pads[1], "#hat{%s} = %.2f #pm %.2f (%.2f(stat) #pm %.2f(syst)%s)" % (
                Translate("m_{ t}", translate), POI_fit[1], (POI_fit[2] - POI_fit[0]) / 2.,statUnc, systUnc,
                '' if args.units is None else ' '+args.units),3)
        else:
            plot.DrawTitle(pads[1], "#hat{%s} = %.2f #pm %.2f%s" % (
                Translate("m_{ t}", translate), POI_fit[1], (POI_fit[2] - POI_fit[0]) / 2.,
                '' if args.units is None else ' '+args.units),3)
    else:
        plot.DrawTitle(pads[1], "#hat{%s} = %.2g #pm %.2g%s" % (
            Translate(POIs[selectedPOI], translate), POI_fit[1], (POI_fit[2] - POI_fit[0]) / 2.,
            '' if args.units is None else ' '+args.units),3)
    extra = ''
    if page == 0:
Exemplo n.º 6
0
    gr_invalid.Draw('2SAME')

for gr in graphs:
    gr.Draw('ZPSAME')
gr_fit.Draw('PSAME')

pads[0].RedrawAxis()

title_box = ROOT.TPaveText(xmin + (xmax - xmin) * 0.01,
                           float(N) + 0.3, xmin + (xmax - xmin) * 0.65,
                           float(N + 1) - 0.2, 'NB')
title_box.SetTextFont(42)
title_box.SetTextAlign(12)
title_box.AddText('#scale[1.4]{#bf{CMS}}')
# title_box.AddText('#scale[0.5]{%s}' % '')
plot.DrawTitle(pads[0], args.subline, 3)
title_box.SetMargin(0.0)
title_box.Draw()

frame_h = 1. - pads[0].GetBottomMargin() - pads[0].GetTopMargin()
frame_frac = pads[0].GetBottomMargin() + (frame_h *
                                          ((float(N) - 0.4) / float(N + 1)))
legend = ROOT.TLegend(0.66, frame_frac, 0.95, 0.945, '', 'NBNDC')
legend.AddEntry(gr_fit, 'Observed', 'P')

for bar in args.legend.split(','):
    i = bars.index(bar)
    legend.AddEntry(graphs[i], default_bar_labels[bar], 'L')
legend.Draw()

# plot.DrawCMSLogo(pads[0], 'CMS',
Exemplo n.º 7
0
    h_axes[1].Draw()

    r_data = plot.MakeRatioHist(h_data, h_tot, True, False)
    r_tot = plot.MakeRatioHist(h_tot, h_tot, True, False)
    r_tot.Draw('E2SAME')
    r_data.Draw('SAME')

    plot.SetupTwoPadSplitAsRatio(
        pads, plot.GetAxisHist(
            pads[0]), plot.GetAxisHist(pads[1]), 'Obs/Exp', True, 0.61, 1.39)

    # Go back and tidy up the axes and frame
    pads[0].cd()
    pads[0].GetFrame().Draw()
    pads[0].RedrawAxis()

    # CMS logo
    plot.DrawCMSLogo(pads[0], 'CMS', 'Internal', 11, 0.045, 0.05, 1.0, '', 1.0)
    plot.DrawTitle(pads[0], '12.9 fb^{-1} (13 TeV)', 3)

    latex = ROOT.TLatex()
    plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03)
    latex.DrawLatex(0.20, 0.75, args.title)
    # plot.DrawTitle(pads[0], args.title, 1)

    # ... and we're done
    canv.Print('.png')
    canv.Print('.pdf')


Exemplo n.º 8
0
axish[0].Draw()
LOMC_Z_mass.Draw("HISTSAME")
LOMC_Z_mass_unc.Draw("e2same")
data_Z_mass.Draw("PSAME")
legend = plot.PositionedLegend(0.2, 0.1, 3, 0.015)
legend.AddEntry(LOMC_Z_mass, "Z#rightarrow ee", "F")
legend.AddEntry(data_Z_mass, "Data", "P")
legend.Draw("SAME")
axish[0].Draw("axissame")
pads[1].cd()
axish[1].Draw("axis")
ratio_mchist.SetMarkerSize(0)
ratio_mchist.Draw("e2same")
ratio_datahist.Draw("e0same")
pads[1].RedrawAxis("G")
plot.DrawTitle(pads[0], "41.5 fb^{-1} (13 TeV-2017)", 3)

canvas.SaveAs("mee_inclusive_nlo_weight_2017.pdf")
#canvas.SaveAs("mmumu_inclusive_weight.pdf")

canvas2 = ROOT.TCanvas("c1", "c1")
pads2 = plot.TwoPadSplit(0.29, 0.01, 0.01)
axish2 = createAxisHists(2, LOMC_Z_pt,
                         LOMC_Z_pt.GetXaxis().GetXmin(),
                         LOMC_Z_pt.GetXaxis().GetXmax() - 0.01)
pads2[0].SetLogy()
axish2[0].GetYaxis().SetRangeUser(1, 12 * LOMC_Z_pt.GetMaximum())
axish2[0].GetXaxis().SetTitleSize(0)
axish2[0].GetXaxis().SetLabelSize(0)
axish2[1].GetYaxis().SetRangeUser(0.8, 1.2)
axish2[1].GetXaxis().SetTitle("p_{T}(ee) [GeV]")
Exemplo n.º 9
0
def main(args):

    fitvars = 'm_sv_vs_pt_tt'
    fitvars = 'm_sv'

    if len(args.file_dir.split("_")) >= 4: era = args.file_dir.split("_")[3]
    else: era = 'all'
    if era == "2016":
        lumi = "36.3 fb^{-1} (13 TeV)"
    elif era == "2017":
        lumi = "41.5 fb^{-1} (13 TeV)"
    elif era == "2018":
        lumi = "59.7 fb^{-1} (13 TeV)"
    elif era == "all":
        lumi = "138 fb^{-1} (13 TeV)"

    plot.ModTDRStyle(width=1800, height=700, r=0.4, l=0.16, t=0.12, b=0.15)
    ROOT.TGaxis.SetExponentOffset(-0.06, 0.01, "y")
    # Channel & Category label

    if args.channel == '':
        args.channel = args.file_dir.split("_")[1]
    if args.channel == "tt":
        channel_label = "#tau_{h}#tau_{h}"
    if args.channel == "lt":
        channel_label = "#mu_{}#tau_{h}+e_{}#tau_{h}"
    if args.channel == "mt":
        channel_label = "#mu_{}#tau_{h}"
    if args.channel == "et":
        channel_label = "e_{}#tau_{h}"
    if args.channel == "em":
        channel_label = "e_{}#mu_{}"

    bin_number = args.file_dir.split("_")[2]
    #if args.ratio_range=="":
    #  args.ratio_range = "0.7,1.3"
    if bin_number in ["2", "35", "36", "37"]:
        if args.channel == 'tt': bin_label = "b tag"
        if args.channel in ['mt', 'et', 'lt']:
            bin_label = "b tag"
            if bin_number == "35": bin_label = "b tag, Tight-m_{T}"
            if bin_number == "36": bin_label = "b tag, Loose-m_{T}"
        if args.channel in ['em']:
            bin_label = "b tag"
            if bin_number == "2": bin_label = "t#bar{t} CR"
            if bin_number == "35": bin_label = "b tag, High D_{#zeta}"
            if bin_number == "36": bin_label = "b tag, Medium D_{#zeta}"
            if bin_number == "37": bin_label = "b tag, Low D_{#zeta}"
        plot.ModTDRStyle(r=0.04, l=0.18)
        if args.ratio_range == "":
            args.ratio_range = "0.85,1.15"
        bin_label = "b tag"  # no sub labels when combing all sub-categories
    if bin_number in ["32", "33", "34"]:
        if args.ratio_range == "":
            args.ratio_range = "0.4,1.6"
        if args.channel == 'tt': bin_label = "No b tag"
        if args.channel in ['mt', 'et', 'lt']:
            bin_label = "No b tag"
            if bin_number == "32": bin_label = "No b tag, Tight-m_{T}"
            if bin_number == "33": bin_label = "No b tag, Loose-m_{T}"
        if args.channel in ['em']:
            bin_label = "No b tag"
            if bin_number == "32": bin_label = "No b tag, High D_{#zeta}"
            if bin_number == "33": bin_label = "No b tag, Medium D_{#zeta}"
            if bin_number == "34": bin_label = "No b tag, Low D_{#zeta}"
        bin_label = "b tag"  # no sub labels when combing all sub-categories

    if bin_number in [
            "132", "232", "332", "432", "133", "233", "333", "433", "33", "34"
    ]:
        if args.ratio_range == "":
            args.ratio_range = "0.7,1.3"
        if args.channel == 'tt': bin_label = "No b tag"
        if args.channel in ['mt', 'et', 'lt']:
            bin_label = "No b tag"
            if bin_number[1:] == "32": bin_label = "No b tag, Tight-m_{T}"
            if bin_number[1:] == "33": bin_label = "No b tag, Loose-m_{T}"
        if args.channel in ['em']:
            bin_label = "No b tag"
            if bin_number[1:] == "32": bin_label = "No b tag, High D_{#zeta}"
            if bin_number[1:] == "33": bin_label = "No b tag, Medium D_{#zeta}"
            if bin_number[1:] == "34": bin_label = "No b tag, Low D_{#zeta}"

        bin_label = "No b tag"  # no sub labels when combing all sub-categories
        if bin_number[0] == '1': bin_label += ', p_{T}^{#tau#tau}<50 GeV'
        if bin_number[0] == '2': bin_label += ', 50< p_{T}^{#tau#tau}<100 GeV'
        if bin_number[0] == '3': bin_label += ', 100< p_{T}^{#tau#tau}<200 GeV'
        if bin_number[0] == '4': bin_label += ', p_{T}^{#tau#tau}> 200 GeV'
        plot.ModTDRStyle(r=0.04, l=0.18)

    ## Add bin labels
    bin_labels = {}
    with open("scripts/bin_labels.json") as jsonfile:
        full_bin_labels = json.load(jsonfile)
        if bin_number in ["32", "33", "34"]:
            bin_labels = full_bin_labels[fitvars]['nobtag']
        else:
            bin_labels = full_bin_labels[fitvars]['btag']

    is2D = False

    print fitvars, bin_number
    if fitvars == 'm_sv' or bin_number in [
            "2", "35", "36", "37", "132", "232", "332", "432", "133", "233",
            "333", "433"
    ]:
        x_title = "m_{#tau#tau} (GeV)"
        #x_bins = re.split("\[|\]",bin_labels)[1].split(",")
        #Nxbins = len(x_bins) - 1
    else:
        is2D = True
        x_title = "Bin number"
        x_bins = re.split("\[|\]", bin_labels)[3].split(",")
        Nxbins = len(x_bins) - 1

    if is2D:
        y_bin_var = re.split(",|\[|\]", bin_labels)[0]
        y_bin_labels = re.split("\[|\]", bin_labels)[1].split(",")
    else:
        y_bin_var = ""
        y_bin_labels = ""

    is2D = False  # we now split 2D histograms into 1D

    file_dir = args.file_dir
    mode = args.mode
    manual_blind = args.manual_blind
    x_blind_min = args.x_blind_min
    x_blind_max = args.x_blind_max
    cms_label = args.cms_label
    empty_bin_error = args.empty_bin_error
    extra_pad = float(args.extra_pad)
    custom_x_range = args.custom_x_range
    custom_y_range = args.custom_y_range
    x_axis_min = float(args.x_axis_min)
    x_axis_max = float(args.x_axis_max)
    y_axis_min = float(args.y_axis_min)
    y_axis_max = float(args.y_axis_max)
    log_y = args.log_y
    log_x = args.log_x
    if (args.outname != ''):
        outname = args.outname + '_'
    else:
        outname = ''

    if args.file_dir == "htt_tt_232": extra_pad = 0.45
    if args.file_dir == "htt_tt_35": extra_pad = 0.57
    if args.file_dir == "htt_tt_132": extra_pad = 0.65
    if args.file_dir == "htt_tt_232": extra_pad = 0.62
    if args.file_dir == "htt_em_35": extra_pad = 0.7
    if args.file_dir == "htt_lt_35": extra_pad = 0.45
    if args.file_dir == "htt_lt_232": extra_pad = 0.45
    if args.file_dir == "htt_em_232": extra_pad = 0.45
    if '_35' in args.file_dir or '_132' in args.file_dir or '_232' in args.file_dir or args.bOnly:
        cms_label = 'Supplementary'

    if args.file:
        print "Providing shape file: ", args.file, ", with specified subdir name: ", file_dir
        shape_file = args.file
        shape_file_name = args.file

    histo_file = ROOT.TFile(shape_file)

    #Store plotting information for different backgrounds
    background_schemes = {
        'mt': [
            backgroundComp("Others",
                           ["ZL", "VVL", "qqH125", "bbH125", "ggH125"],
                           ROOT.TColor.GetColor("#B0C4DE")),
            #backgroundComp("H(125 GeV)#rightarrow#tau#tau",["qqH125","bbH125","ggH125"],ROOT.TColor.GetColor(51,51,230)),
            #backgroundComp("Diboson",["VVL"],ROOT.TColor.GetColor("#6F2D35")),
            backgroundComp("t#bar{t}", ["TTL"],
                           ROOT.TColor.GetColor("#9999cc")),
            #backgroundComp("Z#rightarrowll",["ZL"],ROOT.TColor.GetColor("#4496c8")),
            backgroundComp("Jet#rightarrow#tau_{h}", ["jetFakes"],
                           ROOT.TColor.GetColor(192, 232, 100)),
            backgroundComp("#tau#tau Bkg.", ["EMB"],
                           ROOT.TColor.GetColor("#ffcc66")),
        ],
        'et': [
            backgroundComp("Others",
                           ["ZL", "VVL", "qqH125", "bbH125", "ggH125"],
                           ROOT.TColor.GetColor("#B0C4DE")),
            #backgroundComp("H(125 GeV)#rightarrow#tau#tau",["qqH125","bbH125","ggH125"],ROOT.TColor.GetColor(51,51,230)),
            #backgroundComp("Diboson",["VVL"],ROOT.TColor.GetColor("#6F2D35")),
            backgroundComp("t#bar{t}", ["TTL"],
                           ROOT.TColor.GetColor("#9999cc")),
            #backgroundComp("Z#rightarrowll",["ZL"],ROOT.TColor.GetColor("#4496c8")),
            backgroundComp("Jet#rightarrow#tau_{h}", ["jetFakes"],
                           ROOT.TColor.GetColor(192, 232, 100)),
            backgroundComp("#tau#tau Bkg.", ["EMB"],
                           ROOT.TColor.GetColor("#ffcc66")),
        ],
        'lt': [
            backgroundComp("Others",
                           ["ZL", "VVL", "qqH125", "bbH125", "ggH125"],
                           ROOT.TColor.GetColor("#B0C4DE")),
            #backgroundComp("H(125 GeV)#rightarrow#tau#tau",["qqH125","bbH125","ggH125"],ROOT.TColor.GetColor(51,51,230)),
            #backgroundComp("Diboson",["VVL"],ROOT.TColor.GetColor("#6F2D35")),
            backgroundComp("t#bar{t}", ["TTL"],
                           ROOT.TColor.GetColor("#9999cc")),
            #backgroundComp("Z#rightarrowll",["ZL"],ROOT.TColor.GetColor("#4496c8")),
            backgroundComp("Jet#rightarrow#tau_{h}", ["jetFakes"],
                           ROOT.TColor.GetColor(192, 232, 100)),
            backgroundComp("#tau#tau Bkg.", ["EMB"],
                           ROOT.TColor.GetColor("#ffcc66")),
        ],
        'tt': [
            backgroundComp("Others",
                           ["ZL", "VVL", "qqH125", "bbH125", "ggH125"],
                           ROOT.TColor.GetColor("#B0C4DE")),
            #backgroundComp("H(125 GeV)#rightarrow#tau#tau",["qqH125","bbH125","ggH125"],ROOT.TColor.GetColor(51,51,230)),
            #backgroundComp("Diboson",["VVL"],ROOT.TColor.GetColor("#6F2D35")),
            backgroundComp("t#bar{t}", ["TTL"],
                           ROOT.TColor.GetColor("#9999cc")),
            #backgroundComp("Z#rightarrowll",["ZL"],ROOT.TColor.GetColor("#4496c8")),
            backgroundComp("Jet#rightarrow#tau_{h}", ["jetFakes", "wFakes"],
                           ROOT.TColor.GetColor(192, 232, 100)),
            backgroundComp("#tau#tau Bkg.", ["EMB"],
                           ROOT.TColor.GetColor("#ffcc66")),
        ],
        'em': [
            backgroundComp("Others", [
                "ZL", "qqH125", "bbH125", "ggH125", 'WHWW125', 'ZHWW125',
                'ggHWW125', 'qqHWW125', "W", "VVL"
            ], ROOT.TColor.GetColor("#B0C4DE")),
            #backgroundComp("H(125 GeV)",["qqH125","bbH125","ggH125",'WHWW125','ZHWW125','ggHWW125','qqHWW125'],ROOT.TColor.GetColor(51,51,230)),
            backgroundComp("QCD", ["QCD"], ROOT.TColor.GetColor("#ffccff")),
            #backgroundComp("Electroweak",["W","VVL"],ROOT.TColor.GetColor(222, 90, 106)),
            backgroundComp("t#bar{t}", ["TTL"],
                           ROOT.TColor.GetColor("#9999cc")),
            #backgroundComp("Z#rightarrowll",["ZL"],ROOT.TColor.GetColor("#4496c8")),
            backgroundComp("#tau#tau Bkg.", ["EMB"],
                           ROOT.TColor.GetColor("#ffcc66")),
        ],
    }

    #Extract relevent histograms from shape file
    sighists = []

    #signal_names = 'TotalSig'
    signal_names = ['ggh_t', 'ggh_i', 'ggh_b']
    if args.no_signal: signal_names = []

    file_dir_list = []
    file_dir_list = [file_dir]

    if not args.no_signal:
        [sighist,
         binname] = getHistogram(histo_file, signal_names, file_dir_list, mode,
                                 args.no_signal, log_x)
        sighists.append(sighist)
    bkghist = getHistogram(histo_file, 'TotalBkg', file_dir, mode,
                           logx=log_x)[0]
    sbhist = bkghist.Clone()
    # can use this one for showing ggX as well as qqX
    sbhist_alt = bkghist.Clone()

    if not args.use_asimov:
        total_datahist = getHistogram(histo_file,
                                      "data_obs",
                                      file_dir,
                                      mode,
                                      logx=log_x)[0]
    else:
        total_datahist = getHistogram(histo_file,
                                      "TotalProcs",
                                      file_dir,
                                      mode,
                                      logx=log_x)[0].Clone()
        for bin_ in range(1, total_datahist.GetNbinsX() + 1):
            content = total_datahist.GetBinContent(bin_)
            total_datahist.SetBinError(bin_, np.sqrt(content))

    blind_datahist = total_datahist.Clone()
    total_datahist.SetMarkerStyle(20)
    blind_datahist.SetMarkerStyle(20)
    blind_datahist.SetLineColor(1)

    total_bkg = getHistogram(histo_file,
                             "TotalBkg",
                             file_dir,
                             mode,
                             logx=log_x)[0].Clone()
    azimov_datahist = blind_datahist.Clone()
    for i in range(0, azimov_datahist.GetNbinsX() + 1):
        azimov_datahist.SetBinContent(i, -0.1)
        azimov_datahist.SetBinError(i, 0)

    azimov_datahist.SetLineColor(ROOT.kRed)
    azimov_datahist.SetMarkerColor(ROOT.kRed)

    #Blinding by hand using requested range, set to 70-110 by default
    # for 0jet category
    if not is2D and manual_blind:
        for i in range(0, total_datahist.GetNbinsX()):
            low_edge = total_datahist.GetBinLowEdge(i + 1)
            high_edge = low_edge + total_datahist.GetBinWidth(i + 1)
            if ((low_edge > float(x_blind_min)
                 and low_edge < float(x_blind_max))
                    or (high_edge > float(x_blind_min)
                        and high_edge < float(x_blind_max))):
                blind_datahist.SetBinContent(i + 1, -0.1)
                blind_datahist.SetBinError(i + 1, 0)
                c = total_bkg.GetBinContent(i + 1)
                azimov_datahist.SetBinContent(i + 1, c)
                azimov_datahist.SetBinError(i + 1, c**.5)
    # for boosted category:
    if is2D and manual_blind:
        x_blind_ind = [
            ind for ind, x in enumerate(x_bins) if 120 >= int(x) >= 70
        ]
        x_blind_ind1 = []

        dummy_list = [
            int(x) for x in np.linspace(Nxbins, Nxbins * Nxbins, Nxbins)
        ]
        for i in range(0, total_datahist.GetNbinsX()):
            if i in dummy_list:
                x_blind_ind1 = [x + i for x in x_blind_ind]
            if i in x_blind_ind or i in x_blind_ind1:
                blind_datahist.SetBinContent(i + 1, -0.1)
                blind_datahist.SetBinError(i + 1, 0)
                c = total_bkg.GetBinContent(i + 1)
                azimov_datahist.SetBinContent(i + 1, c)
                azimov_datahist.SetBinError(i + 1, c**.5)

    #Set bin errors for empty bins if required:
    if empty_bin_error:
        for i in range(1, blind_datahist.GetNbinsX() + 1):
            if blind_datahist.GetBinContent(i) == 0:
                blind_datahist.SetBinError(i, 1.8)
    #Set uniform bin errors properly for Content < 10 bins
    if args.proper_errors_uniform:
        proper_errs_dict = {
            0: 1.29,
            1: 2.38,
            2: 3.51,
            3: 4.20,
            4: 4.44,
            5: 5.06,
            6: 5.46,
            7: 6.05,
            8: 6.02,
            9: 6.46
        }
        for i in range(1, blind_datahist.GetNbinsX() + 1):
            if blind_datahist.GetBinContent(
                    i) < 9.5 and blind_datahist.GetBinContent(i) >= 0:
                new_err = proper_errs_dict[round(
                    blind_datahist.GetBinContent(i))]
                blind_datahist.SetBinError(i, new_err)

    #Normalise by bin width
    scale = 1.0
    if is2D:
        scale = 1. / 10.  # if we have an unrolled plot then we need to account for the bins being in 10 GeV units
    bkghist.Scale(scale, "width")
    sbhist.Scale(scale, "width")

    for shist in sighists:
        if mode == 'prefit':
            shist.Scale(6.0 * scale,
                        "width")  # can scale up signals here if desired
        else:
            shist.Scale(scale, "width")  # can scale up signals here if desired

    for shist in sighists:
        sbhist.Add(shist)
    #sbhist.Scale(scale,"width")
    #sbhist_alt.Scale(scale,"width")
    blind_datahist.Scale(scale, "width")
    azimov_datahist.Scale(scale, "width")

    blind_datagraph = ROOT.TGraphAsymmErrors(blind_datahist)
    azimov_datagraph = ROOT.TGraphAsymmErrors(azimov_datahist)

    channel = args.channel

    #Create stacked plot for the backgrounds
    bkg_histos = []
    for i, t in enumerate(background_schemes[channel]):
        plots = t['plot_list']
        isHist = False
        h = ROOT.TH1F()
        for j, k in enumerate(plots):
            if h.GetEntries() == 0 and getHistogram(
                    histo_file, k, file_dir, mode, False,
                    logx=log_x) is not None:
                isHist = True
                h = getHistogram(histo_file, k, file_dir, mode, logx=log_x)[0]
                h.SetName(k)
            else:
                if getHistogram(histo_file,
                                k,
                                file_dir,
                                mode,
                                False,
                                logx=log_x) is not None:
                    isHist = True
                    h.Add(
                        getHistogram(histo_file, k, file_dir, mode,
                                     logx=log_x)[0])
        h.SetFillColor(t['colour'])
        h.SetLineColor(ROOT.kBlack)
        h.SetMarkerSize(0)

        h.Scale(scale, "width")
        if isHist:
            bkg_histos.append(h)

    stack = ROOT.THStack("hs", "")
    for hists in bkg_histos:
        stack.Add(hists)

    #Setup style related things
    c2 = ROOT.TCanvas()
    c2.cd()

    if args.ratio:
        pads = plot.TwoPadSplit(0.35, 0.01, 0.01)
    else:
        pads = plot.OnePad()

    for p in pads:
        p.SetFrameLineWidth(1)

    pads[0].cd()
    if (log_y):
        pads[0].SetLogy(1)
    if (log_x):
        pads[0].SetLogx(1)

    if custom_x_range:
        if x_axis_max > bkghist.GetXaxis().GetXmax():
            x_axis_max = bkghist.GetXaxis().GetXmax()
    if args.ratio:
        if (log_x):
            pads[1].SetLogx(1)
        axish = createAxisHists(2, bkghist,
                                bkghist.GetXaxis().GetXmin(),
                                bkghist.GetXaxis().GetXmax() - 0.01)
        axish[1].GetXaxis().SetTitle(x_title)
        if is2D:
            axish[1].GetXaxis().SetLabelSize(0.03)
        axish[1].GetYaxis().SetNdivisions(4)
        axish[1].GetYaxis().SetLabelSize(0.033)
        axish[1].GetXaxis().SetLabelSize(0.033)
        if is2D:
            axish[1].GetXaxis().SetNdivisions(bkghist.GetNbinsX() / Nxbins,
                                              Nxbins, 0, False)
        axish[0].GetYaxis().SetTitleSize(0.048)
        axish[0].GetYaxis().SetLabelSize(0.033)
        axish[0].GetYaxis().SetTitleOffset(0.5)
        axish[0].GetXaxis().SetTitleSize(0)
        axish[0].GetXaxis().SetLabelSize(0)
        if is2D:
            axish[0].GetXaxis().SetNdivisions(bkghist.GetNbinsX() / Nxbins,
                                              Nxbins, 0, False)
        axish[0].GetYaxis().SetTitleSize(axish[1].GetXaxis().GetTitleSize())
        axish[0].GetXaxis().SetRangeUser(x_axis_min,
                                         bkghist.GetXaxis().GetXmax() - 0.01)
        axish[1].GetXaxis().SetRangeUser(x_axis_min,
                                         bkghist.GetXaxis().GetXmax() - 0.01)
        axish[0].GetXaxis().SetMoreLogLabels()
        axish[0].GetXaxis().SetNoExponent()
        axish[1].GetXaxis().SetMoreLogLabels()
        axish[1].GetXaxis().SetNoExponent()
        axish[1].GetXaxis().SetTitleOffset(0.85)

        if not is2D:
            axish[0].GetXaxis().SetRangeUser(
                0.,
                bkghist.GetXaxis().GetXmax() - 0.01)
            axish[1].GetXaxis().SetRangeUser(
                0.,
                bkghist.GetXaxis().GetXmax() - 0.01)

        if custom_x_range:
            axish[0].GetXaxis().SetRangeUser(x_axis_min, x_axis_max - 0.01)
            axish[1].GetXaxis().SetRangeUser(x_axis_min, x_axis_max - 0.01)
        if custom_y_range:
            axish[0].GetYaxis().SetRangeUser(y_axis_min, y_axis_max)
            axish[1].GetYaxis().SetRangeUser(y_axis_min, y_axis_max)
    else:
        axish = createAxisHists(1, bkghist,
                                bkghist.GetXaxis().GetXmin(),
                                bkghist.GetXaxis().GetXmax() - 0.01)
        if custom_x_range:
            axish[0].GetXaxis().SetRangeUser(x_axis_min, x_axis_max - 0.01)
        if custom_y_range:
            axish[0].GetYaxis().SetRangeUser(y_axis_min, y_axis_max)
    axish[0].GetYaxis().SetTitleOffset(0.5)
    axish[1].GetYaxis().SetTitleOffset(0.5)
    axish[0].GetYaxis().SetTitle("dN/dm_{#tau#tau} (1/GeV)")
    if not is2D:
        axish[0].GetYaxis().SetTitle("dN/dm_{#tau#tau} (1/GeV)")
        #axish[0].GetYaxis().SetTitle("< Events / GeV >")
        axish[0].GetYaxis().SetTitleOffset(1.5)
        axish[1].GetYaxis().SetTitleOffset(1.5)

    axish[0].GetXaxis().SetTitle(x_title)

    if not custom_y_range:
        axish[0].SetMaximum(extra_pad * bkghist.GetMaximum())
    if not custom_y_range:
        if (log_y):
            ymin = 0.1
            axish[0].SetMinimum(ymin)
        else:
            axish[0].SetMinimum(0)

    hist_indices = [0]
    for i in hist_indices:
        pads[i].cd()
        axish[i].Draw("AXIS")

        bkghist.SetMarkerSize(0)
        bkghist.SetFillColor(2001)
        bkghist.SetLineColor(1)
        bkghist.SetLineWidth(1)
        bkghist.SetFillColor(plot.CreateTransparentColor(12, 0.4))
        bkghist.SetLineColor(0)

        #stack.Draw("histsame")
        #bkghist.Draw("e2same")
        #Add signal, either model dependent or independent
        if not args.no_signal:
            sighist.SetLineColor(ROOT.kRed)
            sighist.SetLineWidth(2)
            if not is2D:
                sighist.SetLineWidth(3)
            for shist in sighists:
                for j in range(1, shist.GetNbinsX() + 1):
                    entry = shist.GetBinContent(j)
                    if entry < axish[0].GetMinimum():
                        shist.SetBinContent(j, axish[0].GetMinimum() * 1.00001)

                shist_stack = shist.Clone()
                shist_stack.SetLineColor(ROOT.kBlack)
                shist_stack.SetLineWidth(1)
                #shist_stack.SetFillStyle(1)
                shist_stack.SetFillColor(ROOT.kRed)
                #stack.Add(shist_stack) # uncomment to add to the stack
        #        shist.Draw("histsame][") # removing vertical lines at the borders of the pad; possible with the trick above
        stack.Draw("histsame")
        shist.Draw("histsame ][")
        bkghist.Draw("e2same")
        blind_datagraph_extra = blind_datagraph.Clone()
        blind_datagraph_extra.Draw("P Z 0 same")
        blind_datagraph.SetMarkerSize(0.)
        blind_datagraph.Draw("P Z 0 same")

        azimov_datagraph_extra = azimov_datagraph.Clone()
        azimov_datagraph_extra.Draw("P Z 0 same")
        azimov_datagraph.SetMarkerSize(0.)
        azimov_datagraph.Draw("P Z 0 same")

        axish[i].Draw("axissame")

    pads[0].cd()
    pads[0].SetTicks(1)
    pads[1].SetTicks(1)
    #Setup legend
    if not is2D:
        legend = plot.PositionedLegend(0.42, 0.33, 3, 0.02, 0.02)
        #def PositionedLegend(width, height, pos, offset, horizontaloffset=None):
        legend.SetTextSize(0.028)
    else:
        legend = PositionedLegendUnrolled(0.13, 0.5, 7, 0.02)
        legend.SetTextSize(0.035)
    legend.SetTextFont(42)
    legend.SetFillStyle(0)

    legend.AddEntry(total_datahist, "Observed", "PEl")
    #Drawn on legend in reverse order looks better
    bkg_histos.reverse()

    background_schemes[channel].reverse()
    leg_hists = [None] * len(bkg_histos)
    for legi, hists in enumerate(bkg_histos):
        legend.AddEntry(hists, background_schemes[channel][legi]['leg_text'],
                        "f")
    #legend.AddEntry(bkghist,"Background uncertainty","f")
    bkghist.SetLineWidth(0)
    legend.AddEntry(bkghist, "Bkg. unc.", "f")
    if is2D:
        if not mode == 'prefit':
            if not args.no_signal:
                legend.AddEntry(sighist,
                                "gg#phi @ 5.8 pb (m_{#phi}= 100 GeV)" % vars(),
                                "l")
        else:
            if not args.no_signal:
                legend.AddEntry(sighist,
                                "gg#phi @ 5.8 pb (m_{#phi}= 100 GeV)" % vars(),
                                "l")

    else:
        #if not args.no_signal: legend.AddEntry(shist_stack,"gg#phi(100 GeV) @ 5.8 pb"%vars(),"f") # uncomment if showing in the stack
        if not args.no_signal:
            legend.AddEntry(sighist,
                            "gg#phi @ 5.8 pb (m_{#phi}= 100 GeV)" % vars(),
                            "l")
    legend.Draw("same")

    latex2 = ROOT.TLatex()
    latex2.SetNDC()
    latex2.SetTextAngle(0)
    latex2.SetTextColor(ROOT.kBlack)
    latex2.SetTextFont(42)
    if not is2D:
        #latex2.SetTextSize(0.032)
        #latex2.DrawLatex(0.21,0.89,"{}, {}".format(bin_label.split(',')[0], channel_label))
        #latex3 = ROOT.TLatex()
        #latex3.SetNDC()
        #latex3.SetTextSize(0.032)
        #latex3.SetTextAngle(0)
        #latex3.SetTextColor(ROOT.kBlack)
        #latex3.SetTextFont(42)
        #if len(bin_label.split(','))>1: latex3.DrawLatex(0.21,0.84,"{}".format(bin_label.split(',')[1]))
        textsize = 0.033  #0.027
        begin_left = None
        ypos = 0.960 if "_{" in bin_label else 0.955
        latex2 = ROOT.TLatex()
        latex2.SetNDC()
        latex2.SetTextAngle(0)
        latex2.SetTextColor(ROOT.kBlack)
        latex2.SetTextSize(textsize)
        if begin_left == None:
            #begin_left = 0.145
            begin_left = 0.180
        latex2.SetTextFont(42)
        latex2.DrawLatex(begin_left, 0.960, channel_label + ', ' + bin_label)
    else:
        latex2.SetTextAlign(23)
        latex2.SetTextSize(0.05)
        latex2.DrawLatex(0.46, 0.955, "{}, {}".format(bin_label,
                                                      channel_label))

    if args.bOnly:
        #pads[0].cd()
        latex2.DrawLatex(0.54, 0.55, "Bkg. only fit")

    #CMS and lumi labels
    plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]),
                     extra_pad if extra_pad > 0 else 0.3)
    extra = cms_label
    #extra='Preliminary'
    if not is2D:
        #DrawCMSLogo(pads[0], 'CMS', extra, 0, 0.07, -0.0, 2.0, '', 0.85, relExtraDX=0.05)
        cms_scale = 1.0
        DrawCMSLogo(pads[0], 'CMS', extra, 11, 0.045, 0.05, 1.0, '', cms_scale)

        plot.DrawTitle(pads[0], lumi, 3, textSize=0.6)
    else:
        DrawCMSLogo(pads[0],
                    'CMS',
                    extra,
                    0,
                    0.07,
                    -0.0,
                    2.0,
                    '',
                    0.6,
                    relExtraDX=0.005)
        DrawTitleUnrolled(pads[0], lumi, 3, scale=0.6)

    #Add ratio plot if required
    axish[1].GetYaxis().SetTitle("Obs./Exp.")
    if args.ratio:
        ratio_bkghist = plot.MakeRatioHist(bkghist, bkghist, True, False)
        sbhist.SetLineColor(ROOT.kRed)
        sbhist_alt.SetLineColor(ROOT.kBlue)
        sbhist.SetLineWidth(2)
        sbhist_alt.SetLineWidth(2)
        if not is2D:
            sbhist.SetLineWidth(3)
            sbhist_alt.SetLineWidth(3)

        bkghist_errors = bkghist.Clone()
        #for i in range(1,bkghist_errors.GetNbinsX()+1): bkghist_errors.SetBinContent(i,bkghist.GetBinError(i))
        for i in range(1, bkghist_errors.GetNbinsX() + 1):
            bkghist_errors.SetBinContent(i, 1.)
        ratio_sighist = plot.MakeRatioHist(sbhist, bkghist, True, False)
        ratio_datahist_ = plot.MakeRatioHist(blind_datahist, bkghist, True,
                                             False)
        azimov_ratio_datahist_ = plot.MakeRatioHist(azimov_datahist, bkghist,
                                                    True, False)

        ratio_datahist = ROOT.TGraphAsymmErrors(ratio_datahist_)
        azimov_ratio_datahist = ROOT.TGraphAsymmErrors(azimov_ratio_datahist_)

        pads[1].cd()
        #pads[1].SetGrid(0,1)
        axish[1].Draw("axis")
        axish[1].SetMinimum(float(args.ratio_range.split(',')[0]))
        axish[1].SetMaximum(float(args.ratio_range.split(',')[1]))
        ratio_bkghist.SetMarkerSize(0)

        ratio_bkghist.Draw("e2same")
        ratio_datahist.Draw("P Z 0 same")
        ratio_sighist.Draw('histsame')

        if args.f_bOnly:
            bonly_histo_file = ROOT.TFile(args.f_bOnly)
            bonlyhist = getHistogram(bonly_histo_file,
                                     'TotalBkg',
                                     file_dir,
                                     mode,
                                     logx=log_x)[0]
            bonlyhist.Scale(1, "width")
            bonlyhist.SetLineColor(ROOT.kBlue)
            bonlyhist.SetLineWidth(2)
            bonlyhist.SetLineStyle(2)
            ratio_bonlyhist = plot.MakeRatioHist(bonlyhist, bkghist, True,
                                                 False)
            ratio_bonlyhist.Draw("histsame")
            pads[0].cd()
            legend.AddEntry(bonlyhist, 'Bkg. only fit', 'l')
            legend.Draw()
            #bonlyhist.Draw('histsame')
            bonlyhist.SetMarkerSize(0)
            bonlyhist.Draw('lsame')
            stack.Draw("histsame")
            shist.Draw("histsame ][")
            bkghist.Draw("e2same")
            blind_datagraph.SetMarkerSize(1)
            blind_datagraph.Draw("P Z 0 same")
            pads[1].cd()

        if args.manual_blind: azimov_ratio_datahist.Draw("P Z 0 same")
        pads[1].RedrawAxis("G")
        if is2D:
            rlegend = ROOT.TLegend(0.85, 0.27, 0.98, 0.16, '', 'NBNDC')
            rlegend.SetTextFont(42)
            rlegend.SetTextSize(0.035)
            rlegend.SetFillStyle(0)
            rlegend.AddEntry(ratio_datahist, "Obs./Exp.", "PE")
            rlegend.AddEntry("", " ", "")
            #rlegend.AddEntry(ratio_sighist,"(Sig.+Bkg.)/Bkg.","L")
        #rlegend.Draw("same")
        # Draw extra axis for explanation (use "N" for no optimisation)
        if is2D:
            extra_axis = ROOT.TGaxis(0, -0.03, 30., -0.03, 0., 300., 403, "NS")
            extra_axis.SetLabelSize(0.03)
            extra_axis.SetLabelFont(42)
            extra_axis.SetMaxDigits(3)
            extra_axis.SetTitle("m_{#tau#tau} (GeV)")
            extra_axis.SetTitleFont(42)
            extra_axis.SetTitleSize(0.035)
            extra_axis.SetTitleOffset(1.1)
            extra_axis.SetTickSize(0.08)
            extra_axis.Draw()

    pads[0].cd()
    pads[0].GetFrame().Draw()
    pads[0].RedrawAxis()

    ## Add lines after every Nxbins
    #line = ROOT.TLine()
    #line.SetLineWidth(2)
    #line.SetLineStyle(3)
    #line.SetLineColor(1)
    #x = bkghist.GetNbinsX()/Nxbins
    #x_min=bkghist.GetXaxis().GetBinLowEdge(1)
    #x_max=bkghist.GetXaxis().GetBinLowEdge(bkghist.GetNbinsX()+1)
    #x_range=x_max-x_min

    ## for now we have to hard code x=4 otherwise we have issues when the auto rebinning has been used
    #x=4
    #if is2D:
    #    for l in range(1,x):
    #        pads[0].cd()
    #        ymax = axish[0].GetMaximum()
    #        ymin = axish[0].GetMinimum()
    #        line.DrawLine(l*x_range/x,ymin,l*x_range/x,ymax)
    #        if args.ratio:
    #            pads[1].cd()
    #            ymax = axish[1].GetMaximum()
    #            ymin = axish[1].GetMinimum()
    #            line.DrawLine(l*x_range/x,ymin,l*x_range/x,ymax)

    ## Add bin labels between lines
    pads[0].cd()
    latex_bin = ROOT.TLatex()
    latex_bin.SetNDC()
    latex_bin.SetTextAngle(0)
    latex_bin.SetTextColor(ROOT.kBlack)
    latex_bin.SetTextFont(42)
    latex_bin.SetTextSize(0.035)
    if len(y_bin_labels) > 6 or ('_2_' in file_dir and len(y_bin_labels) > 5):
        latex_bin.SetTextSize(0.027)

    for i in range(0, len(y_bin_labels)):
        if i < len(y_bin_labels) - 1:
            y_bin_label = "{} #leq {} < {} {}".format(y_bin_labels[i],
                                                      y_bin_var,
                                                      y_bin_labels[i + 1],
                                                      "GeV")
            l = ROOT.gPad.GetLeftMargin()
            r = ROOT.gPad.GetRightMargin()
            #xshift = ((1-r-l)/(axish[0].GetNbinsX()/Nxbins))*i + l
            # have to hard code 4 here other wise we have problems when the autorebinning has been used
            xshift = ((1 - r - l) / (4)) * i + l
            latex_bin.DrawLatex(xshift + 0.02, 0.82, y_bin_label)
        else:
            #xshift = ((1-r-l)/(axish[0].GetNbinsX()/Nxbins))*i + l
            # have to hard code 4 here other wise we have problems when the autorebinning has been used
            xshift = ((1 - r - l) / (4)) * i + l
            y_bin_label = "{} > {} {}".format(y_bin_var, y_bin_labels[i],
                                              "GeV")
            latex_bin.DrawLatex(xshift + 0.02, 0.82, y_bin_label)

    #Save as png and pdf with some semi sensible filename
    shape_file_name = shape_file_name.replace(".root", "_%(mode)s" % vars())
    shape_file_name = shape_file_name.replace("_shapes", "")
    outname += shape_file_name + "_" + file_dir.strip("htt").strip("_")
    if (log_x):
        outname += "_logx"
    c2.SaveAs("plots/%(outname)s.pdf" % vars())

    del c2
    histo_file.Close()
Exemplo n.º 10
0
                              ROOT.RooFit.LineStyle(ROOT.kDashed),
                              ROOT.RooFit.LineColor(ROOT.kBlue),
                              ROOT.RooFit.Name("BkgPass"))
    '''
    pads[0].cd()
    xframe.Draw()

    axis = plot.GetAxisHist(pads[0])
    #plot.Set(axis.GetXaxis().SetTitle('m_{tag-probe} (GeV)'))
    if args.particle == 'e':
        plot.Set(axis.GetXaxis().SetTitle('p_{t}(e) (GeV)'))
    else:
        plot.Set(axis.GetXaxis().SetTitle('p_{t}(#mu) (GeV)'))
    plot.Set(axis.GetYaxis().SetTitle('Events / %g GeV' % width))
    #plot.DrawTitle(pads[0], 'Pass Region', 1)
    plot.DrawTitle(pads[0], args.title, 1)

    latex.SetTextSize(0.035)
    #latex.DrawLatex(0.5, 0.89, args.title)
    #latex.DrawLatex(0.5, 0.84, 'p_{T}: [%g, %g] GeV #eta: [%g, %g]' % (b[2], b[3], b[4], b[5]))
    font = latex.GetTextFont()
    latex.DrawLatex(0.2, 0.9, 'pass region')
    latex.SetTextFont(42)
    #latex.DrawLatex(0.63, 0.75, '#chi^{2} = %.2f' % (xframe.chiSquare("AllPass", "DataPass", nparams)))
    latex.DrawLatex(
        0.63, 0.7, '#varepsilon = %.4f #pm %.4f' %
        (wsp.var('efficiency').getVal(), wsp.var('efficiency').getError()))
    ROOT.gStyle.SetLegendBorderSize(1)
    legend1 = ROOT.TLegend(0.6, 0.8, 0.925, 0.939)
    legend1.AddEntry(xframe.findObject("DataPass"), "data", "ep")
    #legend1.AddEntry(xframe.findObject("AllPass"), "Z #rightarrow #mu#mu + BG", "l")
Exemplo n.º 11
0
exppt.SetFillStyle(0)
exppt.SetLineWidth(0)
exppt.SetTextFont(42)
exppt.SetTextColor(args.exp_color)
exppt.SetTextSize(0.07)
exppt.Draw()

plot.DrawCMSLogo(pads[0],
                 args.logo,
                 args.logo_sub,
                 11,
                 0.045,
                 0.035,
                 1.2,
                 cmsTextSize=1.)
plot.DrawTitle(pads[0], "137 fb^{-1} (13 TeV)", 3)

legend = ROOT.TLegend(0.15, 0.62, 0.45, 0.76, '', 'NBNDC')
legend.SetFillStyle(0)

legend.AddEntry(obs_scan['func'], args.obs_label, 'L')
legend.AddEntry(exp_scan['func'], args.exp_label, 'L')
legend.Draw()

save_graph = obs_scan['graph'].Clone()
save_graph.GetXaxis().SetTitle(
    '%s = %.3f %+.3f/%+.3f' % (fixed_name, val_nom[0], val_nom[2], val_nom[1]))
exp_graph = exp_scan['graph'].Clone()
exp_graph.GetXaxis().SetTitle(
    '%s = %.3f %+.3f/%+.3f' %
    (fixed_name, exp_val_nom[0], exp_val_nom[2], exp_val_nom[1]))
Exemplo n.º 12
0
def MakePlot(name, outdir, hists, cfg, layouts):
    copyhists = {}
    for hname, h in hists.iteritems():
        if len(cfg['rebinvar']):
            copyhists[hname] = VariableRebin(h, cfg['rebinvar'])
        else:
            copyhists[hname] = h.Clone()
        if cfg['divwidth']:
            copyhists[hname].Scale(1., 'width')

    hists = copyhists

    # Canvas and pads
    canv = ROOT.TCanvas(name, name)
    if cfg['ratio'] or cfg['fraction']:
        pads = plot.TwoPadSplit(0.27, 0.01, 0.01)
    else:
        pads = plot.OnePad()

    # Get the data and create axis hist
    h_data = hists[cfg['data_name']]
    # h_data = Getter(file, '%s/data_obs' % target, True)
    if isinstance(h_data, ROOT.TH2):
        print 'TH2: aborting!'
        return

    h_axes = [h_data.Clone() for x in pads]
    for h in h_axes:
        if len(cfg['x_range']):
            h.GetXaxis().SetRangeUser(*cfg['x_range'])
        h.Reset()

    build_h_tot = True
    h_tot = None
    if 'TotalProcs' in hists:
        h_tot = hists['TotalProcs']
        build_h_tot = False

    x_title = cfg['x_title'][0]
    units = cfg['x_title'][1]

    if x_title == '' and h_data.GetXaxis().GetTitle() != '':
        x_title = h_data.GetXaxis().GetTitle()

    if ':' in x_title:
        units = x_title.split(':')[1]
        x_title = x_title.split(':')[0]

    if cfg['logy']:
        pads[0].SetLogy()
        h_axes[0].SetMinimum(0.001)

    if cfg['ratio'] or cfg['fraction']:
        plot.StandardAxes(h_axes[1].GetXaxis(), h_axes[0].GetYaxis(), x_title,
                          units)
    else:
        plot.StandardAxes(h_axes[0].GetXaxis(), h_axes[0].GetYaxis(), x_title,
                          units)
    h_axes[0].Draw()

    # A dict to keep track of the hists
    h_store = {}

    layout = layouts[cfg['layout']]

    stack = ROOT.THStack()
    legend = ROOT.TLegend(*(cfg['legend_pos'] + ['', 'NBNDC']))

    for info in layout:
        hist = hists[info['entries'][0]]
        col = info['color']
        if isinstance(col, list):
            col = ROOT.TColor.GetColor(*col)
        plot.Set(hist, FillColor=col, Title=info['legend'])
        if len(info['entries']) > 1:
            for other in info['entries'][1:]:
                hist.Add(hists[other])
        h_store[info['name']] = hist
        if build_h_tot:
            if h_tot is None:
                h_tot = hist.Clone()
            else:
                h_tot.Add(hist)
        stack.Add(hist)

    h_tot.SetFillColor(plot.CreateTransparentColor(12, 0.3))
    h_tot.SetMarkerSize(0)

    legend.AddEntry(h_data, 'Observed', 'PL')
    for ele in reversed(layout):
        legend.AddEntry(h_store[ele['name']], '', 'F')
    bkg_uncert_label = 'Stat. Uncertainty'
    if not build_h_tot:
        bkg_uncert_label = 'Uncertainty'
    legend.AddEntry(h_tot, bkg_uncert_label, 'F')

    stack.Draw('HISTSAME')
    h_tot.Draw("E2SAME")
    if not cfg['hide_data']:
        h_data.Draw('E0SAME')

    plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.35)
    legend.Draw()
    if cfg['legend_padding'] > 0.:
        print h_axes[0].GetMinimum(), h_axes[0].GetMaximum()
        if not h_axes[0].GetMaximum() == 0.:
            plot.FixBoxPadding(pads[0], legend, cfg['legend_padding'])

    # Do the ratio plot
    if cfg['ratio'] or cfg['fraction']:
        pads[1].cd()
        pads[1].SetGrid(0, 1)
        h_axes[1].Draw()

        if cfg['ratio']:
            r_data = plot.MakeRatioHist(h_data, h_tot, True, False)
            r_tot = plot.MakeRatioHist(h_tot, h_tot, True, False)
            r_tot.Draw('E2SAME')
            if not cfg['hide_data']:
                r_data.Draw('SAME')

            plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]),
                                         plot.GetAxisHist(pads[1]), 'Obs/Exp',
                                         True, 0.61, 1.69)
        if cfg['fraction']:
            r_frac = plot.MakeRatioHist(h_tot, h_data, True, True)
            r_frac.Draw('SAME')
            plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]),
                                         plot.GetAxisHist(pads[1]), 'Exp/Obs',
                                         True, 0.0, 0.5)

    # Go back and tidy up the axes and frame
    pads[0].cd()
    pads[0].GetFrame().Draw()
    pads[0].RedrawAxis()

    # CMS logo
    plot.DrawCMSLogo(pads[0], cfg['main_logo'], cfg['sub_logo'], 11, 0.045,
                     0.05, 1.0, '', 1.0)
    plot.DrawTitle(pads[0], cfg['top_title_left'], 1)
    if cfg['auto_top_title_right']:
        title_right = h_data.GetTitle()
        if title_right.startswith('lumi:'):
            plot.DrawTitle(pads[0], title_right.replace('lumi:', ''), 3)
    else:
        plot.DrawTitle(pads[0], cfg['top_title_right'], 3)

    latex = ROOT.TLatex()
    plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03)
    latex.DrawLatex(0.20, 0.75, args.title)
    # plot.DrawTitle(pads[0], args.title, 1)

    # ... and we're done
    canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.png')
    canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.pdf')
Exemplo n.º 13
0
        legend.AddEntry(QCD, "QCD", "f")
        legend.AddEntry(VBF, "SM H#rightarrow#tau#tau, m_{H}=125 GeV", "f")
        legend.AddEntry(Data, "Observed", "ep")
        legend.AddEntry(TotProc, "Exp. Uncertainty", "f")
        legend.Draw("same")
        latex = ROOT.TLatex()
        latex.SetNDC()
        latex.SetTextAngle(0)
        latex.SetTextColor(ROOT.kBlack)
        latex.SetTextSize(0.026)

        #CMS and lumi labels
        plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.15)
        plot.DrawCMSLogo(pads[0], 'CMS', 'Preliminary', 11, 0.045, 0.05, 1.0,
                         '', 1.0)
        plot.DrawTitle(pads[0], "2.3 fb^{-1} (13 TeV)", 3)

        #add ratio plot
        DataForRatio = Data.Clone()
        DataForRatio.Divide(TotProc)
        ErrForRatio = TotProc.Clone()
        ErrForRatio.Divide(TotProc)
        #DataForRatio.SetFillColor(plot.CreateTransparentColor(12,1))
        DataForRatio.SetFillColor(ROOT.EColor.kBlack)
        pads[1].cd()
        pads[1].SetGrid(1, 1)
        axish[1].Draw("axis")
        axish[1].SetMinimum(0.5)
        axish[1].SetMaximum(1.5)
        DataForRatio.SetMarkerSize(1.2)
        DataForRatio.SetMarkerStyle(20)
Exemplo n.º 14
0
h_dat_r.Draw('esamex0')

pads[0].cd()


axes[0].SetMaximum(8E6)
# plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.3)

legend = plot.PositionedLegend(0.30, 0.20, 3, 0.03)
legend.AddEntry(h_dat, "Observed", "pe")
legend.AddEntry(h_bkg, "Background", "f")
legend.AddEntry(h_err, "Uncertainty", "f")
legend.AddEntry(h_sig, "t#bar{t}H (#mu=1.26)", "f")
legend.AddEntry(h_sig_mu1, "t#bar{t}H (#mu=1.00)", "f")
# // legend->AddEntry(&sb_err, "Bkg. Uncertainty", "f");
legend.Draw()

for pad in pads:
    pad.cd()
    plot.FixOverlay()


# plot.DrawCMSLogo(pads[0], 'CMS', 'Preliminary', 0, 0.12, 0.035, 1.2)
plot.DrawCMSLogo(pads[0], 'CMS', 'Supplementary', 11, 0.045, 0.035, 1.2, '', 0.9)
plot.DrawTitle(pads[0], '5.1 fb^{-1} (7 TeV) + 19.7 fb^{-1} (8 TeV) + 35.9 fb^{-1} (13 TeV)' , 3)


canv.Print('.pdf')
canv.Print('.png')
# canv.Print('.C')
Exemplo n.º 15
0
# axis[0].GetXaxis().SetTitle(args.x_title)
# axis[0].GetXaxis().SetLabelOffset(axis[0].GetXaxis().GetLabelOffset()*2)

pads[0].RedrawAxis()
pads[0].RedrawAxis('g')
pads[0].GetFrame().Draw()

line = ROOT.TLine()
line.SetLineColor(ROOT.kBlue)
line.SetLineWidth(2)
plot.DrawHorizontalLine(pads[0], line, 1)

# info = ROOT.TPaveText(0.47, 0.75, 0.70, 0.91, 'NDCNB')
# info.SetTextFont(42)
# info.SetTextAlign(12)
# info.AddText('#bf{ttH combination}')
# info.AddText('HIG-15-005 H#rightarrow#gamma#gamma')
# info.AddText('HIG-15-008 H#rightarrowleptons')
# info.AddText('HIG-16-004 H#rightarrowbb')
# info.Draw()

# box = ROOT.TPave(pads[0].GetLeftMargin(), 0.81, 1-pads[0].GetRightMargin(), 1-pads[0].GetTopMargin(), 1, 'NDC')
# box.Draw()

plot.DrawCMSLogo(pads[0], 'CMS', 'Preliminary', 11, 0.045, 0.035, 1.2, '', 1.1)
plot.DrawTitle(pads[0], '2.3-2.7 fb^{-1} (13 TeV)', 3)
plot.DrawTitle(pads[0], 'm_{H} = 125 GeV', 1)

canv.Print('.pdf')
canv.Print('.png')
Exemplo n.º 16
0
hist.GetXaxis().SetTitle(x_title)
hist.GetYaxis().SetTitle(y_title)
hist.GetZaxis().SetTitle(z_title)
hist.GetXaxis().SetLabelFont(42)
hist.GetYaxis().SetLabelFont(42)
hist.GetXaxis().SetTickLength(0)
hist.GetYaxis().SetTickLength(0)
hist.GetXaxis().SetLabelSize(args.label_size)
hist.GetYaxis().SetLabelSize(args.label_size)
hist.GetZaxis().SetLabelSize(0.045)
# hist.GetZaxis().SetTitle('#rho')
hist.SetContour(255)

canv = ROOT.TCanvas(args.output, args.output)
pads = plot.OnePad()

ROOT.gStyle.SetTextFont(42)
hist.SetMarkerSize(args.marker_size)
hist.Draw(args.draw_opt)

plot.FixOverlay()

plot.DrawCMSLogo(pads[0], 'CMS', args.subline, 0, 0.17, 0.035, 1.2)

if args.label is not None:
    plot.DrawTitle(pads[0], args.label, 3)

canv.Print('.pdf')
canv.Print('.png')
Exemplo n.º 17
0
    graph_list[i].SetMarkerStyle(20)
    graph_list[i].SetMarkerColor(colourlist[i])
    graph_list[i].SetLineStyle(2)
    graph_list[i].Draw("PL")

pads[0].cd()
h_top = axis.Clone()
#necessary in case chosen range surrounds 0 which will cause axis to contain a horizontal line at 0
h_top.GetYaxis().SetRangeUser(0.001, 100)
plot.Set(h_top.GetXaxis(), LabelSize=0, TitleSize=0, TickLength=0)
plot.Set(h_top.GetYaxis(), LabelSize=0, TitleSize=0, TickLength=0)
h_top.Draw()

legend = plot.PositionedLegend(0.4, 0.11, 3, 0.015)
plot.Set(legend, NColumns=1, Header='')
for i in range(len(files)):
    legend.AddEntry(graph_list[i], labels[i], "PL")

legend.Draw()

#plot.DrawCMSLogo(pads[0], 'CMS', args.cms_sub, 11, 0.045, 0.15, 1.0, '', 1.0)
plot.DrawTitle(pads[0], '%s' % args.title, 3)
plot.FixOverlay()

pads[1].cd()
pads[1].GetFrame().Draw()
pads[1].RedrawAxis()

c1.SaveAs("%s.pdf" % outname)
c1.SaveAs("%s.png" % outname)
Exemplo n.º 18
0
        line[i].SetLineColor(13)
        line[i].Draw()

        latex.append(ROOT.TLatex())
        #latex[i].SetNDC()
        latex[i].SetTextAngle(0)
        latex[i].SetTextAlign(12)
        latex[i].SetTextSize(0.04)
        latex[i].SetTextColor(13)
        t = c.GetTopMargin()
        b = c.GetBottomMargin()
        r = c.GetRightMargin()
        #latex[i].DrawLatex(1.01-r,-b+((1-math.log(y[i])/math.log(0.001)*(1-t-b))),str(i+1) + "#sigma")
        latex[i].DrawLatex(3800., y[i], str(i + 1) + "#sigma")

    plot.DrawTitle(c, '138 fb^{-1} (13 TeV)', 3)
    plot.DrawCMSLogo(c, 'CMS', 'Supplementary', 0, 0.15, 0, 0, '', 0.9)
    #plot.DrawCMSLogo(c, 'CMS', 'Preliminary', 0, 0.15, 0, 0, '', 0.9)

    line2 = ROOT.TLine(225., limit_dict["lowmass"]["p_value"].GetMinimum(),
                       225, 1.)
    line2.Draw()
    latex2 = ROOT.TLatex()
    latex2.SetNDC()
    latex2.SetTextAngle(0)
    latex2.SetTextAlign(12)
    latex2.SetTextFont(42)
    latex2.SetTextSize(0.04)
    latex2.DrawLatex(0.19, 0.91, 'Low-mass')
    latex2.DrawLatex(0.45, 0.91, 'High-mass')
Exemplo n.º 19
0
        boxes.append(
            bad_trigger.DrawBox(float(i),
                                plot.GetAxisHist(pads[2]).GetMinimum(),
                                float(i + 1),
                                plot.GetAxisHist(pads[2]).GetMaximum()))
    elif not prescale_l1_ok[str(run)]:
        boxes.append(
            some_presc_l1.DrawBox(float(i),
                                  plot.GetAxisHist(pads[2]).GetMinimum(),
                                  float(i + 1),
                                  plot.GetAxisHist(pads[2]).GetMaximum()))

tot_lumi = sum(lumi_dict.values()) / 1000.  # fb-1 for now

right_label = '%.1f fb^{-1} (13 TeV)' % tot_lumi
if args.min_lumi > 0.:
    right_label += ', runs with L > %g pb^{-1}' % args.min_lumi

if args.yields is not None:
    plot.DrawTitle(pads[0], yields[-1], 1)
plot.DrawTitle(pads[0], right_label, 3)

legend = ROOT.TLegend(0.1, 0.01, 0.7, 0.07, '', 'NBNDC')
legend.AddEntry(bad_trigger, 'Prescaled in run', 'F')
legend.AddEntry(some_presc_l1, 'Partial L1 prescale', 'F')
legend.SetNColumns(2)
legend.Draw()

canv.Print('.png')
canv.Print('.pdf')
Exemplo n.º 20
0
    legend.AddEntry(hists, background_schemes[channel][legi]['leg_text'], "f")
legend.AddEntry(bkghist, "Background uncertainty", "f")
legend.AddEntry(blind_datahist, "Observation", "P")
legend.Draw("same")
latex = ROOT.TLatex()
latex.SetNDC()
latex.SetTextAngle(0)
latex.SetTextColor(ROOT.kBlack)
latex.SetTextSize(0.026)
#latex.DrawLatex(0.61,0.53,"m_{h}^{mod+}, m_{A}=%(mA)s GeV, tan#beta=%(tb)s"%vars())

#CMS and lumi labels
plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]),
                 extra_pad if extra_pad > 0 else 0.15)
plot.DrawCMSLogo(pads[0], 'CMS', 'Preliminary', 11, 0.045, 0.05, 1.0, '', 1.0)
plot.DrawTitle(pads[0], "35.9 fb^{-1} (13 TeV)", 3)

#Add ratio plot if required
if args.ratio:
    ratio_bkghist = bkghist.Clone()
    ratio_bkghist.Divide(bkghist)
    blind_datahist.Divide(bkghist)
    pads[1].cd()
    pads[1].SetGrid(0, 1)
    axish[1].Draw("axis")
    axish[1].SetMinimum(0.7)
    axish[1].SetMaximum(1.3)
    ratio_bkghist.SetMarkerSize(0)
    ratio_bkghist.Draw("e2same")
    blind_datahist.DrawCopy("psame")
Exemplo n.º 21
0
for i in xrange(1, hist.GetYaxis().GetNbins() + 1):
    new_name = hist.GetYaxis().GetBinLabel(i)
    if new_name in name_translate:
        new_name = name_translate[new_name]
        new_name = ColorLabels(new_name)
    hist.GetYaxis().SetBinLabel(i, new_name)

hist.GetXaxis().LabelsOption('h')
hist.GetXaxis().SetLabelFont(62)
hist.GetYaxis().SetLabelFont(62)
hist.GetXaxis().SetLabelSize(0.04)
hist.GetYaxis().SetLabelSize(0.041)
if not args.cov:
    hist.SetMinimum(-1)
    hist.SetMaximum(+1)
hist.SetContour(255)

canv = ROOT.TCanvas(args.output, args.output)
pads = plot.OnePad()

hist.Draw('COLZTEXT')

plot.DrawCMSLogo(pads[0], '#it{ATLAS}#bf{ and }CMS', 'LHC Run 1 Internal', 0,
                 0.38, 0.035, 1.2)
if args.label is not None: plot.DrawTitle(pads[0], args.label, 3)

canv.Print('.pdf')
canv.Print('.png')
# canv.Print('.C')
Exemplo n.º 22
0
    legend.SetNColumns(3)
    legend.AddEntry(g_pulls, 'Pull', 'LP')
    legend.AddEntry(g_impacts_hi, '+1#sigma Impact', 'F')
    legend.AddEntry(g_impacts_lo, '-1#sigma Impact', 'F')
    legend.Draw()

    if args.color_groups is not None:
        legend2 = ROOT.TLegend(0.01, 0.94, 0.30, 0.99, '', 'NBNDC')
        legend2.SetNColumns(2)
        for name, h in color_group_hists.iteritems():
            legend2.AddEntry(h, Translate(name, translate), 'F')
        legend2.Draw()
    elif len(seen_types) > 1:
        legend2 = ROOT.TLegend(0.01, 0.94, 0.30, 0.99, '', 'NBNDC')
        legend2.SetNColumns(2)
        for name, h in color_hists.iteritems():
            if name == 'Unrecognised': continue
            legend2.AddEntry(h, name, 'F')
        legend2.Draw()

    plot.DrawCMSLogo(pads[0], 'CMS', args.cms_label, 0, 0.25, 0.00, 0.00)
    plot.DrawTitle(pads[1], '#hat{%s} = %.3g #pm %.3g%s' % (
        Translate(POIs[0], translate), POI_fit[1], (POI_fit[2] - POI_fit[0]) / 2.,
        '' if args.units is None else ' '+args.units), 3)
    extra = ''
    if page == 0:
        extra = '('
    if page == n - 1:
        extra = ')'
    canv.Print('.pdf%s' % extra)
Exemplo n.º 23
0
             wsp.var("m_ll").getMin()) / splitData.At(1).numEntries()
    splitData.At(1).plotOn(xframe)
    wsp.pdf("passing").plotOn(xframe,
                              ROOT.RooFit.Slice(wsp.cat('cat'), "pass"),
                              ROOT.RooFit.LineColor(ROOT.kBlue))
    wsp.pdf("passing").plotOn(xframe,
                              ROOT.RooFit.Slice(wsp.cat('cat'), "pass"),
                              ROOT.RooFit.Components('backgroundPass'),
                              ROOT.RooFit.LineStyle(ROOT.kDashed),
                              ROOT.RooFit.LineColor(ROOT.kBlue))
    pads[0].cd()
    xframe.Draw()
    axis = plot.GetAxisHist(pads[0])
    plot.Set(axis.GetXaxis().SetTitle('m_{tag-probe} (GeV)'))
    plot.Set(axis.GetYaxis().SetTitle('Events / %g GeV' % width))
    plot.DrawTitle(pads[0], 'Pass Region', 1)
    latex.SetTextSize(0.03)
    latex.DrawLatex(0.5, 0.89, args.title)
    latex.DrawLatex(
        0.5, 0.84,
        'p_{T}: [%g, %g] GeV #eta: [%g, %g]' % (b[2], b[3], b[4], b[5]))
    latex.SetTextFont(42)
    latex.DrawLatex(
        0.5, 0.79, '#varepsilon = %.4f #pm %.4f' %
        (wsp.var('efficiency').getVal(), wsp.var('efficiency').getError()))

    xframe2 = wsp.var("m_ll").frame(ROOT.RooFit.Title("Failing"))
    splitData.At(0).plotOn(xframe2)
    wsp.pdf("failing").plotOn(xframe2,
                              ROOT.RooFit.Slice(wsp.cat('cat'), "fail"),
                              ROOT.RooFit.LineColor(ROOT.kRed))
Exemplo n.º 24
0
    legend.AddEntry(g_impacts_lo, '-1#sigma Impact', 'F')
    legend.Draw()

    leg_width = pads[0].GetLeftMargin() - 0.01
    if args.color_groups is not None:
        legend2 = ROOT.TLegend(0.01, 0.94, leg_width, 0.99, '', 'NBNDC')
        legend2.SetNColumns(2)
        for name, h in color_group_hists.iteritems():
            legend2.AddEntry(h, Translate(name, translate), 'F')
        legend2.Draw()
    elif len(seen_types) > 1:
        legend2 = ROOT.TLegend(0.01, 0.94, leg_width, 0.99, '', 'NBNDC')
        legend2.SetNColumns(2)
        for name, h in color_hists.iteritems():
            if name == 'Unrecognised': continue
            legend2.AddEntry(h, name, 'F')
        legend2.Draw()

    plot.DrawCMSLogo(pads[0], 'CMS', args.cms_label, 0, 0.25, 0.00, 0.00)
    s_nom, s_hi, s_lo = GetRounded(POI_fit[1], POI_fit[2] - POI_fit[1], POI_fit[1] - POI_fit[0])
    if not args.blind:
        plot.DrawTitle(pads[1], '#hat{%s} = %s^{#plus%s}_{#minus%s}%s' % (
            Translate(POI, translate), s_nom, s_hi, s_lo,
            '' if args.units is None else ' '+args.units), 3, 0.27)
    extra = ''
    if page == 0:
        extra = '('
    if page == n - 1:
        extra = ')'
    canv.Print('.pdf%s' % extra)
Exemplo n.º 25
0
        POIs = sorted(args.POI_line.split())
    else:
        POIs = args.POI_line.split()
    for i, P in enumerate(POIs):
        if P in name_translate:
            POIs[i] = name_translate[P]
    POI_line = '[' + ', '.join(POIs) + ']'
    if args.legend_pos == 5:
        POI_line = '#scale[0.7]{#splitline{[' + ', '.join(
            POIs[:5]) + ',}{' + ', '.join(POIs[5:]) + ']}}'
    if args.legend_pos == 8:
        POI_line = '#scale[1.0]{#splitline{[' + ', '.join(
            POIs[:5]) + ',}{' + ', '.join(POIs[5:]) + ']}}'

if not args.no_input_label:
    plot.DrawTitle(pads[0], '#bf{Input:} %s' % collab, 3)
# legend_l = 0.70 if len(args) >= 4 else 0.73

latex = ROOT.TLatex()
latex.SetNDC()
latex.SetTextFont(42)
latex.SetTextSize(0.04)

legend_l = 0.73
if len(other_scans) > 0:
    legend_l = legend_l - len(other_scans) * 0.04
    if args.legend_pos == 6:
        legend_l = legend_l - len(other_scans) * 0.015
if args.legend_pos in [1, 6]:
    legend = ROOT.TLegend(0.15, legend_l, 0.45, 0.78, '', 'NBNDC')
elif args.legend_pos == 2:
Exemplo n.º 26
0
        plot.Set(graph_data, LineColor=ROOT.kRed, MarkerColor=ROOT.kRed)
        graph_data.Draw('SAMEP')
        graph_mc.Draw('SAMEP')
        plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.35)

        pads[1].cd()
        pads[1].SetGrid(0, 1)
        axisr.Draw()
        plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]),
                                     plot.GetAxisHist(pads[1]), 'Data/MC',
                                     True, 0.61, 1.39)
        graph_ratio.Draw('SAMEP')
        # CMS logo
        plot.DrawCMSLogo(pads[0], 'CMS', 'Internal', 11, 0.045, 0.05, 1.0, '',
                         1.0)
        plot.DrawTitle(pads[0], '12.9 fb^{-1} (13 TeV)', 3)

        latex = ROOT.TLatex()
        plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03)
        latex.DrawLatex(0.20, 0.75, args.title)
        # graph_data.Print()
        legend = ROOT.TLegend(0.67, 0.78, 0.90, 0.91, '', 'NBNDC')
        legend.AddEntry(graph_data, 'Data', 'PL')
        legend.AddEntry(graph_mc, 'All MC', 'PL')
        legend.Draw()
        canv.Print('.png')
        canv.Print('.pdf')

if doDeltaBeta:
    for var in ['ntiso_t', 'pho_out_t']:
        canvColz = ROOT.TCanvas(output + "_dbeta_%s" % var,
Exemplo n.º 27
0
        if P in name_translate:
            POIs[i] = name_translate[P]
    POI_line = '[' + ', '.join(POIs) + ']'
    if args.legend_pos == 5:
        POI_line = '#scale[0.7]{#splitline{[' + ', '.join(
            POIs[:5]) + ',}{' + ', '.join(POIs[5:]) + ']}}'
    if args.legend_pos == 8:
        POI_line = '#scale[1.0]{#splitline{[' + ', '.join(
            POIs[:5]) + ',}{' + ', '.join(POIs[5:]) + ']}}'

# if not args.no_input_label:
# plot.DrawTitle(pads[0], '#bf{Input:} %s' % collab, 3)
# legend_l = 0.70 if len(args) >= 4 else 0.73

plot.DrawTitle(
    pads[0], '#lower[-0.1]{PbPb (391 {#mu}b^{-1}, #sqrt{s_{NN}} = 5.02 TeV)}',
    3)

latex = ROOT.TLatex()
latex.SetNDC()
latex.SetTextFont(42)
latex.SetTextSize(0.04)

legend_l = 0.73
if len(other_scans) > 0:
    legend_l = legend_l - len(other_scans) * 0.04
    if args.legend_pos == 6:
        legend_l = legend_l - len(other_scans) * 0.015
if args.legend_pos in [1, 6]:
    legend = ROOT.TLegend(0.15, legend_l, 0.45, 0.78, '', 'NBNDC')
elif args.legend_pos == 2:
Exemplo n.º 28
0
            plot.Set(r_obs_graphs_stat[i],
                     FillColor=17,
                     LineColor=12,
                     LineWidth=1)
            plot.Set(r_obs_graphs_syst[i],
                     FillColor=41,
                     LineColor=28,
                     LineWidth=1)
            # r_obs_graphs_syst[i].Draw('E5SAME')
            # r_obs_graphs_stat[i].Draw('E5SAME')
        r_obs_graphs[i].Draw('SAMEP')
        # r_ref_hists_1D[i].Draw('LSAME')

latex.SetTextSize(0.05)
chg_labels = {'p': '+', 'n': '-', 'x': '#pm'}
# latex.DrawLatexNDC(0.17, 0.17, 'W^{%s}(#rightarrowl^{%s}#nu)#gamma' % (chg_labels[args.charge], chg_labels[args.charge]))

legend.Draw()

pads[0].cd()
# plot.DrawCMSLogo(pads[0], 'CMS', 'Internal', 0, 0.24, 0.035, 1.2, cmsTextSize=0.9)
plot.DrawCMSLogo(pads[0], 'CMS', 'Internal', 11, 0.045, 0.05, 1.0, '', 1.0)

plot.DrawTitle(pads[-1], '136.9 fb^{-1} (13 TeV)', 3)
plot.DrawTitle(
    pads[0], 'W^{%s}(l^{%s}#nu)#gamma' %
    (chg_labels[args.charge], chg_labels[args.charge]), 1)

canv.Print('.png')
canv.Print('.pdf')
Exemplo n.º 29
0
if 'obs' in contours:
    legend.AddEntry(contours['obs'][0], "Observed", "F")
if 'exp-1' in contours and 'exp+1' in contours:
    legend.AddEntry(contours['exp-1'][0], "#pm 1#sigma Expected", "F")
if 'exp0' in contours:
    if 'obs' in contours:
        legend.AddEntry(contours['exp0'][0], "Expected", "L")
    else:
        legend.AddEntry(contours['exp0'][0], "Expected", "F")
if 'exp-2' in contours and 'exp+2' in contours:
    legend.AddEntry(contours['exp-2'][0], "#pm 2#sigma Expected", "F")
legend.Draw()

# Draw logos and titles
plot.DrawCMSLogo(pads[0], 'CMS', args.cms_sub, 11, 0.045, 0.15, 1.0, '', 1.0)
plot.DrawTitle(pads[0], args.title_right, 3)
plot.DrawTitle(pads[0], args.title_left, 1)

# Redraw the frame because it usually gets covered by the filled areas
pads[1].cd()
pads[1].GetFrame().Draw()
pads[1].RedrawAxis()

# Draw the scenario label
latex = ROOT.TLatex()
latex.SetNDC()
latex.SetTextSize(0.04)
latex.DrawLatex(0.155, 0.75, args.scenario_label)

canv.Print('.pdf')
canv.Print('.png')
Exemplo n.º 30
0
    legend.AddEntry(cont_minus1sigma[0], "#pm 1#sigma Expected", "F")
if cont_exp[0]: legend.AddEntry(cont_exp[0], "Expected", "L")
if cont_minus2sigma[0]:
    legend.AddEntry(cont_minus2sigma[0], "#pm 2#sigma Expected", "F")
legend.Draw("same")

# ROOT is just the worst - ARC requested the observed symbol in the legend be changed to this
if (cont_obs[0]):
    legline = ROOT.TLine(605, 13, 680, 13)
    legline.SetLineWidth(3)
    legline.SetLineColor(ROOT.kBlack)
    legline.DrawLineNDC(legend.GetX1() + 0.0106,
                        legend.GetY2() - 0.36,
                        legend.GetX1() + 0.0516,
                        legend.GetY2() - 0.36)

if args.custom_y_range:
    axis.GetYaxis().SetRangeUser(float(args.y_axis_min),
                                 float(args.y_axis_max))
axis.GetXaxis().SetTitle("m_{A} (GeV)")
if args.custom_x_range:
    axis.GetXaxis().SetRangeUser(float(args.x_axis_min),
                                 float(args.x_axis_max))
plot.DrawCMSLogo(pads[1], 'Combine Harvester', scenario_label, 11, 0.045,
                 0.035, 1.2)
plot.DrawTitle(pads[1], args.lumi_label, 3)
plot.FixOverlay()
c1.SaveAs(args.ana_label + "_" + args.scenario + ".pdf")
c1.SaveAs(args.ana_label + "_" + args.scenario + ".png")
c1.SaveAs(args.ana_label + "_" + args.scenario + ".C")