示例#1
0
def RatioCanvas(canvas_name,
                canvas_title,
                canw=500,
                canh=600,
                ratio_size_as_fraction=0.35):
    from ROOT import TCanvas, TPad
    c = TCanvas(canvas_name, canvas_title, canw, canh)
    c.cd()
    top = TPad("pad_top", "This is the top pad", 0.0, ratio_size_as_fraction,
               1.0, 1.0)
    top.SetBottomMargin(0.02 / float(top.GetHNDC()))
    top.SetTopMargin(0.04 / float(top.GetHNDC()))
    top.SetRightMargin(0.05)
    top.SetLeftMargin(0.16)
    top.SetFillColor(0)
    top.Draw()
    tobject_collector.append(top)

    c.cd()
    bot = TPad("pad_bot", "This is the bottom pad", 0.0, 0.0, 1.0,
               ratio_size_as_fraction)
    bot.SetBottomMargin(0.11 / float(bot.GetHNDC()))
    bot.SetTopMargin(0.02 / float(bot.GetHNDC()))
    bot.SetRightMargin(0.05)
    bot.SetLeftMargin(0.16)
    bot.SetFillColor(0)
    bot.Draw()
    tobject_collector.append(bot)

    return c
示例#2
0
def plot_data_vs_refold(args, regularisation_settings, tau):
    '''
    Plot the differences between the unfolded and refolded distributions

    TODO Include also with best tau - redo unfolding with best tau then come here
    '''
    from ROOT import gStyle

    variable = regularisation_settings.variable
    channel = regularisation_settings.channel
    plot_outpath = regularisation_settings.outpath.replace('tables/', 'plots/')+'tauscan/taus/'
    make_folder_if_not_exists(plot_outpath)

    # tau as string name for output
    tau = str(tau).replace('.', 'p')

    outfile = plot_outpath+'data_vs_refold_'+channel+'_'+variable+'_tau_'+tau+'.pdf'
    if args.run_measured_as_data:
        outfile = plot_outpath+'measured_vs_refold_'+channel+'_'+variable+'_tau_'+tau+'.pdf'
    if args.run_smeared_measured_as_data:
        outfile = plot_outpath+'smeared_vs_refold_'+channel+'_'+variable+'_tau_'+tau+'.pdf'
    if args.unfolded_binning:
        outfile = outfile.replace('.pdf', '_unf_binning.pdf')

    c = TCanvas('c1','c1',1000,800)
    gStyle.SetOptStat(0)

    p1 = TPad("pad1", "p1",0.0,0.2,1.0,1.0,21)
    p1.SetFillColor(0);
    p1.Draw()
    p2 = TPad("pad2", "p2",0.0,0.0,1.0,0.2,22)
    p2.SetFillColor(0);
    p2.Draw()

    p1.cd()
    regularisation_settings.h_data.SetTitle("Data vs Refolded Data;;NEvents")
    regularisation_settings.h_data.Draw()

    regularisation_settings.h_refolded.SetLineColor(2)
    regularisation_settings.h_refolded.Draw("same")

    leg1 = TLegend(0.7, 0.8, 0.9, 0.9)
    leg1.SetLineColor(0)
    leg1.SetFillColor(0)
    leg1.AddEntry(regularisation_settings.h_data, "Data")
    leg1.AddEntry(regularisation_settings.h_refolded, "Refolded Data")
    leg1.Draw()

    p2.cd()
    h_ratio = regularisation_settings.h_data.Clone()
    h_ratio.Divide(regularisation_settings.h_refolded)
    h_ratio.SetTitle(";"+variable+";")
    h_ratio.SetLineColor(1);
    h_ratio.Draw()

    c.SaveAs(outfile)
    c.Delete()
    print "Written plots to {outfile}".format(outfile = outfile)
    return
示例#3
0
def makePlot(mds, ds, pdf):
    """ Mass fit plot """
    frame = mds.frame()
    ds.plotOn(frame, DataError(RooAbsData.SumW2), MarkerSize(1))
    pdf.plotOn(frame, LineWidth(2))

    # pull histogram
    pullHist = frame.pullHist()
    pullFrame = mds.frame(Title(''))
    pullFrame.addPlotable(pullHist, 'P')
    pullFrame.GetYaxis().SetRangeUser(-5, 5)

    canvas = TCanvas('m(Ds)', 'm(Ds)', 600, 700)
    canvas.cd()

    pad1 = TPad('pad1', 'pad1', .01, .20, .99, .99)
    pad2 = TPad('pad2', 'pad2', .01, .01, .99, .20)
    pad1.Draw()
    pad2.Draw()

    pad1.cd()
    pad1.SetLeftMargin(0.15)
    pad1.SetFillColor(0)

    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetTitleOffset(0.85)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(1.6)
    frame.Draw()

    pad2.cd()
    pad2.SetLeftMargin(0.15)
    pad2.SetFillColor(0)
    
    pullFrame.SetMarkerSize(0.05)
    pullFrame.Draw()

    mdsRange = fitRange()['mDs']
    lineUp = TLine(mdsRange[0], 3, mdsRange[1], 3)
    lineUp.SetLineColor(kBlue)
    lineUp.SetLineStyle(2)
    lineUp.Draw()

    lineCe = TLine(mdsRange[0], 0, mdsRange[1], 0)
    lineCe.SetLineColor(kBlue)
    lineCe.SetLineStyle(1)
    lineCe.SetLineWidth(2)
    lineCe.Draw()

    lineD0 = TLine(mdsRange[0], -3, mdsRange[0], -3)
    lineD0.SetLineColor(kBlue)
    lineD0.SetLineStyle(2)
    lineD0.Draw()

    canvas.Update()
示例#4
0
文件: plot.py 项目: Pupoin/tool
def plot3(key, xsections, histos, names, LogY, weights, outputDIR):
  c1=TCanvas(key, key, 800, 600)
  pad1 = TPad("pad1", "", 0.00, 0.0, 0.99, 0.99)
  pad1.SetGridx()
  pad1.SetGridy()
  pad1.SetFillColor(0)
  pad1.SetLineColor(0)
  pad1.SetBottomMargin(0.1)
  pad1.Draw()

  leg1 = TLegend(0.68,0.55,0.86,0.86)
  histos[0].GetXaxis().SetLabelSize(0)
  histos[0].SetMarkerStyle(20)

  for i in range(0,len(histos)):
    #if histos[i].Integral()==0: continue
    histos[i].Scale(xsections[i]/weights[i])
    histos[i].SetLineColor(i+1)
    histos[i].SetLineWidth(2)


  pad1.cd()
  if LogY:
    pad1.SetLogy()
  ymax=[]
  histos[0].Draw('pe')
  for i in range(0, len(histos)):
    ymax.append(histos[i].GetMaximum())
  ymax.sort(reverse=True)
  histos[0].SetMaximum(1.2* ymax[0])
  #histos[0].SetMinimum(0.1)

  for i in range(1,len(histos)):
    histos[i].Draw('same h')
  histos[0].GetXaxis().SetTitle(key)
  histos[0].GetXaxis().SetTitleSize(0.04)
  histos[0].GetXaxis().SetTitleOffset(1.1)
  histos[0].GetXaxis().SetLabelSize(0.035)
  histos[0].GetYaxis().SetTitle("XS/bin [pb]")
  histos[0].GetYaxis().SetTitleSize(0.04)
  histos[0].GetYaxis().SetTitleOffset(1.09)
  histos[0].GetYaxis().SetLabelSize(0.035)

  leg1.AddEntry(histos[0], names[0])
  for i in range(1,len(histos)):
    leg1.AddEntry(histos[i], names[i])
  leg1.SetFillStyle(0)
  leg1.SetBorderSize(0)
  leg1.Draw()
  c1.Update()

  if LogY:
    c1.SaveAs(outputDIR + '/' + key + '_log.png')
    c1.SaveAs(outputDIR + '/' + key + '_log.pdf')
  else:
    c1.SaveAs(outputDIR + '/' + key + '.png')
    c1.SaveAs(outputDIR + '/' + key + '.pdf')
  for i in range(0,len(histos)):
    histos[i].Scale(weights[i]/xsections[i])
def PlotFakeRatio(ratio):
    c = TCanvas("c", "canvas", 800, 800)
    gStyle.SetOptStat(0)
    gStyle.SetLegendBorderSize(0)

    pad = TPad("pad", "pad", 0.01, 0.01, 0.99, 0.99)
    pad.Draw()
    pad.cd()
    pad.SetGrid()
    pad.SetFillColor(0)
    pad.SetFrameBorderMode(0)
    pad.SetBorderMode(0)

    xaxis_title = "Photon P_{T} [GeV]"

    leg = getLegend(xmin=0.5, ymin=0.7, scale=0.75)

    fake_style(ratio)
    ratio.SetTitle("")
    ratio.GetYaxis().SetTitle("Fake Ratio")
    # ratio.GetYaxis().SetTitleOffset(0.5)
    ratio.GetXaxis().SetTitle(xaxis_title)
    # ratio.GetYaxis().SetRangeUser(0.75,1.2)
    print SetBounds([ratio], scale=1)

    ratio.Draw("p same")

    leg.AddEntry(ratio, "#frac{Data_{ISO}}{Data_{Non-ISO}}", "lp")
    leg.Draw()

    lumi_label = '%s' % float('%.3g' %
                              (max(config.lumi.values()) / 1000.)) + " fb^{-1}"
    texLumi, texCMS = getCMSText(lumi_label, config.version, scale=0.8)

    SaveAs(c,
           "fake_ratio_%s" % parser.args.variable,
           year=config.version,
           sub="GammaPurity/FakeRatio/")
示例#6
0
文件: ps.py 项目: menglu21/GEN_staff
NonuJetpT_mad = TH1D("NonuJetpT madspin", "", 20, 0, 200)
NonuJetpT_mad.SetStats(0)
NonuJetpT_mad.Sumw2()
NonuJetpT_mad.GetYaxis().SetTitle("a.u.")
NonuJetpT_mad.GetYaxis().SetTitleSize(0.05)
NonuJetpT_mad.GetYaxis().SetTitleOffset(0.75)
NonuJetpT_mad.GetXaxis().SetLabelSize(0)
NonuJetpT_mad.SetMinimum(0)
NonuJetpT_nomad = TH1D("NonuJetpT nomadspin", "", 20, 0, 200)
NonuJetpT_nomad.SetStats(0)
NonuJetpT_nomad.Sumw2()

c1 = TCanvas("tauphi", "tauphi", 800, 600)
tauphi_pad1 = TPad("pad1", "", 0.00, 0.20, 0.99, 0.99)
tauphi_pad2 = TPad("pad2", "", 0.00, 0.00, 0.99, 0.20)
tauphi_pad1.SetFillColor(0)
tauphi_pad1.SetLineColor(0)
tauphi_pad2.SetFillColor(0)
tauphi_pad2.SetLineColor(0)
tauphi_pad1.SetBottomMargin(0.03)
tauphi_pad2.SetTopMargin(0.15)
tauphi_pad2.SetBottomMargin(0.3)
tauphi_pad1.Draw()
tauphi_pad2.Draw()

c2 = TCanvas("taueta", "taueta", 800, 600)
taueta_pad1 = TPad("pad1", "", 0.00, 0.20, 0.99, 0.99)
taueta_pad2 = TPad("pad2", "", 0.00, 0.00, 0.99, 0.20)
taueta_pad1.SetFillColor(0)
taueta_pad1.SetLineColor(0)
taueta_pad2.SetFillColor(0)
示例#7
0
def makeDiTauStack(outDir,
                   inFile,
                   rootDir,
                   s,
                   labelX,
                   units="GeV",
                   left=False,
                   channel="",
                   json="Golden",
                   log=False,
                   dndm=False,
                   doRatio=False,
                   year=2017,
                   sign='OS',
                   LTcut=0.,
                   cat='mmtt',
                   wait='wait'):

    tdrstyle.setTDRStyle()

    writeExtraText = True  # if extra text
    extraText = "Preliminary"  # default extra text is "Preliminary"
    lumi_sqrtS = "13 TeV"
    if json == "Golden": lumi_13TeV = channel + "    41.8 fb^{-1}, 2017"
    iPeriod = 4  # 1=7TeV, 2=8TeV, 3=7+8TeV, 7=7+8+13TeV

    xR = 0.65  #legend parameters
    xR = 0.2  #legend parameters
    H = 600
    W = 600
    H_ref = 600
    W_ref = 600

    # references for T, B, L, R
    T = 0.08 * H_ref
    B = 0.12 * H_ref
    L = 0.16 * W_ref
    R = 0.04 * W_ref

    #margins for inbetween the pads in a ratio plot
    B_ratio = 0.1 * H_ref
    T_ratio = 0.03 * H_ref

    #margin required for lebal on bottom of raito plot
    B_ratio_label = 0.3 * H_ref

    c = TCanvas('c1', 'c1', 50, 50, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)

    if not doRatio:
        c.SetLeftMargin(L / W)
        c.SetRightMargin(R / W)
        c.SetTopMargin(T / H)
        c.SetBottomMargin(B / H)

    c.cd()

    ratioPad = TPad("pad2", "", 0.0, 0.0, 1.0, 0.29)
    plotPad = TPad("pad1", "", 0.0016, 0.291, 1.0, 1.0)
    if doRatio:
        plotPad.SetTicks(0, 0)
        plotPad.SetLeftMargin(L / W)
        plotPad.SetRightMargin(R / W)
        plotPad.SetTopMargin(T / H)
        plotPad.SetBottomMargin(B_ratio / H)
        plotPad.SetFillColor(0)
        plotPad.SetBottomMargin(0)

        ratioPad.SetLeftMargin(L / W)
        ratioPad.SetRightMargin(R / W)
        ratioPad.SetTopMargin(T_ratio / H)
        ratioPad.SetTopMargin(0.007)
        ratioPad.SetBottomMargin(B_ratio_label / H)
        ratioPad.SetGridy(1)
        ratioPad.SetFillColor(4000)

    else:
        plotPad = TPad("pad1", "", 0.0, 0.03, 1.0, 1.0)
        plotPad.SetLeftMargin(L / W)
        plotPad.SetRightMargin(R / W)
        plotPad.SetTopMargin(T / H)
        plotPad.SetBottomMargin(B / H)

    plotPad.Draw()
    plotPad.cd()

    print("In makeStack inFile={0:s}".format(inFile))
    f = TFile(inFile)

    groups = ['data', 'Reducible', 'Rare', 'ZZ4L', 'Signal']
    histo = {}
    colors = {
        'data': 0,
        'Reducible': kMagenta - 10,
        'Rare': kBlue - 8,
        'ZZ4L': kAzure - 9,
        'Signal': kRed
    }
    hs = THStack("hs", "")
    for group in groups:
        if len(cat) == 4:
            histo[group] = f.Get("h{0:s}_{1:s}_Mtt".format(group, cat))
        else:
            histo[group] = f.Get("h{0:s}_ee{1:s}_Mtt".format(group, cat))
            histo2 = f.Get("h{0:s}_mm{1:s}_Mtt".format(group, cat))
            histo[group].Add(histo2)

        if dndm: convertToDNDM(histo[group])
        if group == 'data':
            applyDATAStyle(histo[group])
        else:
            applyStyle(histo[group], colors[group], 1, 1001)
        if group != 'data': hs.Add(histo[group])

    try:
        hMax = 1.2 * max(histo['data'].GetMaximum(), hs.GetMaximum())
    except KeyError:
        hMax = 1.2 * hs.GetMaximum()

    hs.SetMaximum(hMax)
    hs.Draw("HIST")
    try:
        histo['data'].Draw("e,SAME")
    except KeyError:
        pass

    if doRatio:
        hs.GetXaxis().SetLabelSize(0)
    else:
        if units != "":
            hs.GetXaxis().SetTitle(labelX + " [" + units + "]")
        else:
            hs.GetXaxis().SetTitle(labelX)

    hs.GetYaxis().SetTitle("Events")
    hs.GetYaxis().SetTitleOffset(1)

    if dndm: hs.GetYaxis().SetTitle("dN/d" + labelX)
    c.cd()
    if doRatio:
        data2 = histo['data'].Clone("data")
        mc = histo['Rare']
        mc.Add(histo['Reducible'])
        mc.Add(histo['ZZ4L'])
        xmin = mc.GetXaxis().GetXmin()
        xmax = mc.GetXaxis().GetXmax()
        line = TLine(xmin, 1.0, xmax, 1.0)
        line.SetLineWidth(1)
        line.SetLineColor(kBlack)

        ratioPad.Draw()
        ratioPad.cd()

        data2.Divide(data2, mc)

        data2.SetMarkerStyle(20)
        data2.SetTitleSize(0.12, "Y")
        data2.SetTitleOffset(0.40, "Y")
        data2.SetTitleSize(0.12, "X")
        data2.SetLabelSize(0.10, "X")
        data2.SetLabelSize(0.08, "Y")
        data2.GetYaxis().SetRangeUser(0.62, 1.38)
        data2.GetYaxis().SetNdivisions(305)
        data2.GetYaxis().SetTitle("Obs/Exp   ")

        if units != "":
            data2.GetXaxis().SetTitle(labelX + " [" + units + "]")
        else:
            data2.GetXaxis().SetTitle(labelX)

        data2.Draw("P")
        line.Draw()

    c.cd()
    plotPad.cd()

    l = TLegend(xR, 0.55, xR + 0.28, 0.9)
    for group in groups:
        try:
            l.AddEntry(histo[group], group, "F")
        except KeyError:
            continue

    l.SetBorderSize(0)
    l.SetFillColor(0)
    l.SetFillStyle(0)
    l.SetTextSize(0.04)
    l.Draw()

    lTex1 = TLatex(120., 0.97 * hMax, 'Preliminary {0:d}'.format(year))
    lTex1.SetTextSize(0.04)
    lTex1.Draw()
    signText = 'Same Sign'
    if sign == 'OS': signText = 'Opposite Sign'
    lTex2 = TLatex(120., 0.90 * hMax, '{0:s}'.format(signText))
    lTex2.SetTextSize(0.04)
    lTex2.Draw()
    if len(cat) == 4:
        lt = {
            'eeet': '#it{l}#it{l}#it{e}#tau',
            'eemt': '#it{l}#it{l}#mu#tau',
            'eett': '#it{l}#it{l}#tau#tau',
            'mmet': '#mu#mu#it{e}#tau',
            'mmmt': '#mu#mu#mu#tau',
            'mmtt': '#mu#mu#tau#tau'
        }
    else:
        lt = {
            'et': '#it{l}#it{l}#it{e}#tau',
            'mt': '#it{l}#it{l}#mu#tau',
            'tt': '#it{l}#it{l}#tau#tau'
        }
    lTex3 = TLatex(120., 0.83 * hMax,
                   '{0:s} H_LT > {1:d} '.format(lt[cat], int(LTcut)))
    lTex3.SetTextSize(0.04)
    lTex3.Draw()

    plotPad.Draw()
    #CMS_lumi(plotPad,4,11)

    outFileBase = "Stack_{0:d}_{1:s}_{2:s}_LT{3:02d}".format(
        year, cat, sign, int(LTcut))
    c.SaveAs("{0:s}.png".format(outFileBase))
    c.SaveAs("{0:s}.root".format(outFileBase))
    if wait == 'wait':
        raw_input()
    else:
        import time
        time.sleep(5.)
#exit()
ratioPad = TPad("pad2","",0.0,0.0,1.0,0.29)
exit()
print("After ratioPad") 
plotPad = TPad("pad1","",0.0016,0.291,1.0,1.0)
print("After plotPad")

exit()

if doRatio :
    plotPad.SetTicks(0,0)
    plotPad.SetLeftMargin(L/W)
    plotPad.SetRightMargin(R/W)
    plotPad.SetTopMargin(T/H)
    plotPad.SetBottomMargin(B_ratio/H) 
    plotPad.SetFillColor(0)
    plotPad.SetBottomMargin(0)
    
    ratioPad.SetLeftMargin  (L/W)
    ratioPad.SetRightMargin (R/W)
    ratioPad.SetTopMargin   (T_ratio/H)
    ratioPad.SetTopMargin   (0.007)
    ratioPad.SetBottomMargin(B_ratio_label/H)
    ratioPad.SetGridy(1)
    ratioPad.SetFillColor(4000)
else :
    print("L={0:f} W={1:f} R={2:f} H={3:f}".format(L,W,R,H))
    plotPad = TPad("pad1","",0.0,0.03,1.0,1.0)
    print("After pad1")
    plotPad.SetLeftMargin(L/W)
    plotPad.SetRightMargin(R/W)
def thresholds(var, title, xtitle, nbin, low, high, region):
    cutter = cuts[region]
    weight = cutter
    can = TCanvas("can", "can", 1000, 900)
    can.SetBottomMargin(0.3)
    can.SetRightMargin(0.06)
    can.cd()
    gPad.SetLogy(1)
    gStyle.SetOptStat(0)
    backs = TH1D('a', 'a', nbin, low, high)
    backs.SetFillStyle(3344)
    backs.SetFillColor(1)
    phojet = TH1D('b', 'b', nbin, low, high)
    phojet.SetFillColor(7)
    phojet.SetLineColor(7)
    qcd = TH1D('c', 'c', nbin, low, high)
    qcd.SetFillColor(5)
    qcd.SetLineColor(5)
    stack = THStack('d', title + ";" + xtitle + ";" + "Events")
    Variables = {}
    print "Variable: " + var
    for tre in List:
        histName = var + tre
        Variables[tre] = TH1F(histName, ";" + xtitle + ";" + "Events", nbin,
                              low, high)
        #		if tre == "dipho":
        #			weight = cutter+"&& (JetPho_dR<0.1)"
        treepj[tre].Draw(var + ">>" + histName, weight)
        Variables[tre].Sumw2()
        scalable = lumi * crossx[tre] * kFact[tre] / Nevents[tre]
        Variables[tre].Scale(scalable)
        if tre.startswith("df"):
            Variables[tre].SetLineColor(colors[tre])
            Variables[tre].SetLineWidth(3)
        if tre.startswith("GJets"):
            backs.Add(Variables[tre])
            phojet.Add(Variables[tre])
        if tre.startswith("QCD"):
            backs.Add(Variables[tre])
            qcd.Add(Variables[tre])
        if tre.startswith("DiPhoton"):
            Variables[tre].SetFillColor(3)
            Variables[tre].SetLineColor(3)
            backs.Add(Variables[tre])
    Variables['Data'] = TH1F('data', ";" + xtitle + ";" + "Events", nbin, low,
                             high)
    treepj['Data'].Draw(var + ">>data", cutter, "goff")
    Variables['Data'].SetLineColor(1)
    Variables['Data'].SetLineWidth(2)
    stack.Add(Variables['DiPhoton'])
    stack.Add(qcd)
    stack.Add(phojet)
    stack.SetMaximum(1000000.0)
    stack.SetMinimum(0.001)
    stack.Draw("hist")
    stack.GetXaxis().SetLabelSize(0)
    backs.Draw("e2same")
    Variables['Data'].Draw("e1same")
    Variables['df1en0'].Draw("histsame")
    Variables['df1en1'].Draw("histsame")
    Variables['df1en2'].Draw("histsame")
    Variables['df1en3'].Draw("histsame")
    pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0)
    pad.SetTopMargin(0.7)
    pad.SetFillColor(0)
    pad.SetGridy(1)
    pad.SetFillStyle(0)
    pad.Draw()
    pad.cd(0)
    pad.SetRightMargin(0.06)
    Pull = TH1D('Pull', 'Pull', nbin, low, high)
    Pull = Variables['Data'].Clone()
    Pull.Divide(backs)
    Pull.SetMarkerStyle(20)
    Pull.SetMaximum(2.0)
    Pull.SetMinimum(0.0)
    Pull.SetFillColor(2)
    Pull.GetXaxis().SetTitle(xtitle)
    Pull.GetYaxis().SetTitleSize(0.04)
    Pull.GetYaxis().SetTitle('Data/MC')
    Pull.SetMarkerSize(0.7)
    Pull.GetYaxis().SetNdivisions(5)
    line = TF1("line", "1", low, high)
    line.SetLineColor(2)
    line.SetLineWidth(2)
    Pull.Draw("e1")
    line.Draw('same')
    latex2 = TLatex()
    latex2.SetNDC()
    latex2.SetTextSize(0.035)
    latex2.SetTextAlign(31)  # align right
    latex2.DrawLatex(
        0.87, 0.95,
        "Work In Progress, " + str(lumi) + " fb^{-1} at #sqrt{s} = 13 TeV")
    led = TLegend(0.7, 0.7, 0.94, 0.9)
    led.AddEntry(phojet, "#gamma + Jet", 'f')
    led.AddEntry(qcd, "QCD DiJet", 'f')
    led.AddEntry(Variables['DiPhoton'], "#gamma + #gamma", 'f')
    led.AddEntry(Variables['df1en0'], "f_{D} = 1E0")
    led.AddEntry(Variables['df1en1'], "f_{D} = 1E-1")
    led.AddEntry(Variables['df1en2'], "f_{D} = 1E-2")
    led.AddEntry(Variables['df1en3'], "f_{D} = 1E-3")
    led.AddEntry(Variables['Data'], "Data")
    led.SetFillColor(0)
    led.Draw("same")
    can.SaveAs("plots/" + region + "-" + var + ".pdf")
    can.Close()
    phojet.Delete()
    qcd.Delete()
示例#10
0
文件: lhe.py 项目: menglu21/GEN_staff
neueta_mad.SetStats(0)
neueta_mad.Sumw2()
neueta_mad.GetYaxis().SetTitle("a.u.")
neueta_mad.GetYaxis().SetTitleSize(0.05)
neueta_mad.GetYaxis().SetTitleOffset(0.75)
neueta_mad.GetXaxis().SetLabelSize(0)
#neueta_mad.SetMaximum(1000)
neueta_mad.SetMinimum(0)
neueta_nomad = TH1D("neu eta nomadspin","",30,-3,3)
neueta_nomad.SetStats(0)
neueta_nomad.Sumw2()

c1= TCanvas("lphi","lphi",800,600)
lphi_pad1 = TPad("pad1", "", 0.00, 0.20, 0.99, 0.99)
lphi_pad2 = TPad("pad2", "", 0.00, 0.00, 0.99, 0.20)
lphi_pad1.SetFillColor(0)
lphi_pad1.SetLineColor(0)
lphi_pad2.SetFillColor(0)
lphi_pad2.SetLineColor(0)
lphi_pad1.SetBottomMargin(0.03);
lphi_pad2.SetTopMargin(0.15);
lphi_pad2.SetBottomMargin(0.3);
lphi_pad1.Draw()
lphi_pad2.Draw()

c2= TCanvas("lpt","lpt",800,600)
lpt_pad1 = TPad("pad1", "", 0.00, 0.20, 0.99, 0.99)
lpt_pad2 = TPad("pad2", "", 0.00, 0.00, 0.99, 0.20)
lpt_pad1.SetFillColor(0)
lpt_pad1.SetLineColor(0)
lpt_pad2.SetFillColor(0)
示例#11
0
def eraselabel(pad, h):
    pad.cd()
    pe = TPad("pe", "pe", 0, 0, pad.GetLeftMargin(), h)
    pe.Draw()
    pe.SetFillColor(pad.GetFillColor())
    pe.SetBorderMode(0)
示例#12
0
def DrawOverlap(fileVec,
                histVec,
                titleVec,
                legendtext,
                pngname,
                logstatus=[0, 0],
                xRange=[-99999, 99999, 1]):

    gStyle.SetOptTitle(0)
    gStyle.SetOptStat(0)
    gStyle.SetTitleOffset(1.1, "Y")
    gStyle.SetTitleOffset(0.9, "X")
    gStyle.SetLineWidth(3)
    gStyle.SetFrameLineWidth(3)

    i = 0

    histList_ = []
    histList = []
    histList1 = []
    maximum = []

    ## Legend
    leg = TLegend(0.65, 0.650, 0.89, 0.85)  #,NULL,"brNDC");
    leg.SetBorderSize(0)
    #    leg.SetNColumns(3)
    leg.SetLineColor(1)
    leg.SetLineStyle(1)
    leg.SetLineWidth(1)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetTextFont(22)
    leg.SetTextSize(0.045)

    c = TCanvas("c1", "c1", 0, 0, 500, 500)
    #c.SetBottomMargin(0.15)
    #c.SetLeftMargin(0.15)
    #c.SetLogy(0)
    #c.SetLogx(0)
    c1_2 = TPad("c1_2", "newpad", 0., 0.30, 1, 0.994)
    c1_2.Draw()
    c1_1 = TPad("c1_1", "newpad1", 0, 0.02, 1, 0.30)
    c1_1.Draw()

    print("you have provided " + str(len(fileVec)) + " files and " +
          str(len(histVec)) + " histograms to make a overlapping plot")
    print "opening rootfiles"
    c.cd()
    c1_2.SetBottomMargin(0.013)
    c1_2.SetLogy(logstatus[1])
    c1_2.SetLogx(logstatus[0])

    c1_2.cd()
    ii = 0
    inputfile = {}
    print str(fileVec[(len(fileVec) - 1)])
    for ifile_ in range(len(fileVec)):
        print("opening file  " + fileVec[ifile_])
        inputfile[ifile_] = TFile(fileVec[ifile_])
        print "fetching histograms"
        for ihisto_ in range(len(histVec)):
            print("printing histo " + str(histVec[ihisto_]))
            histo = inputfile[ifile_].Get(histVec[ihisto_])
            #status_ = type(histo) is TGraphAsymmErrors
            histList.append(histo)
            # for ratio plot as they should nt be normalize
            histList1.append(histo)
            print histList[ii].Integral()
            histList[ii].Rebin(xRange[2])
            print('after', histList[ii].Integral(0, -1))
            histList[ii].Scale(1.0 / histList[ii].Integral(0, -1))
            maximum.append(histList[ii].GetMaximum())
            maximum.sort()
            ii = ii + 1

    print histList
    for ih in range(len(histList)):
        tt = type(histList[ih])
        if logstatus[1] is 1:
            histList[ih].SetMaximum(maximum[(len(maximum) - 1)] *
                                    25)  #1.4 for log
            histList[ih].SetMinimum(0.001)  #1.4 for log
        if logstatus[1] is 0:
            histList[ih].SetMaximum(maximum[(len(maximum) - 1)] *
                                    1.2)  #1.4 for log
            histList[ih].SetMinimum(0)  #1.4 for log


#        print "graph_status =" ,(tt is TGraphAsymmErrors)
#        print "hist status =", (tt is TH1D) or (tt is TH1F)
        if ih == 0:
            if tt is TGraphAsymmErrors:
                histList[ih].Draw("AP")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("hist")
        if ih > 0:
            #histList[ih].SetLineWidth(2)
            if tt is TGraphAsymmErrors:
                histList[ih].Draw("P same")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("hist same")

        if tt is TGraphAsymmErrors:
            histList[ih].SetMaximum(1.4)
            histList[ih].SetMarkerColor(colors[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetMarkerStyle(markerStyle[ih])
            histList[ih].SetMarkerSize(1)
            leg.AddEntry(histList[ih], legendtext[ih], "PL")
        if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
            histList[ih].SetLineStyle(linestyle[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetLineWidth(3)
            leg.AddEntry(histList[ih], legendtext[ih], "L")
        histList[ih].GetYaxis().SetTitle(titleVec[1])
        histList[ih].GetYaxis().SetTitleSize(0.062)
        histList[ih].GetYaxis().SetTitleOffset(0.78)
        histList[ih].GetYaxis().SetTitleFont(22)
        histList[ih].GetYaxis().SetLabelFont(22)
        histList[ih].GetYaxis().SetLabelSize(.062)
        histList[ih].GetXaxis().SetRangeUser(xRange[0], xRange[1])
        histList[ih].GetXaxis().SetLabelSize(0.0000)
        histList[ih].GetXaxis().SetTitle(titleVec[0])
        histList[ih].GetXaxis().SetLabelSize(0.052)
        histList[ih].GetXaxis().SetTitleSize(0.052)
        histList[ih].GetXaxis().SetTitleOffset(1.04)
        histList[ih].GetXaxis().SetTitleFont(22)
        histList[ih].GetXaxis().SetTickLength(0.07)
        histList[ih].GetXaxis().SetLabelFont(22)
        histList[ih].GetYaxis().SetLabelFont(22)
        # histList[ih].GetXaxis().SetNdivisions(508)
        #

        i = i + 1
    pt = TPaveText(0.0877181, 0.91, 0.9580537, 0.95, "brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(22)
    pt.SetTextSize(0.046)
    #    text = pt.AddText(0.05,0.5,"ATLAS Internal ")
    text = pt.AddText(0.65, 1.0, "#sqrt{s} = 13 TeV (36fb^{-1})")
    pt.Draw()

    t2a = TPaveText(0.277181, 0.81, 0.6780537, 0.89, "brNDC")
    t2a.SetBorderSize(0)
    t2a.SetFillStyle(0)
    t2a.SetTextSize(0.046)
    t2a.SetTextAlign(12)
    t2a.SetTextFont(22)
    histolabel1 = str(fileVec[(len(fileVec) - 1)])
    text1 = t2a.AddText(0.065, 0.5, "ATLAS Internal")
    t2a.Draw()
    leg.Draw()
    #
    c.cd()

    h_inc = histList1[0].Clone()
    h_vbs = histList1[1].Clone()
    h_qcd = histList1[2].Clone()
    h_int = histList1[3].Clone()

    h_inc.Add(h_vbs, -1)
    h_inc.Add(h_qcd, -1)

    ## ratio plot
    hdivide_1 = h_int.Clone()
    hdivide_1.Divide(h_vbs)
    # hdivide_1.GetYaxis().SetTitle(str(legendtext[(len(legendtext)-1)]))
    hdivide_1.GetYaxis().SetTitleSize(0.11)
    hdivide_1.GetYaxis().SetTitle("ratio")

    hdivide_1.GetYaxis().SetTitleOffset(0.43)
    hdivide_1.GetYaxis().SetTitleFont(22)
    hdivide_1.GetYaxis().SetLabelSize(0.13)
    hdivide_1.GetYaxis().CenterTitle()

    hdivide_1.GetXaxis().SetTitleSize(0.14)
    hdivide_1.GetXaxis().SetTitleOffset(0.89)
    hdivide_1.GetXaxis().SetTitleFont(22)
    hdivide_1.GetXaxis().SetLabelSize(0.14)

    hdivide_1.GetYaxis().SetLabelFont(22)
    c.cd()
    c1_1.cd()

    #    c1_1.Range(-7.862408,-629.6193,53.07125,486.5489)
    c1_1.SetFillColor(0)
    c1_1.SetTicky(1)
    c1_1.SetTopMargin(0.0510)
    c1_1.SetBottomMargin(0.3006666678814)
    c1_1.SetFrameFillStyle(0)
    c1_1.SetFrameBorderMode(0)
    c1_1.SetFrameFillStyle(0)
    c1_1.SetFrameBorderMode(0)
    c1_1.SetLogy(0)
    hdivide_1.GetXaxis().SetRangeUser(xRange[0], xRange[1])
    hdivide_1.GetYaxis().SetNdivisions(505)
    c1_1.Draw()
    c1_1.SetGridy()

    hdivide_1.SetMarkerStyle(20)
    hdivide_1.SetMarkerColor(2)
    hdivide_1.SetMarkerSize(1)
    hdivide_1.Draw("P")

    hdivide_2 = h_int.Clone()
    hdivide_2.Divide(h_qcd)
    hdivide_2.SetMarkerStyle(21)
    hdivide_2.SetMarkerColor(4)
    hdivide_2.SetMarkerSize(1)
    hdivide_2.Draw("Psame")

    hdivide_3 = h_int.Clone()
    hdivide_3.Divide(h_inc)
    hdivide_3.SetMarkerStyle(22)
    hdivide_3.SetMarkerColor(1)
    hdivide_3.SetMarkerSize(1)
    hdivide_3.Draw("Psame")

    hdivide_1.SetMinimum(-1.01)
    hdivide_1.SetMaximum(3.20)

    c.cd()

    outputdirname = 'plots/'
    histname = outputdirname + pngname
    c.SaveAs(histname + '.png')
    c.SaveAs(histname + '.pdf')
    c.SaveAs(histname + '.root')
    c.SaveAs(histname + '.C')
示例#13
0
class TopPad:
   def __init__(self):
      # list of plots for this pad
      self.plots = []

   def AddPlot(self,plot,draw_options='',legend_label=None,legend_draw_options='lp'):
      clone = plot.Clone(plot.GetName() + '_clone')
      clone.SetDirectory(0)
      self.plots.append(Plot(clone,draw_options,legend_label,legend_draw_options))
   
   def Draw(self,
            pad_name             = 'top_pad',
            pad_title            = 'Top Pad',
            pad_x1               = 0,
            pad_y1               = 0,
            pad_x2               = 1,
            pad_y2               = 1,
            pad_border_size      = 1,
            pad_bottom_margin    = 0,
            pad_top_margin       = 0,
            pad_left_margin      = 0,
            pad_right_margin     = 0,
            pad_y_ndiv           = None,
            legend_x1            = None,
            legend_y1            = None,
            legend_x2            = None,
            legend_y2            = None,
            legend_border_size   = 0,
            legend_fill_style    = 0,
            legend_chi2          = False,
            ):

      # create the pad
      self.pad = TPad(pad_name,
                      pad_title,
                      pad_x1,
                      pad_y1,
                      pad_x2,
                      pad_y2,
                      pad_border_size,
                      0,
                     )
      self.pad.SetMargin(pad_left_margin,pad_right_margin,pad_bottom_margin,pad_top_margin)
      self.pad.SetFillColor(0)
      self.pad.Draw()
      self.pad.cd()

      # create the legend
      draw_legend = False
      if legend_x1 != None and legend_x2 != None and legend_y1 != None and legend_y2 != None:
         draw_legend = True

      if draw_legend:
         self.legend = TLegend(legend_x1,legend_y1,legend_x2,legend_y2)
         self.legend.SetBorderSize(legend_border_size)
         self.legend.SetFillStyle(legend_fill_style)

      # draw the plots
      for i in range(len(self.plots)):
         plot = self.plots[i]
         chi2 = None
         if i == 0:
            #plot.plot.GetYaxis().SetLabelSize(0)
            # can turn off the X-axis labels
            plot.plot.GetXaxis().SetLabelSize(0)
            plot.plot.GetXaxis().SetTitle('')
            if pad_y_ndiv is not None:
               plot.plot.GetYaxis().SetNdivisions(pad_y_ndiv)
            plot.Draw()
         else:
            plot.Draw(same=True)
            # calculate chi2 between this plot and the first
            if legend_chi2:
               chi2 = ChiSquared.TH1ChiSquared(self.plots[0].plot,plot.plot)
         if draw_legend:
            plot.AddToLegend(self.legend,chi2)
      
      if draw_legend:
         self.legend.Draw('same')
示例#14
0
def plot2(key, xsections, histos, names, LogY, weights, outputDIR):
  c1=TCanvas(key, key, 800, 600)
  pad1 = TPad("pad1", "", 0.00, 0.20, 0.99, 0.99)
  pad2 = TPad("pad2", "", 0.00, 0.00, 0.99, 0.20)
  pad1.SetGridx()
  pad1.SetGridy()
  pad2.SetGridy()
  pad1.SetFillColor(0)
  pad1.SetLineColor(0)
  pad2.SetFillColor(0)
  pad2.SetLineColor(0)
  pad1.SetBottomMargin(0.03)
  pad2.SetTopMargin(0.15)
  pad2.SetBottomMargin(0.3)
  pad1.Draw()
  pad2.Draw()

  leg1 = TLegend(0.68,0.55,0.86,0.86)
  histos[0].GetXaxis().SetLabelSize(0)
  histos[0].SetMarkerStyle(20)

  for i in range(0,len(histos)):
    #if histos[i].Integral()==0: continue
    histos[i].Scale(xsections[i]/weights[i])
    histos[i].SetLineColor(i+1)
    histos[i].SetLineWidth(2)

  histo_ratio=histos[1].Clone()
  for i in range(2,len(histos)):
    histo_ratio.Add(histos[i])
  histo_ratio.SetLineWidth(2)

  histo_sum=histo_ratio.Clone()
  histo_sum.SetLineColor(49)
  histo_sum.SetLineWidth(2)

  histo_ratio.SetTitle('')
  histo_ratio.Divide(histos[0])
  histo_ratio.SetLineColor(49)
  histo_ratio.SetMaximum(1.5)
  histo_ratio.SetMinimum(0.5)
  histo_ratio.GetYaxis().SetNdivisions(4,kFALSE)
  histo_ratio.GetXaxis().SetTitle(key)
  histo_ratio.GetXaxis().SetTitleSize(0.15)
  histo_ratio.GetXaxis().SetTitleOffset(0.75)
  histo_ratio.GetXaxis().SetLabelSize(0.13)
  histo_ratio.GetYaxis().SetTitle('summed/inc')
  histo_ratio.GetYaxis().SetTitleSize(0.1)
  histo_ratio.GetYaxis().SetTitleOffset(0.3)
  histo_ratio.GetYaxis().SetLabelSize(0.13)

  pad1.cd()
  if LogY:
    pad1.SetLogy()
  histos[0].SetMaximum(1.2*histos[0].GetMaximum())
  histos[0].SetMinimum(0.0001)
  histos[0].Draw('pe')
  for i in range(1,len(histos)):
    histos[i].Draw('same h')
  histo_sum.Draw('same h')  
  
  leg1.AddEntry(histos[0], names[0])
  leg1.AddEntry(histo_sum, 'MGsummed')
  for i in range(1,len(histos)):
    leg1.AddEntry(histos[i], names[i])
  leg1.SetFillStyle(0)
  leg1.SetBorderSize(0)
  leg1.Draw()
  c1.Update()

  pad2.cd()
  histo_ratio.Draw()
  if LogY:
    c1.SaveAs(outputDIR + '/' + key + '_log.png')
    c1.SaveAs(outputDIR + '/' + key + '_log.pdf')
  else:
    c1.SaveAs(outputDIR + '/' + key + '.png')
    c1.SaveAs(outputDIR + '/' + key + '.pdf')
  for i in range(0,len(histos)):
    histos[i].Scale(weights[i]/xsections[i])
def makeDiTauStack(outDir,
                   inFile,
                   rootDir,
                   s,
                   labelX,
                   units="GeV",
                   left=False,
                   channel="",
                   json="Golden",
                   log=False,
                   dndm=False,
                   doRatio=False):

    cat = 'mmtt'
    tdrstyle.setTDRStyle()

    writeExtraText = True  # if extra text
    extraText = "Preliminary"  # default extra text is "Preliminary"
    lumi_sqrtS = "13 TeV"
    if json == "Golden": lumi_13TeV = channel + "    41.8 fb^{-1}, 2017"
    iPeriod = 4  # 1=7TeV, 2=8TeV, 3=7+8TeV, 7=7+8+13TeV

    xR = 0.65  #legend parameters
    xR = 0.2  #legend parameters
    H = 600
    W = 600
    H_ref = 600
    W_ref = 600

    # references for T, B, L, R
    T = 0.08 * H_ref
    B = 0.12 * H_ref
    L = 0.16 * W_ref
    R = 0.04 * W_ref

    #margins for inbetween the pads in a ratio plot
    B_ratio = 0.1 * H_ref
    T_ratio = 0.03 * H_ref

    #margin required for lebal on bottom of raito plot
    B_ratio_label = 0.3 * H_ref

    c = TCanvas('c1', 'c1', 50, 50, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)

    if not doRatio:
        c.SetLeftMargin(L / W)
        c.SetRightMargin(R / W)
        c.SetTopMargin(T / H)
        c.SetBottomMargin(B / H)

    c.cd()

    ratioPad = TPad("pad2", "", 0.0, 0.0, 1.0, 0.29)
    plotPad = TPad("pad1", "", 0.0016, 0.291, 1.0, 1.0)
    if doRatio:
        plotPad.SetTicks(0, 0)
        plotPad.SetLeftMargin(L / W)
        plotPad.SetRightMargin(R / W)
        plotPad.SetTopMargin(T / H)
        plotPad.SetBottomMargin(B_ratio / H)
        plotPad.SetFillColor(0)
        plotPad.SetBottomMargin(0)

        ratioPad.SetLeftMargin(L / W)
        ratioPad.SetRightMargin(R / W)
        ratioPad.SetTopMargin(T_ratio / H)
        ratioPad.SetTopMargin(0.007)
        ratioPad.SetBottomMargin(B_ratio_label / H)
        ratioPad.SetGridy(1)
        ratioPad.SetFillColor(4000)

    else:
        plotPad = TPad("pad1", "", 0.0, 0.03, 1.0, 1.0)
        plotPad.SetLeftMargin(L / W)
        plotPad.SetRightMargin(R / W)
        plotPad.SetTopMargin(T / H)
        plotPad.SetBottomMargin(B / H)

    plotPad.Draw()
    plotPad.cd()

    print("In makeStack inFile={0:s}".format(inFile))
    f = TFile(inFile)

    groups = ['data', 'Reducible', 'Rare', 'ZZ4L', 'Signal']
    histo = {}
    colors = {
        'data': 0,
        'Reducible': kMagenta - 10,
        'Rare': kBlue - 8,
        'ZZ4L': kAzure - 9,
        'Signal': kOrange - 4
    }
    hs = THStack("hs", "")
    for group in groups:
        histo[group] = f.Get("h{0:s}_{1:s}_Mtt".format(group, cat))
        #print("In makeStack(): histo={0:s} type(histo)={1:s}".format(str(histo[group]),type(histo[group])))
        if dndm: convertToDNDM(histo[group])
        if group == 'data':
            applyDATAStyle(histo[group])
        elif group == 'Signal':
            applySignalStyle(histo[group])
        else:
            applyStyle(histo[group], colors[group], 1, 1001)
        if group != 'data': hs.Add(histo[group])

    hMax = 1.2 * max(histo['data'].GetMaximum(), hs.GetMaximum())
    print("hMax={0:f}".format(hMax))
    hs.SetMaximum(hMax)
    hs.Draw("HIST")
    histo['data'].Draw("e,SAME")

    if doRatio:
        hs.GetXaxis().SetLabelSize(0)
    else:
        if units != "":
            hs.GetXaxis().SetTitle(labelX + " [" + units + "]")
        else:
            hs.GetXaxis().SetTitle(labelX)

    hs.GetYaxis().SetTitle("Events")
    hs.GetYaxis().SetTitleOffset(1)

    if dndm: hs.GetYaxis().SetTitle("dN/d" + labelX)

    c.cd()

    if doRatio:
        data2 = histo['data'].Clone("data")
        mc = histo['Rare']
        mc.Add(histo['Reducible'])
        mc.Add(histo['ZZ4L'])
        xmin = mc.GetXaxis().GetXmin()
        xmax = mc.GetXaxis().GetXmax()
        line = TLine(xmin, 1.0, xmax, 1.0)
        line.SetLineWidth(1)
        line.SetLineColor(kBlack)

        ratioPad.Draw()
        ratioPad.cd()

        data2.Divide(data2, mc)

        data2.SetMarkerStyle(20)
        data2.SetTitleSize(0.12, "Y")
        data2.SetTitleOffset(0.40, "Y")
        data2.SetTitleSize(0.12, "X")
        data2.SetLabelSize(0.10, "X")
        data2.SetLabelSize(0.08, "Y")
        data2.GetYaxis().SetRangeUser(0.62, 1.38)
        data2.GetYaxis().SetNdivisions(305)
        data2.GetYaxis().SetTitle("Obs/Exp   ")

        if units != "":
            data2.GetXaxis().SetTitle(labelX + " [" + units + "]")
        else:
            data2.GetXaxis().SetTitle(labelX)

        data2.Draw("P")
        line.Draw()

    c.cd()
    plotPad.cd()

    l = TLegend(xR, 0.55, xR + 0.28, 0.9)
    for group in groups:
        l.AddEntry(histo[group], group, "F")
    l.SetBorderSize(0)
    l.SetFillColor(0)
    l.SetFillStyle(0)
    l.Draw()

    factor = 1.05
    if left: factor = 1. / 2.2

    xL = hs.GetXaxis().GetXmin() + (hs.GetXaxis().GetXmax() -
                                    hs.GetXaxis().GetXmin()) * xR * factor
    yL = hs.GetMaximum() * 0.35

    offsetF = yL - 0.1 * hs.GetMaximum()
    offsetFF = yL - 0.2 * hs.GetMaximum()

    plotPad.Draw()
    #CMS_lumi(plotPad,4,11)

    c.SaveAs("stack.png")
    c.SaveAs("stack.root")
    raw_input()
示例#16
0
def plot1(key, xsection1, xsection2, histo1, histo2, name1, name2, LogY, weight1, weight2, outputDIR):
  c1=TCanvas(key, key, 800, 600)
  pad1 = TPad("pad1", "", 0.00, 0.20, 0.99, 0.99)
  pad2 = TPad("pad2", "", 0.00, 0.00, 0.99, 0.20)
  pad1.SetGridx()
  pad1.SetGridy()
  pad2.SetGridy()
  pad1.SetFillColor(0)
  pad1.SetLineColor(0)
  pad2.SetFillColor(0)
  pad2.SetLineColor(0)
  pad1.SetBottomMargin(0.03)
  pad2.SetTopMargin(0.15)
  pad2.SetBottomMargin(0.3)
  pad1.Draw()
  pad2.Draw()

  leg1 = TLegend(0.65,0.75,0.86,0.86)

  histo1.Scale(xsection1/weight1)
  histo1.SetMaximum(1.2*histo1.GetMaximum())
  histo1.SetMinimum(0.0001)
  histo1.SetLineColor(kRed)
  histo1.SetLineWidth(2)
  histo1.GetXaxis().SetLabelSize(0)
  histo2.Scale(xsection2/weight2)
  histo2.SetLineColor(kBlack)
  histo2.SetLineWidth(2)
  
  pad1.cd()
  if LogY:
    pad1.SetLogy()

  histo_ratio=histo2.Clone()
  histo_ratio.SetTitle('')
  histo_ratio.Divide(histo1)
  histo_ratio.SetMaximum(1.5)
  histo_ratio.SetMinimum(0.5)
  histo_ratio.GetYaxis().SetNdivisions(4,kFALSE)
  histo_ratio.GetXaxis().SetTitle(key)
  histo_ratio.GetXaxis().SetTitleSize(0.15)
  histo_ratio.GetXaxis().SetTitleOffset(0.75)
  histo_ratio.GetXaxis().SetLabelSize(0.13)
  histo_ratio.GetYaxis().SetTitle(name1+'/'+name2)
  histo_ratio.GetYaxis().SetTitleSize(0.1)
  histo_ratio.GetYaxis().SetTitleOffset(0.3)
  histo_ratio.GetYaxis().SetLabelSize(0.13)
  histo_ratio.SetLineWidth(2)

  histo1.Draw('pe')
  histo2.Draw('same pe')
  leg1.AddEntry(histo1, name1)
  leg1.AddEntry(histo2, name2)
  leg1.SetFillStyle(0)
  leg1.SetBorderSize(0)
  leg1.Draw()
  c1.Update()
 
  pad2.cd()
  histo_ratio.Draw()
  if LogY:
    c1.SaveAs(outputDIR + '/' + key + '_log.png')
    c1.SaveAs(outputDIR + '/' + key + '_log.pdf')
  else:
    c1.SaveAs(outputDIR + '/' + key + '.png')
    c1.SaveAs(outputDIR + '/' + key + '.pdf')

  # renew 
  histo1.Scale(weight1/xsection1)
  histo2.Scale(weight2/xsection2)
示例#17
0
    def __plot_profiles_in_same_canvas(self, hist_objs, hist_names, legends,
                                       y_limits, **kwargs):

        legend_position = retrieve_kw(kwargs, 'legend_position',
                                      (0.36, 0.20, 0.66, 0.36))
        legend_prefix = retrieve_kw(kwargs, 'legend_prefix',
                                    'Z#rightarrowee, ')
        legend_header = retrieve_kw(kwargs, 'legend_header', 'Trigger step')
        ylabel = retrieve_kw(kwargs, 'ylabel', 'Trigger Efficiency')
        title = retrieve_kw(kwargs, 'title', 'Trigger Efficiency')
        oname = retrieve_kw(kwargs, 'oname', 'plot_efficiencys')
        column = retrieve_kw(kwargs, 'column', 2)
        doRatio = retrieve_kw(kwargs, 'doRatio', False)
        canvas_size = retrieve_kw(kwargs, 'canvas_size', (1800, 1500))
        # FIXME: This must be disable for now, there is some problem into the xaxis scale
        # The top and bot axis must be match!
        tobject_collector = []
        ratio_size_as_fraction = 0.35

        from ROOT import TCanvas, TLegend, TProfile, TPad
        rows = int(round(len(hist_objs) / float(column)))
        canvas = TCanvas('canvas', 'canvas', canvas_size[0], canvas_size[1])
        canvas.Divide(rows, column)
        leg_holder = []
        for index, hist_str in enumerate(hist_names):
            hists = hist_objs[hist_str]
            pad = canvas.cd(index + 1)
            # Force disable if != of 2
            if len(hists) != 2:
                doRatio = False

            if doRatio:
                drawopt = 'pE1'
                pad.cd()
                top = TPad("pad_top", "This is the top pad", 0.0,
                           ratio_size_as_fraction, 1.0, 1.0)
                top.SetBottomMargin(0.0)
                top.SetBottomMargin(0.06 / float(top.GetHNDC()))
                #top.SetTopMargin   (0.04/float(top.GetHNDC()))
                top.SetRightMargin(0.05)
                top.SetLeftMargin(0.16)
                top.SetFillColor(0)
                top.Draw(drawopt)
                tobject_collector.append(top)
                pad.cd()
                bot = TPad("pad_bot", "This is the bottom pad", 0.0, 0.0, 1.0,
                           ratio_size_as_fraction)
                bot.SetBottomMargin(0.10 / float(bot.GetHNDC()))
                #bot.SetTopMargin   (0.02/float(bot.GetHNDC()))
                bot.SetTopMargin(0.0)
                bot.SetRightMargin(0.05)
                bot.SetLeftMargin(0.16)
                bot.SetFillColor(0)
                bot.Draw(drawopt)
                tobject_collector.append(bot)

            if type(legend_prefix) is not list:
                legend_prefix = [legend_prefix] * len(legends)

            if doRatio:
                top.cd()

            leg = TLegend(legend_position[0], legend_position[1],
                          legend_position[2], legend_position[3])

            from AtlasStyle import setLegend1, atlas_template
            setLegend1(leg)
            leg.SetHeader(legend_header)

            for i, eff in enumerate(hists):
                eff.SetLineColor(self._curve_color[i])
                eff.SetMarkerColor(self._curve_color[i])
                eff.SetMarkerStyle(self._marker_style[i])
                if type(eff) is TProfile: eff.SetStats(0)
                leg.AddEntry(eff, legend_prefix[i] + legends[i], 'p')
                if i is 0: eff.Draw()
                else: eff.Draw('same')

            leg.SetTextSize(0.03)
            leg.SetBorderSize(0)
            leg.Draw()

            if doRatio:
                top.Modified()
                top.Update

            pad.Modified()
            pad.Update()

            from ROOT import TProfile, TEfficiency, kFALSE
            xmin = 0
            xmax = 999

            if type(hists[0]) is TProfile:
                hists[0].GetYaxis().SetRangeUser(y_limits[index][0],
                                                 y_limits[index][1])
            elif type(hists[0]) is TEfficiency:
                hists[0].GetPaintedGraph().GetYaxis().SetRangeUser(
                    y_limits[index][0], y_limits[index][1])
                hists[0].GetPaintedGraph().GetYaxis().SetTitle('A')

                # Fix the X axis
                nbins = hists[0].GetTotalHistogram().GetNbinsX()
                xmin = hists[0].GetTotalHistogram().GetXaxis().GetBinLowEdge(1)
                xmax = hists[0].GetTotalHistogram().GetXaxis().GetBinLowEdge(
                    nbins + 1)
                hists[0].GetPaintedGraph().GetXaxis().SetLimits(xmin, xmax)
            else:
                hists[0].GetYaxis().SetRangeUser(y_limits[index][0],
                                                 y_limits[index][1])

            pad.Modified()
            pad.Update()
            tobject_collector.append(leg)

            if doRatio:
                atlas_template(top, **kwargs)
                top.Update()
                from ROOT import TH1
                divide = ""
                drawopt = 'pE1'
                bot.cd()
                ref = hists[0].GetPassedHistogram().Clone()
                h = hists[1].GetPassedHistogram().Clone()
                #ref = hists[0].Clone()
                #h = hists[1].Clone()
                ref.Sumw2()
                h.Sumw2()
                ref.Divide(hists[0].GetTotalHistogram().Clone())
                h.Divide(hists[1].GetTotalHistogram().Clone())
                #ratioplot = TEfficiency(h,ref)
                ratioplot = h.Clone()
                ratioplot.Sumw2()
                ratioplot.SetName(h.GetName() + '_ratio')
                ratioplot.Divide(h, ref, 1., 1., '')
                #ratioplot.Divide(ref)
                ratioplot.SetFillColor(0)
                ratioplot.SetFillStyle(0)
                ratioplot.SetMarkerColor(1)
                ratioplot.SetLineColor(kBlack)
                ratioplot.SetMarkerStyle(24)
                ratioplot.SetMarkerSize(1.2)
                ratioplot.GetYaxis().SetTitle('trigger / ref')
                ratioplot.GetYaxis().SetTitleSize(0.10)
                ratioplot.GetXaxis().SetTitleSize(0.10)
                ratioplot.GetXaxis().SetLabelSize(0.10)
                ratioplot.GetYaxis().SetLabelSize(0.10)
                ratioplot.GetYaxis().SetRangeUser(0.9, 1.07)
                ratioplot.Draw(drawopt)
                tobject_collector.append(ratioplot)
                #atlas_template(bot, **kwargs)
                from ROOT import TLine
                l1 = TLine(xmin, 1, xmax, 1)
                l1.SetLineColor(kRed)
                l1.SetLineStyle(2)
                l1.Draw()
                tobject_collector.append(l1)
                bot.Update()
            else:
                atlas_template(pad, **kwargs)
            pad.Update()

        canvas.SaveAs(oname + '.pdf')
示例#18
0
def makeTwoScalesGraph(file):
    print(file)
    ch1 = OPData.fromPath('../data/part3/%s' % file, 1)
    ch2 = OPData.fromPath('../data/part3/%s' % file, 2)

    print('make canvas + pad')
    c = TCanvas('c-%s' % file, '', 1280, 720)
    pad = TPad('pad-%s' % file, '', 0, 0, 1, 1)
    pad.Draw()
    pad.cd()

    print('frame')
    frame = pad.DrawFrame(0,
                          min(ch1.getY()) * 1.1, 0.051,
                          max(ch1.getY()) * 1.1)
    frame.SetXTitle('Zeit t / s')
    frame.GetXaxis().CenterTitle()
    frame.SetYTitle('Spannung Spule 2: U_{2} / V')
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetLabelColor(4)
    frame.GetYaxis().SetTitleColor(4)

    print('g1')
    g1 = ch1.makeGraph('g1-%s' % file)
    prepareGraph(g1)
    g1.Draw('PX')

    print('overlay')
    c.cd()
    overlay = TPad('overlay-%s' % file, '', 0, 0, 1, 1)
    overlay.SetFillStyle(4000)  # transparent
    overlay.SetFillColor(0)  # white
    overlay.SetFrameFillStyle(4000)  # transparent
    overlay.Draw()
    overlay.cd()

    print('g2')
    g2 = ch2.makeGraph('g2-%s' % file)
    prepareGraph(g2, 2)
    g2ymin = min(ch2.getY())
    xmin = pad.GetUxmin()
    xmax = pad.GetUxmax()
    ymin = 1.1 * g2ymin
    ymax = abs(ymin)
    if file == '07.tab':  # same scale like 06.tab
        ymin, ymax = -0.07128, 0.07128
    oframe = overlay.DrawFrame(xmin, ymin, xmax, ymax)
    oframe.GetXaxis().SetLabelOffset(99)
    oframe.GetYaxis().SetLabelOffset(99)
    oframe.GetYaxis().SetTickLength(0)
    g2.Draw('PX')

    print('axis')
    axis = TGaxis(xmax, ymin, xmax, ymax, ymin, ymax, 510, "+L")
    axis.SetTitle('Spannung Photodiode: U_{ph} / V')
    axis.CenterTitle()
    axis.SetTitleOffset(1.2)
    axis.Draw()

    print('print')
    c.Update()
    c.Print('../img/part3/%s.pdf' % file[:-4], 'pdf')
def plot_BDT(channel, var, massPoint, bin, low, high, ylabel, xlabel, save, nBtags = -1, setLog = False, finalcuts = False):

    if (channel == 'electron'):      
        cut = 'jet_0_pt_WprimeCalc >= 120 && jet_1_pt_WprimeCalc >= 40 && elec_1_pt_WprimeCalc > 32 && abs(elec_1_eta_WprimeCalc) < 2.5 && elec_1_RelIso_WprimeCalc < 0.1 && corr_met_WprimeCalc > 20' 
        #cut = 'jet_0_pt_WprimeCalc >= 100 && jet_1_pt_WprimeCalc >= 40 && elec_1_pt_WprimeCalc > 30 && abs(elec_1_eta_WprimeCalc) < 2.5 && elec_1_RelIso_WprimeCalc < 0.1 && corr_met_WprimeCalc > 35' 

    if (channel == 'muon'):      
        cut = 'jet_0_pt_WprimeCalc >= 120 && jet_1_pt_WprimeCalc >= 40 && muon_1_pt_WprimeCalc > 26 && abs(muon_1_eta_WprimeCalc) < 2.1 && muon_1_RelIso_WprimeCalc < 0.12 && corr_met_WprimeCalc > 20'
        #cut = 'jet_0_pt_WprimeCalc >= 100 && jet_1_pt_WprimeCalc >= 40 && muon_1_pt_WprimeCalc > 26 && abs(muon_1_eta_WprimeCalc) < 2.1 && muon_1_RelIso_WprimeCalc < 0.12 && corr_met_WprimeCalc > 35' 


    if finalcuts: cut+= '&& BestTop_LjetsTopoCalcNew > 130 && BestTop_LjetsTopoCalcNew < 210 &&  BestTop_Pt_LjetsTopoCalcNew > 75  && Jet1Jet2_Pt_LjetsTopoCalcNew > 100'   
    njets = ""

    if nBtags == -1:
        cutbtag = ''
        save = save     
    if nBtags == 0:
        cutbtag =  ' && ( (jet_0_tag_WprimeCalc + jet_1_tag_WprimeCalc + jet_2_tag_WprimeCalc + jet_3_tag_WprimeCalc + jet_4_tag_WprimeCalc + jet_5_tag_WprimeCalc + jet_6_tag_WprimeCalc + jet_7_tag_WprimeCalc + jet_8_tag_WprimeCalc + jet_9_tag_WprimeCalc) == 0 )'
        save = save + '_0bTags'
        njets = "N_{b tags} = 0"
    if nBtags == 1:
        cutbtag =  ' && ( (jet_0_tag_WprimeCalc + jet_1_tag_WprimeCalc) == 1)'
        save = save + '_1bTags'
        njets = "N_{b tags} = 1"
    if nBtags == 2:
        cutbtag =  ' && ( (jet_0_tag_WprimeCalc + jet_1_tag_WprimeCalc) >= 1 ) '
        save = save + '_GE1bTags'
        njets = "N_{b tags} #geq 1"


    cutwbb = ' && n_Bjets_WprimeCalc > 0' # Wb(b)
    cutwcc = ' && n_Bjets_WprimeCalc==0 && n_Cjets_WprimeCalc>0' # Wc(c)
    cutwjj = ' && n_Bjets_WprimeCalc==0 && n_Cjets_WprimeCalc==0' # W+light
    #cutwbb = ' ' # Wb(b)
    #cutwcc = ' ' # Wc(c)
    #cutwjj = ' ' # W+light
                                                                                                                   
    SFWjmu = 1.08*0.85
    SFWcmu = 1.06*0.92*1.66
    SFWbmu = 1.06*0.92*1.21
    #SFWjmu = 1.0
    #SFWcmu = 1.0
    #SFWbmu = 1.0

    WjjHist = TH1D('WjjHist', 'WjjHist', bin,low,high)
    WccHist = TH1D('WccHist', 'WccHist', bin,low,high)
    WbbHist = TH1D('WbbHist', 'WbbHist', bin,low,high)

    Variables = {}
    efficiency = {}
   
    BkgList = []

    for Type in Samples:

        #print channel,' ',Type

        if (Type.endswith('_el') and channel == 'muon'): continue
        if (Type.endswith('_mu') and channel == 'electron'): continue
        if (not Type.startswith(massPoint) ): continue

        Variables[Type] = TH1D(Type+var+channel, Type+var+channel, bin, low, high)
        histName = Type+var+channel
     
        if (channel == 'electron'): chan = '_el'
        if (channel == 'muon'): chan = '_mu'

        if (channel == 'electron'): weight = 'weight_PU_ABC_PileUpCalc*weight_ElectronEff_WprimeCalc'
        if (channel == 'muon'): weight = 'weight_PU_ABC_PileUpCalc*weight_MuonEff_WprimeCalc'
        
        if ((not Type == massPoint+massPoint+chan) and (not Type == massPoint+'_data'+chan)): BkgList.extend([Type])

        if Type.endswith('wjets'+chan):
            #print 'Filling ',Type
            Trees[Type].Draw(var + " >> " + histName, "("+weight+")*(" + str(SFWjmu) + ")*(" + cut + cutbtag + cutwjj + ")", 'goff')
            Trees[Type].Draw(var + " >> " + "WbbHist","("+weight+")*(" + str(SFWbmu) + ")*(" + cut + cutbtag + cutwbb + ")", 'goff')
            Trees[Type].Draw(var + " >> " + "WccHist","("+weight+")*(" + str(SFWcmu) + ")*(" + cut + cutbtag + cutwcc + ")", 'goff')
            #print 'Raw Wjj ',Variables['WJets'].Integral()
            Variables[Type].Add(WbbHist)
            #print 'Raw Wjj + Wbb ',Variables['WJets'].Integral()
            Variables[Type].Add(WccHist) 
            #print 'Raw Wjj + Wbb + Wcc',Variables['WJets'].Integral()

        elif Type.endswith('data'+chan):
            #print 'Filling ',Type
            Trees[Type].Draw(var + " >> " + histName, "(" + cut + cutbtag + ")", 'goff')
        else:
            #print 'Filling ',Type
            Trees[Type].Draw(var + " >> " + histName, "("+weight+")*(" + cut + cutbtag + ")", 'goff')
            
        if (not Type.endswith('data'+chan)):

            SF = 1.0
            if (channel == 'electron'):
                lumi = lumi_el
            if (channel == 'muon'):
                lumi = lumi_mu

            if (Type.startswith(massPoint+'_'+massPoint)): SF *= 20
            #print 'EVENTS Before Scaling FOR ',Type,' = ',Variables[Type].Integral()
            #print 'Pre Events before scaling for ',Type,' = ',VariablesPre[Type].Integral()
            #print str(SF),' ',str(lumi),' ',str(xsec_norm[Type]),' ',str(Nevents[Type])

            if Variables[Type].Integral() != 0:
                #print Type,' Lumi scaling: ',str(SF*lumi*xsec[Type]/Nevents[Type])
                Variables[Type].Scale ( SF*Yield[Type]/Variables[Type].Integral() ) 
                efficiency[Type] = Variables[Type].Integral()/Nevents[Type]
            else:
                efficiency[Type] = 0

    
    Variables[massPoint+'_ttbar'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_s'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_bs'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_t'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_bt'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_tw'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_btw'+chan].SetFillColor(ROOT.kRed-7)

    Variables[massPoint+'_s'+chan].SetLineColor(ROOT.kRed-7)
    Variables[massPoint+'_bs'+chan].SetLineColor(ROOT.kRed-7)
    Variables[massPoint+'_t'+chan].SetLineColor(ROOT.kRed-7)
    Variables[massPoint+'_bt'+chan].SetLineColor(ROOT.kRed-7)
    Variables[massPoint+'_tw'+chan].SetLineColor(ROOT.kRed-7)
    Variables[massPoint+'_btw'+chan].SetLineColor(ROOT.kRed-7)

    Variables[massPoint+'_wjets'+chan].SetFillColor(ROOT.kGreen-3)
    Variables[massPoint+'_zjets'+chan].SetFillColor(ROOT.kGreen-3)
    Variables[massPoint+'_ww'+chan].SetFillColor(ROOT.kGreen-3)

    Variables[massPoint+'_zjets'+chan].SetLineColor(ROOT.kGreen-3)
    Variables[massPoint+'_ww'+chan].SetLineColor(ROOT.kGreen-3)
    
    Variables[massPoint+'_ttbar'+chan].SetLineWidth(2)
    Variables[massPoint+'_wjets'+chan].SetLineWidth(2)

    Variables[massPoint+'_'+massPoint+chan].SetLineColor(1)
    Variables[massPoint+'_'+massPoint+chan].SetLineWidth(2)
    Variables[massPoint+'_'+massPoint+chan].SetLineStyle(6)

    stack = THStack('a', 'a')
    added = TH1D('a', 'a',bin,low,high)
    topadded  = TH1D('topadded', 'topadded', bin, low, high)
    wjetsadded = TH1D('wjetsadded', 'wjetsadded',bin,low,high)

    wjetsadded = Variables[massPoint+'_wjets'+chan].Clone()
    wjetsadded.Add(Variables[massPoint+'_ww'+chan])
    wjetsadded.Add(Variables[massPoint+'_zjets'+chan])

    topadded = Variables[massPoint+'_ttbar'+chan].Clone()
    topadded.Add(Variables[massPoint+'_s'+chan])
    topadded.Add(Variables[massPoint+'_bs'+chan])
    topadded.Add(Variables[massPoint+'_t'+chan])
    topadded.Add(Variables[massPoint+'_bt'+chan])
    topadded.Add(Variables[massPoint+'_tw'+chan])
    topadded.Add(Variables[massPoint+'_btw'+chan])

    wjetsadded.SetFillColor(ROOT.kGreen-3)
    wjetsadded.SetLineColor(1)
    wjetsadded.SetLineWidth(2)
    topadded.SetFillColor(ROOT.kRed-7)
    topadded.SetLineColor(1)
    topadded.SetLineWidth(2)

    stack.Add(wjetsadded)
    stack.Add(topadded)
    added.Add(wjetsadded)  
    added.Add(topadded)

    print 'Data: ',Variables[massPoint+'_data'+chan].Integral(),' Background: ',added.Integral(),' Data/Background: ',Variables[massPoint+'_data'+chan].Integral()/added.Integral()

    lumi_error = 0.022
    ttbar_error = 0.15
    wjets_error = 0.20
    other_error = 0.20

    uncert_list = []
    lumiband = added.Clone();
    
    for hbin in range(0,lumiband.GetNbinsX()+1): 

        uncert_lumi = 0 
        uncert_xsec = 0
        uncert_stat = 0
 
        for i in BkgList:

            error = 0
             
            if i in xsec.keys(): 
                if (i.startswith(massPoint+'_t') or i.startswith(massPoint+'_b') or i.startswith(massPoint+'_s')): 
                    error = ttbar_error
                    uncert_lumi += (efficiency[i]*xsec[i])**2 
                    uncert_xsec += (Variables[i].GetBinContent(hbin+1)*error)**2
                    uncert_stat += Variables[i].GetBinError(hbin+1)**2
                elif (i.startswith(massPoint+'_w') or i.startswith(massPoint+'_z')):
                    error = wjets_error
                    uncert_lumi += (efficiency[i]*xsec[i])**2 
                    uncert_xsec += (Variables[i].GetBinContent(hbin+1)*error)**2         
                    uncert_stat += Variables[i].GetBinError(hbin+1)**2

        #print 'uncert_lumi: ',uncert_lumi,' uncert_xsec ',uncert_xsec,' uncert_stat ',uncert_stat
        uncert = sqrt( (lumi_error**2)*uncert_lumi + uncert_xsec + uncert_stat )

        if lumiband.GetBinContent(hbin+1) != 0:
            dummy = 1.0
            #print lumiband.GetBinContent(hbin+1),'+/-',uncert,'(',100*uncert/lumiband.GetBinContent(hbin+1),'%)'
        lumiband.SetBinError(hbin+1,uncert);
        added.SetBinError(hbin+1,uncert);
        uncert_list . append(uncert)
    
    #gStyle.SetHatchesSpacing(2.0);
    gStyle.SetHatchesLineWidth(1);
            
    lumiband.SetFillStyle(3344);
    #lumiband.SetFillStyle(3001);
    lumiband.SetFillColor(1);
      
    legend = TLegend(.60,.70,.90,.90)
    legend . AddEntry( Variables[massPoint+'_data'+chan], 'Data' , "lp")
    legend . AddEntry( Variables[massPoint+'_ttbar'+chan], "t#bar{t} + Single-Top", "f")
    legend . AddEntry( Variables[massPoint+'_wjets'+chan], "W#rightarrowl#nu + Z/#gamma*#rightarrowl^{+}l^{-} + VV" , "f")
 
    if (massPoint.endswith('R')): coupling = 'R'
    if (massPoint.endswith('L')): coupling = 'L'
    if (massPoint.endswith('RL')): coupling = 'RL'

    massval = copy.copy(massPoint)
    massval = massval.lstrip('wp')
    massval = massval.rstrip('00'+coupling)
    if (len(massval)==1): massval = '0'+massval
    massval = massval[0]+'.'+massval[1]

    legend . AddEntry( Variables[massPoint+'_'+massPoint+chan], "W'_{"+coupling+"} x 20, m="+massval+" TeV", "l")
    legend . AddEntry( lumiband , "Uncertainty" , "f")

    c4 = TCanvas("c4","c4", 1000, 800)
    
    c4.SetBottomMargin(0.3)
    c4.SetRightMargin(0.06)
    stack.SetMaximum( 2*stack.GetMaximum() ) 
    if setLog:
        c4.SetLogy()
        stack.SetMaximum( stack.GetMaximum()  +  30*stack.GetMaximum() ) 

    stack.SetMinimum(0.1 )
    #stack.SetMarkerSize(0)
    stack.Draw("") 
    stack.GetYaxis().CenterTitle() 
    stack.GetYaxis().SetTitle(ylabel)
    stack.GetXaxis().SetLabelSize(0)
    #stack.GetXaxis().SetTitle(xlabel)
    lumiband.Draw("samee2")
    #lumiband.Draw("esame")
    
    legend.SetShadowColor(0);
    legend.SetFillColor(0);
    legend.SetLineColor(0);
    legend.Draw("same")    

    if (Variables[massPoint+'_data'+chan].GetBinContent(bin+1)>0):
        print "Overflow for ",massPoint+"_"+channel," data "
    Variables[massPoint+'_data'+chan].SetMarkerStyle(20)
    Variables[massPoint+'_data'+chan].Draw('SAMES:E1')
 
    Variables[massPoint+'_'+massPoint+chan].Draw("same")

    latex2 = TLatex()
    latex2.SetNDC()
    latex2.SetTextSize(0.04)
    latex2.SetTextAlign(31) # align right
    if channel == ('electron'): 
        latex2.DrawLatex(0.87, 0.95, "CMS Preliminary, "+lumiPlot_el+" fb^{-1} at #sqrt{s} = 8 TeV");
    if channel == ('muon'): 
        latex2.DrawLatex(0.87, 0.95, "CMS Preliminary, "+lumiPlot_mu+" fb^{-1} at #sqrt{s} = 8 TeV");

    latex3 = TLatex()
    latex3.SetNDC()
    latex3.SetTextSize(0.04)
    latex3.SetTextAlign(31) # align right

    if (channel == 'electron'):
        latex3.DrawLatex(0.47, 0.85, "e+jets " + njets);   
    if (channel == 'muon'):
        latex3.DrawLatex(0.47, 0.85, "#mu+jets " + njets);   
 
    latex4 = TLatex()
    latex4.SetNDC()
    latex4.SetTextSize(0.03)
    latex4.SetTextAlign(22) # align right
    latex4.SetTextAngle(90) # align right
    #latex4.DrawLatex(0.905, 0.56, "overflow")
    
    Pull  = TH1D('Pull', 'Pull', bin, low, high)  
    Pull = Variables[massPoint+'_data'+chan].Clone();
    Pull.Add(added,-1)
    Pull.Divide(added)

    for i in range(bin):
        i += 1
        #print i+1,' ',added.GetBinContent(i+1)
        if (Pull.GetBinContent(i+1) != 0 and Pull.GetBinError(i+1) != 0):
            Pull.SetBinContent(i+1,Pull.GetBinContent(i+1)/Pull.GetBinError(i+1))
        else: Pull.SetBinContent(i+1,0)

    pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0)
    pad.SetTopMargin(0.7)
    pad.SetFillColor(0)
    pad.SetGridy(1)
    pad.SetFillStyle(0)
    pad.Draw()
    pad.cd(0)
    pad.SetRightMargin(0.06)

    Pull.SetMarkerStyle(20)
    Pull.SetMaximum(3.0 )
    Pull.SetMinimum(-3.0)
    Pull.SetFillColor(2)
    Pull.GetXaxis().SetTitle(xlabel)
    Pull.GetYaxis().SetTitleSize(0.04)
    Pull.GetYaxis().SetTitle('#sigma(Data-MC)')
    Pull.SetMarkerSize(0.7)
    Pull.GetYaxis().SetNdivisions(5);
    Pull.Draw("HIST")
    
    c4.SaveAs('Wprime_Plots/StackedHisto_' + save + '.pdf')
      
    del c4
    #del pad
    del stack
    del Variables
示例#20
0
    frame1 = x.frame()
    frame2 = x.frame()
    roohistBkg.plotOn(frame1, RooFit.Binning(NBINS))
    background.plotOn(frame1)
    hpull = frame1.pullHist()
    frame2.addPlotable(hpull, 'p')

    frame1.SetMinimum(0.5)
    frame1.GetXaxis().SetTitle('')
    frame1.GetXaxis().SetLabelSize(0.0)
    frame1.GetYaxis().SetTickLength(0.06)
    frame1.Draw()

    pad = TPad('pad', 'pad', 0., 0., 1., 1.)
    pad.SetTopMargin(0.6)
    pad.SetFillColor(0)
    pad.SetFillStyle(0)
    pad.Draw()
    pad.cd(0)
    frame2.SetMinimum(-5)
    frame2.SetMaximum(5)
    frame2.GetYaxis().SetNdivisions(505)
    frame2.GetXaxis().SetTitleOffset(0.9)
    frame2.GetYaxis().SetTitleOffset(0.8)
    frame2.GetYaxis().SetTickLength(0.06)
    frame2.GetYaxis().SetTitleSize(0.05)
    frame2.GetYaxis().SetLabelSize(0.03)
    frame2.GetYaxis().SetTitle('(Data-Fit)/Error')
    frame2.GetXaxis().SetTitle('m_{jj} (GeV)')
    frame2.Draw()
示例#21
0
class RatioPad:
   REFERENCE_IS_DENOMINATOR = 0
   REFERENCE_IS_NUMERATOR = 1
   def __init__(self): 
      # reference plot: all other plots will be plotted as a ratio to this plot
      self.reference_plot = None

      # list of other plots, which will be calculated as a ratio with the reference
      self.plots = []

   def AddPlot(self,plot,draw_options='',legend_label=None,
                    legend_draw_options='lp',is_reference=False):
      clone = plot.Clone(plot.GetName() + '_clone')
      clone.SetDirectory(0)
      if is_reference:
         self.reference_plot = Plot(clone,draw_options,legend_label,legend_draw_options)
      else:
         self.plots.append(Plot(clone,draw_options,legend_label,legend_draw_options))

   def Draw(self,
            pad_name             = 'bottom_pad',
            pad_title            = 'Bottom Pad',
            pad_x1               = 0,
            pad_y1               = 0,
            pad_x2               = 1,
            pad_y2               = 1,
            pad_border_size      = 1,
            pad_ratio_order      = REFERENCE_IS_DENOMINATOR,
            pad_bottom_margin    = 0,
            pad_top_margin       = 0,
            pad_left_margin      = 0,
            pad_right_margin     = 0,
            yaxis_min            = 0.9,
            yaxis_max            = 1.1,
            y_ndiv               = None,
            y_title              = None,
            ratio_factor         = 2,
           ):
      # create the pad
      self.pad = TPad(pad_name,
                      pad_title,
                      pad_x1,
                      pad_y1,
                      pad_x2,
                      pad_y2,
                      pad_border_size,
                      0
                     )
      self.pad.SetMargin(pad_left_margin,pad_right_margin,pad_bottom_margin,pad_top_margin)
      self.pad.SetFillColor(0)
      self.pad.Draw()
      self.pad.cd()
      
      # create ratio plot for reference
      self.reference_plot.CreateRatio(self.reference_plot,pad_ratio_order)
      # the ratio plot will be plotted first so it determines the axes
      self.reference_plot.ratio.SetMaximum(yaxis_max)
      self.reference_plot.ratio.SetMinimum(yaxis_min)
      # here I setup the ratio to show up 
      self.reference_plot.ratio.GetXaxis().SetLabelSize(self.reference_plot.ratio.GetXaxis().GetLabelSize()*ratio_factor)
      self.reference_plot.ratio.GetYaxis().SetLabelSize(self.reference_plot.ratio.GetYaxis().GetLabelSize()*ratio_factor)
      self.reference_plot.ratio.GetXaxis().SetTitleSize(self.reference_plot.ratio.GetXaxis().GetTitleSize()*ratio_factor)
      self.reference_plot.ratio.GetYaxis().SetTitleSize(self.reference_plot.ratio.GetYaxis().GetTitleSize()*ratio_factor)

      if y_ndiv is not None:
         self.reference_plot.ratio.GetYaxis().SetNdivisions(y_ndiv)
      if y_title is not None:
         self.reference_plot.ratio.GetYaxis().SetTitle(y_title)

      self.reference_plot.DrawRatio()

      for plot in self.plots:
         plot.CreateRatio(self.reference_plot,pad_ratio_order)
         plot.DrawRatio(same=True)
示例#22
0
    def __plot_quadrant_template2(self, h_oo, h_xo, h_ox, h_xx, alias, xlabel,
                                  plotname, doLogY):

        from TrigEgammaDevelopments.plots import AutoFixAxes
        from TrigEgammaDevelopments.helper.util import setBoxes
        from ROOT import TCanvas, gStyle, TLegend, kRed, kBlue, kGreen, kGray, kBlack, TLine, TPad, TLatex
        from TrigEgammaDevelopments.plots.AtlasStyle import AtlasStyle, atlas_template

        ratio_size_as_fraction = 0.35

        # Internal method
        def sortHistograms(hists):
            nevents = [o.GetEntries() for o in hists]
            from operator import itemgetter
            hist_sorted_index = sorted(enumerate(nevents), key=itemgetter(1))
            hist_sorted = list()
            for index in hist_sorted_index:
                hist_sorted.append(hists[index[0]])
            hist_sorted.reverse()
            return hist_sorted

        h_agree = h_xx + h_oo
        h_disagree = h_ox + h_xo
        hsum = h_agree + h_disagree

        gStyle.SetOptStat(111111)
        canvas = TCanvas('canvas', 'canvas', 2500, 1600)
        drawopt = 'pE1'
        canvas.cd()
        top = TPad("pad_top", "This is the top pad", 0.0,
                   ratio_size_as_fraction, 1.0, 1.0)
        top.SetBottomMargin(0.0)
        top.SetBottomMargin(0.06 / float(top.GetHNDC()))
        #top.SetTopMargin   (0.04/float(top.GetHNDC()))
        top.SetRightMargin(0.05)
        top.SetLeftMargin(0.16)
        top.SetFillColor(0)
        top.Draw(drawopt)

        canvas.cd()
        bot = TPad("pad_bot", "This is the bottom pad", 0.0, 0.0, 1.0,
                   ratio_size_as_fraction)
        bot.SetBottomMargin(0.10 / float(bot.GetHNDC()))
        #bot.SetTopMargin   (0.02/float(bot.GetHNDC()))
        bot.SetTopMargin(0.0)
        bot.SetRightMargin(0.05)
        bot.SetLeftMargin(0.16)
        bot.SetFillColor(0)
        bot.Draw(drawopt)

        top.cd()

        h_agree.SetLineWidth(1)
        h_agree.SetLineColor(kBlack)
        h_agree.SetMarkerColor(kBlack)

        h_disagree.SetLineWidth(1)
        h_disagree.SetLineColor(kRed)
        h_disagree.SetMarkerColor(kRed)

        h_agree.SetName('Agreement')
        h_disagree.SetName('Disagreement')

        h_agree.SetStats(1)
        h_disagree.SetStats(1)
        # top
        h1 = sortHistograms([h_agree, h_disagree])
        # bot
        h2 = sortHistograms([h_agree.Clone(), h_disagree.Clone()])

        h1[0].GetXaxis().SetTitle('')
        h1[0].GetYaxis().SetTitle('Counts')

        #h1[0].GetYaxis().SetTitleOffset(0.5)
        #h1[0].GetYaxis().SetLabelSize(0.10)
        #h1[0].GetYaxis().SetTitleSize(0.10)

        #h1[0].GetXaxis().SetLabelSize(0.10)

        h1[0].Draw()
        for i in range(1, len(h1)):
            h1[i].Draw('sames')

        top.Update()
        setBoxes(top, h1)
        if doLogY:
            top.SetLogy()
            AutoFixAxes(top, False, False, 9000)
        else:
            AutoFixAxes(top, False, False, 2)

        bot.cd()
        if doLogY:
            bot.SetLogy()

        hsum.Sumw2()
        for h in h2:
            h.SetStats(0)
            h.Sumw2()
            h.Divide(h, hsum, 1., 1.)

        h2[0].GetYaxis().SetTitle('ratio')
        h2[0].GetXaxis().SetTitle(xlabel)
        h2[0].GetYaxis().SetTitleOffset(0.5)
        h2[0].GetYaxis().SetLabelSize(0.10)
        h2[0].GetYaxis().SetTitleSize(0.10)
        h2[0].GetXaxis().SetLabelSize(0.10)
        h2[0].GetXaxis().SetTitleSize(0.10)

        if not doLogY:
            h2[0].GetYaxis().SetRangeUser(0, 1.05)

        h2[0].Draw('ep1')
        for i in range(1, len(h2)):
            h2[i].Draw('sames')

        if doLogY:
            AutoFixAxes(bot, False, False, 1.1)

        # Loop over histograms
        canvas.SaveAs(plotname)
    def sobWeightedPlot(self,
                        fileName,
                        datasetName,
                        channel,
                        cat,
                        log,
                        mass,
                        tanb,
                        blind,
                        sob=False):

        #        print 'yuta', channel, cat

        c = TCanvas(fileName, '', 600, 600)
        c.cd()
        if log: c.SetLogy(1)

        f = self.openTFile('Plot_' + fileName + '.root')

        isEMSM = fileName.find('SM') != -1 and fileName.find('em') != -1
        isETSM = fileName.find('SM') != -1 and fileName.find('et') != -1

        samples = ['ggH', 'Ztt', 'signal', 'data_obs', 'ttbar', 'EWK', 'Fakes']

        if isEMSM:
            samples.append('ggH_hww')
        if isETSM:
            samples.append('Zee')

        dataGraph = self.tfileGet(f, 'Graph_from_data_obs')

        histDict = {}
        for sample in samples:
            histDict[sample] = self.tfileGet(f, sample)
            #            print 'check :', sample, histDict[sample].GetSumOfWeights()
            if not histDict[sample]:
                print 'Missing histogram', sample, 'in file', 'Plot_' + fileName + '.root'

# original for plots
        xminInset = 60  # 0
        xmaxInset = 179  # 340 (for full range)

        # all range
        #        xminInset = 0 # 0
        #        xmaxInset = 350 # 340 (for full range)

        #        xminInset = 40 # 0
        #        xmaxInset = 200 # 340 (for full range)
        #        xminInset = 120 # 0
        #        xmaxInset = 251 # 340 (for full range)

        if tanb > 0:
            xminInset = mass - 100
            xmaxInset = mass + 100

        if sob:
            xminInset = 0.4
            xmaxInset = 0.7

        ztt = histDict['Ztt']
        ggH = histDict['ggH']
        data = histDict['data_obs']

        # This is to fix a weird plotting bug
        if sob:
            new_data = TH1F('new_data', '', ggH.GetNbinsX(), 0., 0.7)
            for i in range(1, new_data.GetNbinsX() + 1):
                new_data.SetBinContent(i, data.GetBinContent(i))
                # print data.GetBinContent(i)
            data = new_data

        ggH_hww = 0
        zee = 0

        signal = histDict['signal']
        if isEMSM:
            ggH_hww = histDict['ggH_hww']
        if isETSM:
            print 'retrieve Zee'
            zee = histDict['Zee']
        tt = histDict['ttbar']
        ewk = histDict['EWK']
        fakes = histDict['Fakes']

        ztt.GetYaxis().SetRangeUser(0., 1.3 * self.findMaxY(data, 0))
        if log:
            ztt.GetYaxis().SetRangeUser(0.001, 50. * self.findMaxY(data, 0))

        ztt.GetXaxis().SetTitle('#bf{m_{#tau#tau}  [GeV]}')
        ztt.GetYaxis().SetTitle('#bf{S/B Weighted dN/dm_{#tau#tau} [1/GeV]}')
        if tanb > 0. and not log:
            ztt.GetXaxis().SetRangeUser(0., mass + 200.)

        if sob:
            ztt.GetXaxis().SetTitle('S/(S+B)')
            ztt.GetYaxis().SetTitle('Events')

        ztt.SetTitleOffset(1.3, 'Y')
        ztt.SetTitleOffset(1., 'X')
        ztt.GetYaxis().SetNdivisions(505)
        ztt.SetNdivisions(505)

        for b in range(0, signal.GetNbinsX() + 2):
            if signal.GetBinCenter(
                    b) < xminInset or xmaxInset < signal.GetBinCenter(b):
                signal.SetBinContent(b, 0.)
                signal.SetBinError(b, 0.)

        signal.SetName('sig')
        signal.SetFillStyle(3353)  # 1001=solid , 3004,3005=diagonal
        signal.SetFillColor(2)
        signal.SetLineColor(2)
        signal.SetLineStyle(1)
        signal.SetLineWidth(0)

        ggH.SetBinContent(0, 0)  # remove red line on top of y axis in plot
        ggH.SetBinContent(ggH.GetNbinsX() + 1, 0)
        ggH.SetBinError(0, 0)
        ggH.SetBinError(ggH.GetNbinsX() + 1, 0)
        ggH.SetName('ggH')
        ggH.SetFillStyle(3353)  # 1001=solid , 3004,3005=diagonal
        ggH.SetFillColor(2)
        ggH.SetLineColor(2)
        ggH.SetLineStyle(1)
        ggH.SetLineWidth(0)

        if isEMSM:
            errorBand = TH1F(ggH_hww)
        else:
            errorBand = TH1F(ztt)
        errorBand.SetName("errorBand")

        errorBand.SetMarkerSize(0)
        errorBand.SetFillColor(1)
        errorBand.SetFillStyle(3013)
        errorBand.SetLineWidth(1)

        legend = TLegend()
        mssmLabel = ''
        if tanb > 0:
            mssmLabel = "tan#beta={tanb}".format(tanb=tanb)
        higgsLabel = "H(125 GeV)#rightarrow#tau#tau"
        if tanb > 0:
            higgsLabel = "H(125 GeV)#rightarrow#tau#tau"

        legend.SetFillStyle(0)
        legend.SetFillColor(0)
        legend.SetBorderSize(0)
        legend.AddEntry(ggH, higgsLabel, "F")
        if tanb > 0:
            legend.AddEntry(TObject(0), mssmLabel, "")
        legend.AddEntry(data, "observed", "LP")
        if isEMSM:
            legend.AddEntry(ggH_hww, "H(125 GeV)#rightarrowWW", "F")
        legend.AddEntry(ztt, "Z#rightarrow#tau#tau", "F")
        legend.AddEntry(tt, "t#bar{t}", "F")
        if isETSM:
            legend.AddEntry(zee, "Z#rightarrowee", "F")
        legend.AddEntry(ewk, "electroweak", "F")
        legend.AddEntry(fakes, "QCD", "F")

        legend.SetX1NDC(0.63)
        legend.SetX2NDC(1.05)
        legend.SetY1NDC(0.25)
        legend.SetY2NDC(0.46)
        if log:
            legend.SetX1NDC(0.18)
            legend.SetX2NDC(0.60)
            legend.SetY1NDC(0.17)
            legend.SetY2NDC(0.38)

        legend.SetTextSize(.028)
        legend.SetTextAlign(12)

        if isEMSM:
            dataDiff = self.diffPlot(data, ggH_hww, 1)
            dataDiffGraph = self.diffGraph(dataGraph, ggH_hww, 1)
            errBand = self.getErrorBand(ggH_hww)
        else:
            dataDiff = self.diffPlot(data, ztt, 1)
            dataDiffGraph = self.diffGraph(dataGraph, ztt, 1)
            errBand = self.getErrorBand(ztt)

        errBand.SetFillStyle(
            3013
        )  # 1001=solid , 3004,3005=diagonal, 3013=hatched official for H.tau tau
        errBand.SetFillColor(1)
        errBand.SetLineStyle(1)
        errBand.SetLineColor(1)
        errBand.SetLineWidth(1)

        errBandFrame = TH1F(
            'errBandFrame', '',
            int((xmaxInset - xminInset) / dataDiff.GetBinWidth(1)), xminInset,
            xmaxInset)

        errBandFrame.GetYaxis().SetTitle("")
        errBandFrame.GetYaxis().SetRangeUser(
            -1.1 * self.findMinY(dataDiff, blind, 0, xminInset, xmaxInset),
            2.0 * self.findMaxY(dataDiff, blind, 0, xminInset, xmaxInset))
        #        errBandFrame.GetYaxis().SetRangeUser(-1.*self.findMinY(dataDiff,blind,0,xminInset,xmaxInset),1.1*self.findMaxY(dataDiff,blind,0,xminInset,xmaxInset)) # good !
        #        errBandFrame.GetYaxis().SetRangeUser(-0.2*self.findMinY(dataDiff,blind,0,xminInset,xmaxInset),0.5*self.findMaxY(dataDiff,blind,0,xminInset,xmaxInset))

        print 'Yuta', channel, cat
        if (channel == 'e#tau_{h}' and cat == 'vbf') or (channel == 'e#tau_{h}'
                                                         and cat == ''):
            print 'enter'
            errBandFrame.GetYaxis().SetRangeUser(
                -2. * self.findMinY(dataDiff, blind, 0, xminInset, xmaxInset),
                2.0 * self.findMaxY(dataDiff, blind, 0, xminInset, xmaxInset))
        errBandFrame.GetYaxis().SetNdivisions(5)
        errBandFrame.GetYaxis().SetLabelSize(0.06)
        errBandFrame.GetXaxis().SetTitle("#bf{m_{#tau#tau} [GeV]}    ")
        errBandFrame.GetXaxis().SetTitleColor(kBlack)
        errBandFrame.GetXaxis().SetTitleSize(0.07)
        errBandFrame.GetXaxis().SetTitleOffset(0.85)
        errBandFrame.GetXaxis().SetLabelSize(0.06)
        errBandFrame.GetXaxis().SetNdivisions(506)
        #        errBandFrame.SetNdivisions(505)

        legendDiff = TLegend()
        legendDiff.SetFillStyle(0)
        legendDiff.SetFillColor(0)
        legendDiff.SetBorderSize(0)
        legendDiff.AddEntry(signal, higgsLabel, "F")

        if tanb > 0:
            legendDiff.AddEntry(TObject(0), mssmLabel,
                                '')  # That might not work in python
#        legendDiff.AddEntry(dataDiff,"Data - Background","LP")
        legendDiff.AddEntry(dataDiffGraph, "Data - Background", "LEP")
        legendDiff.AddEntry(errBand, "Bkg. Uncertainty", "F")
        legendDiff.SetX1NDC(0.45)
        legendDiff.SetX2NDC(0.88)
        legendDiff.SetY1NDC(0.67)
        legendDiff.SetY2NDC(0.88)
        if dataDiff.GetBinContent(dataDiff.FindBin(mass)) < 0.:
            legendDiff.SetX1NDC(0.45)
            legendDiff.SetX2NDC(0.88)
            legendDiff.SetY1NDC(0.24)
            legendDiff.SetY2NDC(0.45)

        legendDiff.SetTextSize(.045)
        legendDiff.SetTextAlign(12)

        padBack = TPad(
            "padBack", "padBack", 0.57, 0.58, 0.975,
            0.956)  # TPad must be created after TCanvas otherwise ROOT crashes
        padBack.SetFillColor(0)
        pad = TPad(
            "diff", "diff", 0.45, 0.5, 0.9765,
            0.957)  # TPad must be created after TCanvas otherwise ROOT crashes
        pad.cd()
        pad.SetFillColor(0)
        pad.SetFillStyle(0)
        errBandFrame.Draw()
        errBand.Draw("e2lsame")
        signal.Draw("histsame")
        line = TLine()
        line.DrawLine(xminInset, 0, xmaxInset, 0)
        # dataDiff.Draw("pe same")

        if blind == False:
            self.HideBin(dataDiffGraph)

        dataDiffGraph.SetMarkerSize(0.5)
        dataDiffGraph.Draw('pe same')

        for ibin in range(0, dataDiffGraph.GetN()):
            x = Double(0.)
            y = Double(0.)
            dataDiffGraph.GetPoint(ibin, x, y)

            print 'Yuta_bin=', ibin, 'x=', x, 'y=', y, dataDiffGraph.GetErrorYhigh(
                ibin), dataDiffGraph.GetErrorYlow(ibin)
            print 'Yuta_error=', ibin, errBand.GetXaxis().GetBinCenter(
                ibin + 1), errBand.GetBinError(ibin + 1)

        legendDiff.Draw()
        pad.RedrawAxis()

        c.cd()
        ztt.Draw("hist")
        ggH.Draw("hist same")
        if isEMSM:
            ggH_hww.Draw("hist same")
        ztt.Draw("hist same")
        errorBand.Draw("e2 same")
        tt.Draw("hist same")
        if isETSM:
            zee.Draw("hist same")
        ewk.Draw("hist same")
        fakes.Draw("hist same")

        # data.Draw("pe same")
        dataGraph.SetMarkerSize(1)
        dataGraph.Draw('PE same')

        if blind == False:
            self.HideBin(dataGraph)

        print '#####', data.Integral(), data.GetBinContent(1)
        legend.Draw()
        c.RedrawAxis()
        padBack.Draw()  # clear the background axe
        pad.Draw()
        if log: c.SetLogy(1)
        self.CMSPrelim(c, datasetName, channel, cat)

        savepath = 'figure/Plot_' + fileName
        if cat == '':
            savepath = savepath + '.pdf'
        else:
            savepath = savepath + '_' + cat + '.pdf'


#        c.Print('figure/Plot_'+fileName+".eps")
#        c.Print('figure/Plot_'+fileName+".png")
#        c.Print('figure/Plot_'+fileName+".pdf")
        c.Print(savepath)

        c.Close()
示例#24
0
def PlotSig(templates, sideband_templates):
    print "Plotting Signal Template"
    data = templates["Data"].histo.Clone()
    gjets = templates["GJets"].histo.Clone()
    sideband = sideband_templates["Sideband"].histo.Clone()
    full = gjets.Clone()
    full.Add(sideband)

    c = TCanvas("c", "canvas", 800, 800)
    gStyle.SetOptStat(0)
    gStyle.SetLegendBorderSize(0)
    # c.SetLeftMargin(0.15);
    # c.SetLogy();
    #c.cd();

    pad1 = TPad("pad1", "pad1", 0.01, 0.25, 0.99, 0.99)
    pad1.SetBottomMargin(0.)
    pad1.Draw()
    pad1.cd()
    pad1.SetLogy()
    pad1.SetFillColor(0)
    pad1.SetFrameBorderMode(0)
    pad1.SetBorderMode(0)

    temp_style(gjets, kGreen + 2)
    temp_style(sideband, kRed)
    temp_style(full, kBlue + 2)
    DataStyle(data)

    leg = getLegend(xmax=0.7, ymin=0.55, ymax=0.75)

    gjets.Draw("hist")

    gjets.SetTitle("")
    gjets.GetYaxis().SetTitle("Events")

    if templates.variable.xaxis_title == "":
        templates.variable.xaxis_title = next(
            (vartitle for var, vartitle in xaxismap.items()
             if var in templates.variable.variable), "")
    gjets.GetXaxis().SetTitle(templates.variable.xaxis_title)

    sideband.Draw("hist same")
    full.Draw("hist same")
    data.Draw("pex0 same")
    hslist = [data, gjets, sideband]

    leg.AddEntry(data, "Data", "lp")
    leg.AddEntry(gjets, "Real GJets", "l")
    leg.AddEntry(sideband, "QCD Fake Template", "l")
    leg.AddEntry(full, "Full", "l")

    VarBounds(templates.variable.variable, hslist)
    leg.Draw()

    lumi_label = '%s' % float('%.3g' % (templates.lumi / 1000.)) + " fb^{-1}"
    texLumi, texCMS = getCMSText(lumi_label, templates.year)

    if re.search("(\d+to\d+|\d+toInf)", templates.variable.variable):
        ptrange = templates.variable.variable.split("_")[1].split("to")
        rtext = PtRangeText(ptrange=ptrange)

    c.cd()
    pad2 = TPad("pad2", "pad2", 0.01, 0.01, 0.99, 0.25)
    pad2.SetGridy()
    pad2.Draw()
    pad2.cd()
    pad2.SetFillColor(0)
    pad2.SetFrameBorderMode(0)
    pad2.SetBorderMode(0)
    pad2.SetTopMargin(0)
    pad2.SetBottomMargin(0.35)

    ratio = GetRatio(data, full)

    RatioStyle(ratio,
               rymin=-0.25,
               rymax=2.25,
               xname=templates.variable.xaxis_title,
               yname="Data/Full")
    ratio.Draw("pex0")
    line = getRatioLine(data.GetXaxis().GetXmin(), data.GetXaxis().GetXmax())
    line.Draw("same")

    SaveAs(c,
           "real_template_%s" % templates.varname,
           year=templates.year,
           sub="GammaPurity")
示例#25
0
    def plot(self, **kw):

        from ROOT import kRed
        dirname = retrieve_kw(kw, 'dirname', 'Distribution')
        basecolor = retrieve_kw(kw, 'basecolor', kRed - 7)
        pdftitle = retrieve_kw(kw, 'pdftitle', 'Distributions')
        pdfoutput = retrieve_kw(kw, 'pdfoutput', 'distributions')

        import os
        # Organize outputs (.py and .pdf)
        prefix = self._basepath.split('/')[-1]
        localpath = os.getcwd() + '/' + dirname + '/' + prefix

        try:
            if not os.path.exists(localpath):
                os.makedirs(localpath)
        except:
            self._logger.warning('The director %s exist.', localpath)

        hist_names = [
            'et', 'eta', 'mu', 'nvtx', 'reta', 'eratio', 'weta2', 'rhad',
            'rphi', 'f1', 'f3'
        ]
        hist_labels = [
            'E_{T}', "#eta", "<#mu>", 'N_{vtx}', 'R_{eta}', 'E_{ratio}',
            'W_{eta2}', 'R_{had}', 'R_{phi}', 'f_{1}', 'f_{3}'
        ]

        from ROOT import TCanvas, TH1F, gStyle, TLegend, TPad
        from ROOT import kGreen, kRed, kBlue, kBlack, kGray, gPad, kAzure
        from TrigEgammaDevelopments.plots.AtlasStyle import AtlasStyle, atlas_template, setLegend1

        canvas1 = TCanvas('canvas1', 'canvas1', 2500, 1600)
        canvas1.Divide(4, 3)

        # Concatenate distributions for all regions
        def sumAllRegions(histname):
            h = None
            for etBinIdx in range(len(self._etBins) - 1):
                for etaBinIdx in range(len(self._etaBins) - 1):
                    binningname = ('et%d_eta%d') % (etBinIdx, etaBinIdx)
                    path = self._basepath + '/' + self.currentDir(
                    ) + '/' + binningname
                    if h:
                        h += self.storeSvc().histogram(path + '/' + histname)
                    else:
                        h = self.storeSvc().histogram(path + '/' +
                                                      histname).Clone()
            return h

        collector = []
        figures = {
            'rings': [],
            'rnnOutput': [],
            'ringer_profile': str(),
            'shower_shapes': str()
        }
        """
      Plot all shower shapes distributins
    """
        for idx, histname in enumerate(hist_names):
            self.setDir('Data')
            h_data = sumAllRegions(histname)
            self.setDir('MonteCarlo')
            h_mc = sumAllRegions(histname)
            #h_mc, h_data =  self.__scale_histograms(h_mc, h_data, 100, 0.01, 0.01)

            pad = canvas1.cd(idx + 1)
            gStyle.SetOptStat(110011)
            collector.append(pad)

            h_mc.SetFillColor(basecolor)
            h_mc.SetLineColor(basecolor)
            h_data.SetLineColor(kBlack)
            h_mc.Scale(1. / h_mc.GetMaximum())
            h_data.Scale(1. / h_data.GetMaximum())
            h_mc.Draw()
            h_data.Draw('same')
            leg1 = TLegend(0.2, 0.75, 0.5, 0.95)
            setLegend1(leg1)
            leg1.AddEntry(h_mc, 'MC')
            leg1.AddEntry(h_data, 'Data')
            leg1.Draw()
            collector[-1].Update()
            collector.append(h_mc)
            collector.append(h_data)
            collector.append(leg1)

        canvas1.SaveAs(localpath + '/shower_shapes_distributions.pdf')
        figures[
            'shower_shapes'] = localpath + '/shower_shapes_distributions.pdf'
        """
      Plot all shower ringer shapes for each ring
    """
        ratio_size_as_fraction = 0.35
        from RingerCore import progressbar

        rings_localpath = []

        for r in progressbar(range(100),
                             100,
                             step=1,
                             logger=self._logger,
                             prefix="Looping over rings (Plotting...) "):
            canvas2 = TCanvas('canvas2', 'canvas2', 2500, 1600)
            drawopt = 'pE1'
            canvas2.cd()
            top = TPad("pad_top", "This is the top pad", 0.0,
                       ratio_size_as_fraction, 1.0, 1.0)
            top.SetBottomMargin(0.0)
            top.SetBottomMargin(0.06 / float(top.GetHNDC()))
            #top.SetTopMargin   (0.04/float(top.GetHNDC()))
            top.SetRightMargin(0.05)
            top.SetLeftMargin(0.16)
            top.SetFillColor(0)
            top.Draw(drawopt)

            canvas2.cd()
            bot = TPad("pad_bot", "This is the bottom pad", 0.0, 0.0, 1.0,
                       ratio_size_as_fraction)
            bot.SetBottomMargin(0.10 / float(bot.GetHNDC()))
            #bot.SetTopMargin   (0.02/float(bot.GetHNDC()))
            bot.SetTopMargin(0.0)
            bot.SetRightMargin(0.05)
            bot.SetLeftMargin(0.16)
            bot.SetFillColor(0)
            bot.Draw(drawopt)

            self.setDir('MonteCarlo')
            h_mc = sumAllRegions('rings/ring_' + str(r))
            self.setDir('Data')
            h_data = sumAllRegions('rings/ring_' + str(r))
            gStyle.SetOptStat(000000)

            h_mc, h_data = self.__scale_histograms(h_mc, h_data, 100, 0.0001,
                                                   0.025)
            h_mc.Scale(1. / h_mc.GetMaximum())
            h_data.Scale(1. / h_data.GetMaximum())

            from ROOT import TH1, kGray
            divide = ""
            drawopt = 'pE1'
            bot.cd()
            ref = h_mc.Clone()
            h = h_data.Clone()

            ref.Sumw2()
            h.Sumw2()
            ratioplot = h.Clone()
            ratioplot.Sumw2()
            ratioplot.SetName(h.GetName() + '_ratio')
            ratioplot.Divide(h, ref, 1., 1., '')
            ratioplot.SetFillColor(0)
            ratioplot.SetFillStyle(0)
            ratioplot.SetMarkerColor(1)
            ratioplot.SetLineColor(kGray)
            ratioplot.SetMarkerStyle(24)
            ratioplot.SetMarkerSize(1.2)
            ratioplot.GetYaxis().SetTitleSize(0.10)
            ratioplot.GetXaxis().SetTitleSize(0.10)
            ratioplot.GetXaxis().SetLabelSize(0.10)
            ratioplot.GetYaxis().SetLabelSize(0.10)
            ratioplot.GetYaxis().SetRangeUser(-1.6, 3.7)
            ratioplot.GetYaxis().SetTitleOffset(0.7)
            ratioplot.GetYaxis().SetTitle('Data/MC')
            ratioplot.GetXaxis().SetTitle('Ring #' + str(r + 1) + ' [MeV]')
            ratioplot.Draw(drawopt)
            from ROOT import TLine

            nbins = h_data.GetNbinsX()
            xmin = h_data.GetXaxis().GetBinLowEdge(1)
            xmax = h_data.GetXaxis().GetBinLowEdge(nbins + 1)
            l1 = TLine(xmin, 1, xmax, 1)
            l1.SetLineColor(kRed)
            l1.SetLineStyle(2)
            l1.Draw()
            bot.Update()

            top.cd()

            h_mc.SetFillColor(basecolor)
            h_mc.SetLineWidth(1)
            h_mc.SetLineColor(basecolor)
            h_data.SetLineColor(kBlack)
            h_data.SetLineWidth(1)
            h_mc.GetYaxis().SetTitle('Count')
            h_mc.Draw()
            h_data.Draw('same')

            leg1 = TLegend(0.8, 0.70, 0.95, 0.95)
            setLegend1(leg1)
            leg1.AddEntry(h_mc, 'MC')
            leg1.AddEntry(h_data, 'Data')
            leg1.Draw()
            atlas_template(top)
            top.Update()
            canvas2.SaveAs(localpath + '/distribution_ring_' + str(r + 1) +
                           '.pdf')
            figures['rings'].append(localpath + '/distribution_ring_' +
                                    str(r + 1) + '.pdf')
        """
      Plot ringer mean shapes
    """
        h_mean_data = TH1F('h_mean_data', '', 100, 0, 100)
        h_mean_mc = TH1F('h_mean_mc', '', 100, 0, 100)

        for bin in range(100):
            self.setDir('MonteCarlo')
            h_mc = sumAllRegions('rings/ring_' + str(bin))
            self.setDir('Data')
            h_data = sumAllRegions('rings/ring_' + str(bin))
            h_mean_data.SetBinContent(bin + 1, h_data.GetMean())
            h_mean_mc.SetBinContent(bin + 1, h_mc.GetMean())
        canvas3 = TCanvas('canvas3', 'canvas3', 2500, 1600)

        drawopt = 'pE1'
        canvas3.cd()
        top = TPad("pad_top", "This is the top pad", 0.0,
                   ratio_size_as_fraction, 1.0, 1.0)
        top.SetBottomMargin(0.0)
        top.SetBottomMargin(0.06 / float(top.GetHNDC()))
        #top.SetTopMargin   (0.04/float(top.GetHNDC()))
        top.SetRightMargin(0.05)
        top.SetLeftMargin(0.16)
        top.SetFillColor(0)
        top.Draw(drawopt)

        canvas3.cd()
        bot = TPad("pad_bot", "This is the bottom pad", 0.0, 0.0, 1.0,
                   ratio_size_as_fraction)
        bot.SetBottomMargin(0.10 / float(bot.GetHNDC()))
        #bot.SetTopMargin   (0.02/float(bot.GetHNDC()))
        bot.SetTopMargin(0.0)
        bot.SetRightMargin(0.05)
        bot.SetLeftMargin(0.16)
        bot.SetFillColor(0)
        bot.Draw(drawopt)

        gStyle.SetOptStat(000000)
        from ROOT import TH1, kGray
        divide = ""
        drawopt = 'pE1'
        bot.cd()
        ref = h_mean_mc.Clone()
        h = h_mean_data.Clone()
        ref.Sumw2()
        h.Sumw2()
        ratioplot = h.Clone()
        ratioplot.Sumw2()
        ratioplot.SetName(h.GetName() + '_ratio')
        ratioplot.Divide(h, ref, 1., 1., '')
        ratioplot.SetFillColor(0)
        ratioplot.SetFillStyle(0)
        ratioplot.SetMarkerColor(1)
        ratioplot.SetLineColor(kGray)
        ratioplot.SetMarkerStyle(24)
        ratioplot.SetMarkerSize(1.2)
        ratioplot.GetYaxis().SetTitleSize(0.10)
        ratioplot.GetXaxis().SetTitleSize(0.10)
        ratioplot.GetXaxis().SetLabelSize(0.10)
        ratioplot.GetYaxis().SetLabelSize(0.10)
        ratioplot.GetYaxis().SetRangeUser(-1.6, 3.7)
        ratioplot.GetYaxis().SetTitleOffset(0.7)
        ratioplot.GetYaxis().SetTitle('Data/MC')
        ratioplot.GetXaxis().SetTitle('Rings')
        ratioplot.Draw(drawopt)
        from ROOT import TLine

        nbins = h_mean_data.GetNbinsX()
        xmin = h_mean_data.GetXaxis().GetBinLowEdge(1)
        xmax = h_mean_data.GetXaxis().GetBinLowEdge(nbins + 1)
        l1 = TLine(xmin, 1, xmax, 1)
        l1.SetLineColor(kRed)
        l1.SetLineStyle(2)
        l1.Draw()
        bot.Update()

        top.cd()
        h_mean_mc.SetFillColor(basecolor)
        h_mean_mc.SetLineWidth(1)
        h_mean_mc.SetLineColor(basecolor)
        h_mean_data.SetLineColor(kBlack)
        h_mean_data.SetLineWidth(1)
        #h_mean_mc.Scale( 1./h_mean_mc.GetEntries() )
        #h_mean_data.Scale( 1./h_mean_data.GetEntries() )

        if h_mean_mc.GetMaximum() > h_mean_data.GetMaximum():
            ymin = h_mean_mc.GetMinimum()
            ymax = h_mean_mc.GetMaximum()
            h_mean_mc.Draw()
            h_mean_mc.GetYaxis().SetTitle('E[Ring] MeV')
            h_mean_data.Draw('same')
        else:
            ymin = h_mean_data.GetMinimum()
            ymax = h_mean_data.GetMaximum()
            h_mean_data.GetYaxis().SetTitle('E[Ring] MeV')
            h_mean_data.Draw()
            h_mean_mc.Draw('same')

        h_mean_data.Draw('same')

        # prepare ringer lines
        def gen_line_90(x, ymin, ymax, text):
            from ROOT import TLine, TLatex
            ymax = 1.05 * ymax
            l = TLine(x, ymin, x, ymax)
            l.SetLineStyle(2)
            l.Draw()
            txt = TLatex()
            txt.SetTextFont(12)
            txt.SetTextAngle(90)
            txt.SetTextSize(0.04)
            txt.DrawLatex(x - 1, (ymax - ymin) / 2., text)
            return l, txt

        l_ps, t_ps = gen_line_90(8, ymin, ymax, 'presampler')
        l_em1, t_em1 = gen_line_90(72, ymin, ymax, 'EM.1')
        l_em2, t_em2 = gen_line_90(80, ymin, ymax, 'EM.2')
        l_em3, t_em3 = gen_line_90(88, ymin, ymax, 'EM.3')
        l_had1, t_had1 = gen_line_90(92, ymin, ymax, 'Had.1')
        l_had2, t_had2 = gen_line_90(96, ymin, ymax, 'Had.2')
        l_had3, t_had3 = gen_line_90(100, ymin, ymax, 'Had.3')

        leg1 = TLegend(0.8, 0.70, 0.95, 0.95)
        setLegend1(leg1)
        leg1.AddEntry(h_mean_mc, 'MC')
        leg1.AddEntry(h_mean_data, 'Data')
        leg1.Draw()
        atlas_template(top)
        top.Update()

        canvas3.SaveAs(localpath + '/ringer_profile.pdf')
        figures['ringer_profile'] = localpath + '/ringer_profile.pdf'
        """
      Plot all NN distributions for each calo region
    """
        for algname in self._discrList:
            for etBinIdx in range(len(self._etBins) - 1):
                for etaBinIdx in range(len(self._etaBins) - 1):

                    binningname = ('et%d_eta%d') % (etBinIdx, etaBinIdx)
                    path = self._basepath + '/MonteCarlo/' + binningname
                    h_mc = self.storeSvc().histogram(
                        path + '/' + algname +
                        '/discriminantVsMu').ProjectionX().Clone()
                    path = self._basepath + '/Data/' + binningname
                    h_data = self.storeSvc().histogram(
                        path + '/' + algname +
                        '/discriminantVsMu').ProjectionX().Clone()
                    h_mc.Rebin(10)
                    h_data.Rebin(10)
                    h_mc.Scale(1. / h_mc.GetMaximum())
                    h_data.Scale(1. / h_data.GetMaximum())

                    canvas4 = TCanvas('canvas4', 'canvas4', 2500, 1600)
                    drawopt = 'pE1'
                    canvas4.cd()
                    top = TPad("pad_top", "This is the top pad", 0.0,
                               ratio_size_as_fraction, 1.0, 1.0)
                    top.SetBottomMargin(0.0)
                    top.SetBottomMargin(0.06 / float(top.GetHNDC()))
                    #top.SetTopMargin   (0.04/float(top.GetHNDC()))
                    top.SetRightMargin(0.05)
                    top.SetLeftMargin(0.16)
                    top.SetFillColor(0)
                    top.Draw(drawopt)

                    canvas4.cd()
                    bot = TPad("pad_bot", "This is the bottom pad", 0.0, 0.0,
                               1.0, ratio_size_as_fraction)
                    bot.SetBottomMargin(0.10 / float(bot.GetHNDC()))
                    bot.SetTopMargin(0.0)
                    bot.SetRightMargin(0.05)
                    bot.SetLeftMargin(0.16)
                    bot.SetFillColor(0)
                    bot.Draw(drawopt)

                    gStyle.SetOptStat(000000)

                    from ROOT import TH1, kGray
                    divide = ""
                    drawopt = 'pE1'
                    bot.cd()
                    ref = h_mc.Clone()
                    h = h_data.Clone()
                    ref.Sumw2()
                    h.Sumw2()
                    ratioplot = h.Clone()
                    ratioplot.Sumw2()
                    ratioplot.SetName(h.GetName() + '_ratio')
                    ratioplot.Divide(h, ref, 1., 1., '')
                    ratioplot.SetFillColor(0)
                    ratioplot.SetFillStyle(0)
                    ratioplot.SetMarkerColor(1)
                    ratioplot.SetLineColor(kGray)
                    ratioplot.SetMarkerStyle(24)
                    ratioplot.SetMarkerSize(1.2)
                    ratioplot.GetYaxis().SetTitleSize(0.10)
                    ratioplot.GetXaxis().SetTitleSize(0.10)
                    ratioplot.GetXaxis().SetLabelSize(0.10)
                    ratioplot.GetYaxis().SetLabelSize(0.10)
                    ratioplot.GetYaxis().SetRangeUser(-1.6, 3.7)
                    ratioplot.GetYaxis().SetTitleOffset(0.7)
                    ratioplot.GetYaxis().SetTitle('Data/MC')
                    ratioplot.GetXaxis().SetTitle(
                        'Neural Network (Discriminant)')
                    ratioplot.Draw(drawopt)
                    from ROOT import TLine

                    nbins = h_data.GetNbinsX()
                    xmin = h_data.GetXaxis().GetBinLowEdge(1)
                    xmax = h_data.GetXaxis().GetBinLowEdge(nbins + 1)
                    l1 = TLine(xmin, 1, xmax, 1)
                    l1.SetLineColor(kRed)
                    l1.SetLineStyle(2)
                    l1.Draw()
                    bot.Update()

                    top.cd()
                    h_mc.SetFillColor(basecolor)
                    h_mc.SetLineWidth(1)
                    h_mc.SetLineColor(basecolor)
                    h_data.SetLineColor(kBlack)
                    h_data.SetLineWidth(1)
                    h_mc.Scale(1. / h_mc.GetMaximum())
                    h_data.Scale(1. / h_data.GetMaximum())
                    h_mc.GetYaxis().SetTitle(
                        ('Counts (%s)') % (binningname.replace('_', ',')))
                    h_mc.Draw()
                    h_data.Draw('same')

                    leg1 = TLegend(0.8, 0.70, 0.95, 0.95)
                    setLegend1(leg1)
                    leg1.AddEntry(h_mc, 'MC')
                    leg1.AddEntry(h_data, 'Data')
                    leg1.Draw()
                    atlas_template(top)
                    top.Update()
                    canvas4.SaveAs(localpath + '/' + algname + '_rnnOutput_' +
                                   binningname + '.pdf')
                    figures['rnnOutput'].append(localpath + '/' + algname +
                                                '_rnnOutput_' + binningname +
                                                '.pdf')

        #from RingerCore.tex.TexAPI import *
        from RingerCore.tex.BeamerAPI import BeamerTexReportTemplate1, BeamerSection, BeamerMultiFigureSlide, BeamerFigureSlide
        with BeamerTexReportTemplate1(theme='Berlin',
                                      _toPDF=True,
                                      title=pdftitle,
                                      outputFile=pdfoutput,
                                      font='structurebold'):

            with BeamerSection(name='Shower Shapes'):
                BeamerMultiFigureSlide(
                    title='Shower Shapes (MC and Data)',
                    paths=[figures['shower_shapes']],
                    nDivWidth=1  # x
                    ,
                    nDivHeight=1  # y
                    ,
                    texts=None,
                    fortran=False,
                    usedHeight=0.8,
                    usedWidth=1.1)

            with BeamerSection(name='Ringer Shapes Profile'):
                BeamerMultiFigureSlide(
                    title='Ringer Profile (MC and Data)',
                    paths=[figures['ringer_profile']],
                    nDivWidth=1  # x
                    ,
                    nDivHeight=1  # y
                    ,
                    texts=None,
                    fortran=False,
                    usedHeight=0.8,
                    usedWidth=1.1)

            with BeamerSection(name='Ringer Shapes'):
                for s in range(4):
                    paths1 = [
                        path for path in figures['rings'][s * 25:s * 25 + 25]
                    ]
                    BeamerMultiFigureSlide(
                        title='Ringer Shapes (MC and Data)',
                        paths=paths1,
                        nDivWidth=5  # x
                        ,
                        nDivHeight=5  # y
                        ,
                        texts=None,
                        fortran=False,
                        usedHeight=0.8,
                        usedWidth=1.1)

            for algname in self._discrList:
                with BeamerSection(name=('%s Neural Network Output') %
                                   (algname.replace('_', '\_'))):
                    paths2 = []
                    for etBinIdx in range(len(self._etBins) - 1):
                        for etaBinIdx in range(len(self._etaBins) - 1):
                            binningname = ('et%d_eta%d') % (etBinIdx,
                                                            etaBinIdx)
                            paths2.append(localpath + '/' + algname +
                                          '_rnnOutput_' + binningname + '.pdf')
                    BeamerMultiFigureSlide(
                        title=algname.replace('_', '\_'),
                        paths=paths2,
                        nDivWidth=len(self._etaBins)  # x
                        ,
                        nDivHeight=len(self._etBins)  # y
                        ,
                        texts=None,
                        fortran=False,
                        usedHeight=1.0,
                        usedWidth=1.1)

        return StatusCode.SUCCESS
示例#26
0
def main():

    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-i", "--inputfile", dest="inputfile")
    parser.add_option("-N", "--multiplicity", dest="N", type="int", default=3)
    parser.add_option("-x", "--exclusive", action="store_true",\
          dest="isExclusive", default=False)
    parser.add_option("-l", "--label", dest="label", type="string", default="")
    parser.add_option("-z",
                      "--zeyneplabel",
                      action="store_true",
                      dest="zeynep",
                      default=True)
    (options, args) = parser.parse_args()

    N = options.N
    isExclusive = options.isExclusive
    label_text = options.label

    zeynep = options.zeynep

    if isExclusive and not (N == 2 or N == 3):
        parser.error("Exclusive plot only for N =2 or 3")

    import configurations as config
    from ROOT import TFile, TCanvas, THStack, TLegend, TPaveText, gStyle, TPad, TH1F, TGraphAsymmErrors, TMath
    from ModelParser import ModelKey

    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadRightMargin(0.05)
    gStyle.SetPadBottomMargin(0.20)

    gStyle.SetErrorX(0.)

    suffix = ""
    if not isExclusive:
        suffix = "up"

    sm_files = []
    for model in config.sm_models:
        f = TFile("%s/%s.root" % (config.sm_dir, model), "READ")
        sm_files.append(f)

    bh_weights = []
    bh_files = []
    from BHXsec import BHXsec
    xsec = BHXsec()
    for model in config.bh_showcase:
        f = TFile("%s/%s.root" % (config.bh_dir, model), "READ")
        bh_files.append(f)
        h = f.Get("plotsNoCut/ST")
        nEvents = h.GetEntries()
        bh_weights.append(
            xsec.get(model) / nEvents * config.integrated_luminosity)

    c = TCanvas("ST_Mul%d%s" % (N, suffix), "ST_Mul%d%s" % (N, suffix), 500,
                600)
    hs = THStack()
    hs1 = THStack()

    infile = TFile(options.inputfile, "READ")
    hBkg = infile.Get("Background_N%d%s" % (N, suffix))
    #hnewBkg = infile.Get("histoTemplateN3_0")
    hnewBkg = infile.Get("ReferenceTemplateN3_0")
    gBkg = infile.Get("BackgroundGraph_N%d%s" % (N, suffix))
    hData = infile.Get("Data_N%d%s" % (N, suffix))
    hBkg = infile.Get("Background_N%d%s" % (N, suffix))
    hBkg.SetMarkerSize(0)
    hBkg_ = hBkg.Clone("BkgLine")
    hBkg.SetFillColor(33)
    hBkg.SetLineColor(33)
    hBkg_.SetLineWidth(3)
    hBkg_.SetLineColor(862)

    hs.Add(hBkg, "e3")
    hnewBkg.SetLineWidth(3)
    hnewBkg.Scale(10 * 3.407)
    hs.Add(hnewBkg, "l")

    legend = TLegend(0.2826613, 0.4819492, 0.6094355,
                     0.9416102)  # - only for N >= 2 and 3
    #legend = TLegend(0.3026613,0.5519492,0.6094355,0.9416102) # was 0.4919...zeynep

    #legend = TLegend(0.3526613,0.5519492,0.6094355,0.9416102) # was 0.4919...

    #legend.SetTextSize(0.041); #was 0.02966102
    legend.SetTextSize(0.037)
    legend.SetTextFont(42)
    legend.SetFillColor(0)
    legend.SetLineColor(0)
    if isExclusive:
        legend.SetHeader("Multiplicity N = %d" % N)
    else:
        legend.SetHeader("Multiplicity N #geq %d" % N)
    legend.AddEntry(hData, "Data", "lep")
    #legend.AddEntry(hnewBkg, "N=3 Fit Rescaled","l")
    legend.AddEntry(hBkg_, "Background", "l")
    legend.AddEntry(hBkg, "Uncertainty", "f")

    legend_sm = TLegend(0.6471774, 0.7069492, 0.8508065, 0.8471186)
    #   legend_sm = TLegend(0.6271774,0.7369492,0.8308065,0.8771186)
    #   legend_sm.SetTextSize(0.037);
    legend_sm.SetTextSize(0.037)

    legend_sm.SetTextFont(42)
    legend_sm.SetFillColor(0)
    legend_sm.SetLineColor(0)

    for i, f in enumerate(bh_files):
        h = f.Get("plotsN%d%s/ST" % (N, suffix))
        h.Rebin(config.rebin)
        h.Scale(bh_weights[i])

        # Add background
        for ibin in range(h.GetNbinsX()):
            h.SetBinContent(ibin+1,\
                  h.GetBinContent(ibin+1)\
                  + hBkg.GetBinContent(ibin+1))

            h.SetLineWidth(3)
            #h.SetLineColor(i+2)
            h.SetLineStyle(i + 2)

            #if i == 0:
            #h.SetLineColor(814)
            if i == 0:
                h.SetLineStyle(5)
                h.SetLineColor(899)
            if i == 1:
                h.SetLineStyle(9)
                h.SetLineColor(4)
            if i == 2:
                h.SetLineStyle(3)
                h.SetLineColor(614)

        hs.Add(h, "hist")
        model = ModelKey(config.bh_showcase[i])
        bh_legend = "M_{D} = %.1f TeV, M_{BH}^{ min} = %.1f TeV, n = %d" % (\
              model.parameter["MD"],
              model.parameter["M"],
              model.parameter["n"])
        if i == 3:
            bh_legend = "M_{D} = 3.0 TeV, M_{QBH}^{ min} = 4.0 TeV, n = 4"

        legend.AddEntry(h, bh_legend, "l")

#      qbh_legend = "M_{D} = 4.0 TeV, M_{QBH}^{ min} = 5.0 TeV, n = 5"

#      legend.AddEntry(h, qbh_legend, "l")

#if isExclusive:
    zeynep = True
    if zeynep:
        for i, f in enumerate(sm_files):
            h = f.Get("plotsN%d%s/ST" % (N, suffix))
            h.Rebin(config.rebin)
            h.Scale(config.integrated_luminosity)
            h.SetFillColor(config.sm_colors[i])
            h.SetLineColor(config.sm_colors[i])
            hs1.Add(h, "hist")
            legend_sm.AddEntry(h, config.sm_models[i], "f")

    #hs.Add(hData, "e")

    hs.Draw("nostack")
    hs1.Draw("same")

    c.SetLogy(1)
    hs.GetXaxis().SetTitle("S_{T} (GeV)")
    hs.GetYaxis().SetTitle(hData.GetYaxis().GetTitle())
    hs.GetYaxis().SetTitleOffset(1.25)

    hs.GetYaxis().SetTitleSize(0.04)
    hs.GetYaxis().SetLabelSize(0.04)
    hs.GetXaxis().SetTitleSize(0.01)
    hs.GetXaxis().SetLabelSize(0.01)

    ibin = 0
    #if isExclusive:
    #   hs.GetXaxis().SetRangeUser(config.fit_range[0], config.maxST)
    #   ibin = hData.FindBin(config.fit_range[0])
    #else:
    #   hs.GetXaxis().SetRangeUser(config.norm_range[0], config.maxST)
    #   ibin = hData.FindBin(config.norm_range[0])

    if isExclusive:
        hs.GetXaxis().SetRangeUser(1800, config.maxST)
        ibin = hData.FindBin(1800)
    else:
        hs.GetXaxis().SetRangeUser(config.norm_range[0], config.maxST)
        ibin = hData.FindBin(config.norm_range[0])

    from Styles import formatUncertainty
    formatUncertainty(gBkg)
    gBkg.Draw("LX")
    hData.Draw("sameex0")

    hs.SetMinimum(5e-1)
    if isExclusive:
        hs.SetMaximum(1e7)

#     hs.SetMaximum(hData.GetBinContent(ibin) * 40)
    else:
        #hs.SetMaximum(1e8)
        hs.SetMaximum(hData.GetBinContent(ibin) *
                      20)  # or 1e7 for N>=3 and use 4 models

    legend.Draw("plain")
    #if isExclusive:
    if zeynep:
        legend_sm.Draw("plain")

    if isExclusive:
        cmslabel = TPaveText(0.45, 0.96, 0.60, 0.99, "brNDC")
    else:
        cmslabel = TPaveText(0.45, 0.96, 0.60, 0.99, "brNDC")
    cmslabel.AddText(config.cmsTitle)
    #cmslabel.AddText(config.cmsSubtitle)
    cmslabel.SetFillColor(0)
    cmslabel.SetTextSize(0.041)
    cmslabel.Draw("plain")

    label = TPaveText(0.8891129, 0.8644068, 0.9435484, 0.9258475, "brNDC")
    label.SetFillColor(0)
    #label.SetTextSize(0.0529661);
    label.SetTextSize(0.0529661)
    label.AddText(label_text)
    label.Draw("plain")

    c.RedrawAxis()

    #Divide

    ibin = hData.FindBin(config.norm_range[0])
    #print ibin

    fbin = hData.FindBin(config.maxST)
    #print fbin

    hData.Sumw2()
    hBkg_.Sumw2()

    Pull = TH1F("", "", fbin - ibin + 1, (ibin - 1) * 100, fbin * 100)
    Pull2 = TH1F("", "", fbin - ibin + 1, (ibin - 1) * 100, fbin * 100)

    Ratio = hData.Clone()
    Ratio.Add(hBkg_, -1)
    #Ratio.Divide(hBkg_)

    Band = TGraphAsymmErrors(fbin - ibin + 1)

    for i in range(ibin - 1, fbin + 1):
        i += 1
        if hData.GetBinContent(i) != 0:
            value = hData.GetBinContent(i) + (hBkg_.GetBinError(i) *
                                              hBkg_.GetBinError(i))
            #print Ratio.GetBinError(i),  value**(0.5)
            #print i-19,i,(i)*100, hData.GetBinContent(i) , hBkg_.GetBinContent(i),hData.GetBinContent(i) - hBkg_.GetBinContent(i)
            Pull.SetBinContent(
                i - 19, (hData.GetBinContent(i) - hBkg_.GetBinContent(i)) /
                Ratio.GetBinError(i))
            #print Ratio.GetBinError(i), abs(Ratio.GetBinContent(i))*0.05
            #Pull.SetBinContent(i-19,(hData.GetBinContent(i) - hBkg_.GetBinContent(i))/ Ratio.GetBinError(i))
            #Pull.SetBinContent(i-19,(hData.GetBinContent(i) / hBkg_.GetBinContent(i)))
            Pull.SetBinError(i - 19, Ratio.GetBinError(i))
            #Pull.SetBinError(i-19,hData.GetBinError(i)/gBkg.GetErrorY(i))
            if (hBkg_.GetBinContent(i) * 0.05 > hBkg_.GetBinError(i)):
                #print "bin error too small changing the error to: ", hBkg_.GetBinContent(i)*0.05
                Pull2.SetBinContent(
                    i - 19,
                    (hnewBkg.GetBinContent(i) - hBkg_.GetBinContent(i)) /
                    (hBkg_.GetBinContent(i) * 0.05))
            else:
                Pull2.SetBinContent(
                    i - 19,
                    (hnewBkg.GetBinContent(i) - hBkg_.GetBinContent(i)) /
                    hBkg_.GetBinError(i))
            #print hBkg_.GetBinError(i), hBkg_.GetBinContent(i)*0.05
            #print i, " Pull2: ", Pull2.GetBinContent(i-19), "hnewBkg.GetBinContent(i-1): " , hnewBkg.GetBinContent(i-1), "hBkg_.GetBinContent(i): ", hBkg_.GetBinContent(i)
        else:
            Pull.SetBinContent(i - 19, 0)
            Pull2.SetBinContent(
                i - 19,
                (hnewBkg.GetBinContent(i - 1) - hBkg_.GetBinContent(i)) /
                hBkg_.GetBinError(i))

        Band.SetPoint(i, hBkg_.GetBinCenter(i), 1.0)
        #print hBkg_.GetBinContent(i), hBkg_.GetBinError(i)
        up = abs(1. - ((hBkg_.GetBinContent(i) + hBkg_.GetBinError(i)) /
                       hBkg_.GetBinContent(i)))
        down = abs(1. - ((hBkg_.GetBinContent(i) - hBkg_.GetBinError(i)) /
                         hBkg_.GetBinContent(i)))
        Band.SetPointError(i, 0., 0., down, up)

    #Band.Print()
    pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0)

    pad.SetTopMargin(0.799999)
    pad.SetRightMargin(0.05)
    pad.SetBottomMargin(0.09)

    pad.SetFillColor(0)
    #pad.SetGridy(1)
    pad.SetFillStyle(0)
    pad.Draw("same")
    pad.cd(0)

    Ratio.SetMarkerStyle(20)
    Pull.SetMarkerStyle(20)
    Pull.SetLineColor(1)
    Pull.SetMarkerSize(0.9)
    #Pull.SetMaximum(3)
    #Pull.SetMinimum(-1)

    Pull.SetMaximum(2.5)
    Pull.SetMinimum(-2.5)
    Pull.GetYaxis().SetNdivisions(5, 1)

    Pull.GetXaxis().SetTitle('S_{T} (GeV)')
    Pull.GetXaxis().SetLabelSize(0.04)

    Pull.GetYaxis().SetTitleOffset(1.05)
    Pull.GetYaxis().SetLabelSize(0.02)
    Pull.GetYaxis().SetTitleSize(0.025)
    Pull.GetYaxis().CenterTitle(1)

    Pull.GetYaxis().SetTitle('#sigma(Data-Bkg)')

    Pull.SetFillColor(2)
    Pull.Draw("HIST")
    Pull2.SetLineColor(862)
    Pull2.SetLineWidth(3)
    Pull2.SetLineStyle(2)
    #Pull2.Draw("SAME")
    formatUncertainty(Band)
    Band.SetFillStyle(3001)

    # Band.Draw("le3")
    # Pull.Draw("ex0same")
    pad.RedrawAxis()

    gStyle.SetOptStat(0)

    #block1 =TPaveText(0.370,0.84,0.351,0.86,"brNDC"); # for N>=2 and >=3 only
    #block1 =TPaveText(0.361,0.85,0.377,0.87,"brNDC");
    #block1 =TPaveText(0.333,0.88,0.354,0.85,"brNDC") #for n = 2 only

    block1 = TPaveText(0.331, 0.82, 0.357, 0.85, "brNDC")
    #FOR n=3 only
    block1.SetFillColor(0)
    block1.Draw("plain")

    #block2 =TPaveText(0.305,0.84,0.333,0.86,"brNDC"); # for N>=2 and >=3 only
    #block2 =TPaveText(0.395,0.85,0.41,0.87,"brNDC");
    #block2 =TPaveText(0.296,0.88,0.316,0.85,"brNDC"); for n =2 only

    block2 = TPaveText(0.295, 0.82, 0.317, 0.85, "brNDC")
    #FOR n=3 only
    block2.SetFillColor(0)
    block2.Draw("plain")

    if isExclusive:
        c.Print("ST_Mul%d.pdf" % N)
        c.Print("ST_Mul%d.png" % N)
    else:
        c.Print("ST_Mul%dup.pdf" % N)
        c.Print("ST_Mul%dup.png" % N)
    c.Update()

    raw_input("Press Enter to continue...")
]

for i in range(len(h)):
    read_hist(hist_name, h[i], indir, which_year, which_channel,
              setting_for_h[i][1], which_region, barrel_or_endcap,
              setting_for_h[i][0])
    set_hist(h[i], setting_for_h[i][0], setting_for_h[i][1],
             setting_for_h[i][2])

h[10].Add(h[12], -1)
h[11].Add(h[12], -1)

cv = TCanvas("cv_", "cv_", 900, 900)
fPads1 = TPad("pad1", "", 0.00, 0.225, 1.00, 1.00)
fPads2 = TPad("pad2", "", 0.00, 0.00, 1.00, 0.23)
fPads1.SetFillColor(0)
fPads1.SetLineColor(1)
fPads2.SetFillColor(0)
fPads2.SetLineColor(5)
fPads1.SetLineWidth(15)
fPads2.SetLineWidth(13)
fPads1.SetBottomMargin(0.02)
fPads1.SetTicks(1, 1)
fPads1.SetTicks(1, 1)
fPads2.SetTopMargin(0.02)
fPads2.SetBottomMargin(0.4)
fPads1.Draw()
fPads2.Draw()

#cv.SetLogy()
hs = THStack(" ", " ")
示例#28
0
t.SetTextSize(0.026)
t.DrawText(3, 17, r'>>>  x, y = 5, 7')
t.DrawText(3, 16, r'>>>  import math; x*math.sqrt(y)')
t.DrawText(
    3, 14,
    r'>>>  for i in range(2,7): print "sqrt(%d) = %f" % (i,math.sqrt(i))')
t.DrawText(3, 10,
           r'>>>  import ROOT; f1 = ROOT.TF1( "f1", "sin(x)/x", 0, 10 )')
t.DrawText(3, 9, r'>>>  f1.Draw()')
t.SetTextFont(81)
t.SetTextSize(0.018)
t.DrawText(4, 15, '13.228756555322953')
t.DrawText(4, 13.3, 'sqrt(2) = 1.414214')
t.DrawText(4, 12.7, 'sqrt(3) = 1.732051')
t.DrawText(4, 12.1, 'sqrt(4) = 2.000000')
t.DrawText(4, 11.5, 'sqrt(5) = 2.236068')
t.DrawText(4, 10.9, 'sqrt(6) = 2.449490')

pad = TPad('pad', 'pad', .2, .05, .8, .35)
pad.SetFillColor(42)
pad.SetFrameFillColor(33)
pad.SetBorderSize(10)
pad.Draw()
pad.cd()
pad.SetGrid()

f1 = TF1('f1', 'sin(x)/x', 0, 10)
f1.Draw()
nut.cd()
nut.Update()
        c.SetRightMargin(R / W)
        c.SetTopMargin(T / H)
        c.SetBottomMargin(B / H)
        c.SetTickx(0)
        c.SetTicky(0)
        c.Draw()
        c.cd()

        pad1 = TPad("zxc_p1", "zxc_p1", 0, padRatio - padOverlap, 1, 1)
        pad2 = TPad("qwe_p2", "qwe_p2", 0, 0, 1, padRatio + padOverlap)
        pad1.SetLeftMargin(L / W)
        pad1.SetRightMargin(R / W)
        pad1.SetTopMargin(T / H / (1 - padRatio + padOverlap))
        pad1.SetBottomMargin(
            (padOverlap + padGap) / (1 - padRatio + padOverlap))
        pad1.SetFillColor(0)
        pad1.SetBorderMode(0)
        pad1.SetFrameFillStyle(0)
        pad1.SetFrameBorderMode(0)
        pad1.SetTickx(0)
        pad1.SetTicky(0)

        pad2.SetLeftMargin(L / W)
        pad2.SetRightMargin(R / W)
        pad2.SetTopMargin((padOverlap) / (padRatio + padOverlap))
        pad2.SetBottomMargin(B / H / (padRatio + padOverlap))
        pad2.SetFillColor(0)
        pad2.SetFillStyle(4000)
        pad2.SetBorderMode(0)
        pad2.SetFrameFillStyle(0)
        pad2.SetFrameBorderMode(0)
示例#30
0
def makeRatioPlot(hNum,
                  hDen,
                  hDen2="",
                  nameNum="num",
                  nameDen="den",
                  nameDen2="",
                  xtitle="pt",
                  ytitle="Entries",
                  ratiotitle="Ratio",
                  norm=False,
                  log=True,
                  plotName="ratio",
                  outDir='out',
                  ratioyrange=(0, 2)):
    TH1.SetDefaultSumw2()

    # prepare settings of histos
    hNum.SetLineColor(kBlack)
    hNum.SetLineWidth(2)
    hNum.SetMarkerStyle(20)
    #hNum.SetMarkerStyle(1)
    hNum.SetMarkerColor(kBlack)
    hNum.GetYaxis().SetTitle(ytitle)

    hDen.SetLineColor(kOrange + 1)
    hDen.SetMarkerColor(kOrange + 1)
    hDen.SetLineWidth(2)
    hDen.SetMarkerStyle(21)
    #hDen.SetMarkerStyle(1)

    if nameDen2 != "":
        hDen2.SetLineColor(kBlue)
        hDen2.SetMarkerColor(kBlue)
        hDen2.SetLineWidth(2)
        hDen2.SetMarkerStyle(22)
        #hDen2.SetMarkerStyle(1)
        makeHistSettings(hDen2)  #

    makeHistSettings(hNum)
    makeHistSettings(hDen)

    # prepare canva
    canvas = TCanvas(plotName, plotName, 600, 600)
    ROOT.SetOwnership(
        canvas, False
    )  # Crucial to avoid crashes due to the way python deletes the objects
    canvas.cd()
    yMinP1 = 0.305
    bottomMarginP1 = 0.005
    pad1 = TPad('pad1', 'pad1', 0, yMinP1, 0.99, 1)
    if log: pad1.SetLogy()
    pad1.SetBottomMargin(bottomMarginP1)
    pad1.SetFillColor(kWhite)
    pad1.SetTickx()
    pad1.SetTicky()
    pad2 = TPad('pad2', 'pad2', 0., 0.01, .99, 0.300)
    pad2.SetTopMargin(0.033)
    pad2.SetBottomMargin(0.40)
    pad2.SetFillColor(kWhite)
    pad2.SetGridy()
    pad1.SetNumber(1)
    pad2.SetNumber(2)
    pad1.Draw()
    pad2.Draw()

    # prepare legend
    #leg = TLegend(0.75,0.68,0.82,0.88,'')
    #leg.SetBorderSize(0)
    #leg.SetTextSize(0.05)
    leg = defaultLegend(x1=0.15, y1=0.7, x2=0.95, y2=0.95, mult=1.5)

    # Draw
    pad1.cd()
    histo_saver = []

    opt = 'histE'
    #hNumNorm = hNum.Clone()
    if norm:
        hNumNorm = hNum.DrawNormalized('histE')
        histo_saver.append(hNumNorm)
    else:
        hNum.Draw('histE')


#  hNum.SetMaximum(hNum.GetMaximum()*4)
#leg.Draw('same')
    ymax = max(hNum.GetMaximum(), hDen.GetMaximum())

    if log == True:
        hNum.SetMaximum(ymax * 30)
    else:
        hNum.SetMaximum(ymax * 1.7)

    #hDenNorm = hDen.Clone()
    if norm:
        hDenNorm = hDen.DrawNormalized('samehistE')
        histo_saver.append(hDenNorm)
    else:
        hDen.Draw('samehistE')

    #hDenNorm2 = hDen2.Clone()
    if nameDen2 != "":
        if norm:
            hDenNorm2 = hDen2.DrawNormalized('samehistE')
            histo_saver.append(hDenNorm2)
        else:
            hDen2.Draw('samehistE')
        leg.AddEntry(hDen2, nameDen2, 'LP')

    leg.AddEntry(hDen, nameDen, 'LP')
    leg.AddEntry(hNum, nameNum, 'LP')
    leg.Draw('same')

    #print hNumNorm.Integral(), hDenNorm.Integral(), hDenNorm2.Integral()
    #print hNum.Integral(), hDen.Integral(), hDen2.Integral()

    #######################################################
    ### RATIO PAD
    #######################################################
    pad2.cd()
    hRatio = hNum.Clone()
    if nameDen2 != "": hRatio2 = hNum.Clone()

    if norm:
        hRatio = hNumNorm.Clone()
        hRatio2 = hNumNorm.Clone()
        #print 'Ratio integral before division'
        #print hRatio.Integral(), hRatio2.Integral()

        hRatio.Divide(hDenNorm)
        if nameDen2 != "": hRatio2.Divide(hDenNorm2)

        #print 'Ratio integral after division'
        #print hRatio.Integral(), hRatio2.Integral()

    else:
        hRatio.Divide(hDen)
        if nameDen2 != "": hRatio2.Divide(hDen2)

    #hRatio.SetLineColor(kRed+2)
    if nameDen2 != "": hRatio2.SetLineColor(kBlue)
    #print hRatio.Integral()
    makeRatioSettings(hRatio)
    if nameDen2 != "": makeRatioSettings(hRatio2)
    hRatio.GetYaxis().SetRangeUser(ratioyrange[0], ratioyrange[1])

    hRatio.GetXaxis().SetTitle(xtitle)
    hRatio.GetYaxis().SetTitle(ratiotitle)
    hRatio.SetTitle('')

    hRatio.Draw('histE')
    if nameDen2 != "": hRatio2.Draw('histEsame')
    #hRatio.GetXaxis().SetRangeUser(200.,2000.)

    canvas.SaveAs('{d}/{name}.pdf'.format(d=outDir, name=plotName))
    canvas.SaveAs('{d}/{name}.png'.format(d=outDir, name=plotName))