Example #1
0
def plot_hists(hists, name, **kw):
    """
    Function for formatting a list of histograms and plotting them on the same
    canvas, stacked. Returns a dictionary with the following keys:
    'canvas', 'stack', 'hists'.
    """

    #
    #  Read the congif
    #
    show_stats = kw.get('show_stats', False)
    debug = kw.get('debug', False)

    if debug: print "\t in plot_hists"

    #
    #  Config Hists
    #
    plot = config_hists(hists, **kw)

    #
    #  Build the canvas
    #
    c = makeCanvas(name, name, **kw)

    if debug: print "\t calling plot_hists_lists"
    plot_hist_list(hists, **kw)

    # arrange stats
    if show_stats:
        c.Update()
        arrange_stats(hists)
    c.Update()
    return {'canvas': c, 'hists': hists}
def drawStackCompRatio(outName,dataInfo,MCInfo,yTitle,xTitle,rTitle,outDir,min=1,setLogy=1,x_min=None,x_max=None,cmsText="", lumiText=""):
    histData = dataInfo[0].Clone()


    stacksum=MCInfo[0][0].Clone("tmp")
    stacksum.Reset()
    for h in MCInfo:
        stacksum.Add(h[0])

    stacksum.Integral()
    scaleFactor = histData.Integral()/stacksum.Integral()

    

    stack = ROOT.THStack("TestStack", outName)
    for hMC in MCInfo:
        hMC[0].SetFillColor(hMC[2])
        hMC[0].Scale(scaleFactor)
        stack.Add(hMC[0], 'sames')

    stacksum.Scale(scaleFactor)

#    hist2 = histInfo[1][0].Clone()
#    hist2.SetFillColor(ROOT.kYellow)
        
    maxY = max(histData.GetMaximum(),stack.GetMaximum())

    if setLogy:
        histData.SetMaximum(4e0*maxY)
        histData.SetMinimum(min)
        stack.SetMaximum(4e0*maxY)
        stack.SetMinimum(min)
    else:
        stack.SetMaximum(1.4*maxY)
        histData.SetMaximum(1.4*maxY)


    histData.GetYaxis().SetTitle(yTitle)
    histData.GetXaxis().SetTitle(xTitle)

    


    xpos = 0.5
    ypos = 0.69
    xwidth = 0.3
    ywidth = 0.05*(len(MCInfo)+1)
    
    leg = ROOT.TLegend(xpos, ypos, xpos+xwidth, ypos+ywidth)
    leg.AddEntry(histData,dataInfo[1],"PEL")
    for hMC in MCInfo:
        leg.AddEntry(hMC[0],hMC[1] ,"F")
    #leg.AddEntry(offLF,"Offline tracks light-flavor jets","L")
    #leg.AddEntry(hltLF,"HLT tracks light-flavor jets"    ,"PEL")

    canvas = makeCanvas(outName, outName, width=600, height=600)
    split=0.3
    top_pad    = ROOT.TPad("pad1", "The pad 80% of the height",0,split,1,1,0)
    bottom_pad = ROOT.TPad("pad2", "The pad 20% of the height",0,0,1,split,0)
    top_pad.Draw()
    bottom_pad.Draw()
    
    axissep = 0.02
    top_pad.cd()
    top_pad.SetLogy(setLogy)
    top_pad.SetTopMargin(canvas.GetTopMargin()*1.0/(1.0-split))
    top_pad.SetBottomMargin(0.5*axissep)
    top_pad.SetRightMargin(canvas.GetRightMargin())
    top_pad.SetLeftMargin(canvas.GetLeftMargin());
    top_pad.SetFillStyle(0) # transparent
    top_pad.SetBorderSize(0)
        

    stack.Draw()
    if x_max is not None and x_min is not None:
        stack.GetXaxis().SetRangeUser(x_min,x_max)
        histData.GetXaxis().SetRangeUser(x_min,x_max)

    stack.GetYaxis().SetTitle(yTitle)
    stack.GetXaxis().SetTitle(xTitle)
    stack.Draw("hist")


    #hltLF.SetMarkerSize(0.75)
    #hltLF.SetMarkerStyle(21)
    histData.Draw("same pe")
    #offBQ.Draw("hist same")
    #hltBQ.SetMarkerSize(0.75)
    #hltBQ.SetMarkerStyle(21)
    #hltBQ.Draw("same pe")
    leg.Draw("same")

    histRatio = makeRatio(num = histData.Clone(),  den = stacksum.Clone())

    cmsLines = getCMSText(xStart=0.225,yStart=0.85,subtext=cmsText,lumiText=lumiText)
    for cmsl in cmsLines:
        cmsl.Draw("same")



    bottom_pad.cd()
    bottom_pad.SetTopMargin(2*axissep)
    bottom_pad.SetBottomMargin(canvas.GetBottomMargin()*1.0/split)
    bottom_pad.SetRightMargin(canvas.GetRightMargin())
    bottom_pad.SetLeftMargin(canvas.GetLeftMargin());
    bottom_pad.SetFillStyle(0) # transparent
    bottom_pad.SetBorderSize(0)
    ratio_axis = histData.Clone()
    #ratio_axis.GetYaxis().SetTitle("PF to Calo")
    ratio_axis.GetYaxis().SetTitle("Ratio")
    ratio_axis.GetXaxis().SetTitle(histData.GetXaxis().GetTitle())
    ratio_axis.GetYaxis().SetNdivisions(507)
    rMin = 0
    rMax = 2
    ratio_axis.GetYaxis().SetRangeUser(rMin, rMax)
    histRatio.GetYaxis().SetRangeUser(rMin, rMax)
    histRatio.GetYaxis().SetTitle(rTitle)


    histRatio.Draw("PE")
    histRatio.Draw("PE same")
    oldSize = histRatio.GetMarkerSize()
    histRatio.SetMarkerSize(0)
    histRatio.DrawCopy("same e0")
    histRatio.SetMarkerSize(oldSize)
    histRatio.Draw("PE same")

    line = ROOT.TLine()
    if x_max is not None and x_min is not None:
        line.DrawLine(x_min, 1.0, x_max, 1.0)
    else:
        line.DrawLine(histData.GetXaxis().GetXmin(), 1.0, histData.GetXaxis().GetXmax(), 1.0)

    ndivs=[505,503]

    pads = [top_pad, bottom_pad]
    factors = [0.8/(1.0-split), 0.7/split]
    for i_pad, pad in enumerate(pads):

        factor = factors[i_pad]
        ndiv   = ndivs[i_pad]
        
        prims = [ p.GetName() for p in pad.GetListOfPrimitives() ]
        
        #
        #  Protection for scaling hists multiple times
        #
        procedHist = []
        
        for name in prims:
            
            if name in procedHist: continue
            procedHist.append(name)
        
            h = pad.GetPrimitive(name)
            if isinstance(h, ROOT.TH1) or isinstance(h, ROOT.THStack) or isinstance(h, ROOT.TGraph) or isinstance(h, ROOT.TGraphErrors) or isinstance(h, ROOT.TGraphAsymmErrors):
                if isinstance(h, ROOT.TGraph) or isinstance(h, ROOT.THStack) or isinstance(h, ROOT.TGraphErrors) or isinstance(h, ROOT.TGraphAsymmErrors):
                    h = h.GetHistogram()
                #print "factor is",factor,h.GetName(),split
        
                if i_pad == 1:
                    h.SetLabelSize(h.GetLabelSize('Y')*factor, 'Y')
                    h.SetTitleSize(h.GetTitleSize('X')*factor, 'X')
                    h.SetTitleSize(h.GetTitleSize('Y')*factor, 'Y')
                    h.SetTitleOffset(h.GetTitleOffset('Y')/factor, 'Y')
                    
                if i_pad == 1:
                    h.GetYaxis().SetNdivisions(ndiv)
                h.GetXaxis().SetNdivisions()                
                if i_pad == 0:
                    h.SetLabelSize(0.0, 'X')
                    h.GetXaxis().SetTitle("")
                else:
                    h.SetLabelSize(h.GetLabelSize('X')*factor, 'X')
                    ## Trying to remove overlapping y-axis labels.  Doesn't work.
                    # h.GetYaxis().Set(4, h.GetYaxis().GetXmin(), h.GetYaxis().GetXmax()) 
                    # h.GetYaxis().SetBinLabel( h.GetYaxis().GetLast(), '')






    canvas.SaveAs(outDir+"/"+outName+".pdf")
def drawCompRatioGraphs(name,inputHists,ratioHistBinning,yTitle,xTitle,outDir,otherText="",setLogy=1,yMax= 1,yMin = 0,leg="",xMax=1,xMin = -0.2,yLeg=0.76,xLeg=0.2,xStartOther=0.5, yStartOther=0.9, doFit = False,cmsText="Preliminary", lumiText="",rTitle="Ratio",histForXBarycenterCalc=None):

    upperHist = inputHists[0][0].GetHistogram()
    upperHist.GetYaxis().SetTitle(yTitle)
    upperHist.GetXaxis().SetTitle(xTitle)
    upperHist.GetYaxis().SetNdivisions(507)

    
    upperHist.GetYaxis().SetRangeUser(yMin, yMax)
    upperHist.GetXaxis().SetRangeUser(xMin, xMax)



    canvas = makeCanvas(name, name, width=600, height=600)
    split=0.3
    top_pad    = ROOT.TPad("pad1", "The pad 80% of the height",0,split,1,1,0)
    bottom_pad = ROOT.TPad("pad2", "The pad 20% of the height",0,0,1,split,0)
    top_pad.Draw()
    bottom_pad.Draw()

    axissep = 0.035
    top_pad.cd()
    #top_pad.SetLogy(setLogy)
    top_pad.SetTopMargin(canvas.GetTopMargin()*1.0/(1.0-split))
    top_pad.SetBottomMargin(0.5*axissep)
    top_pad.SetRightMargin(canvas.GetRightMargin())
    top_pad.SetLeftMargin(canvas.GetLeftMargin());
    top_pad.SetFillStyle(0) # transparent
    top_pad.SetBorderSize(0)

    upperHist.Draw("axis")



    for hInfoIndx, hInfo  in enumerate(inputHists):

        hInfo[0].SetLineColor  (hInfo[2])
        hInfo[0].SetMarkerColor(hInfo[2])
        if len(hInfo) > 3:
            hInfo[0].SetMarkerStyle(hInfo[3])
            hInfo[0].SetFillStyle(hInfo[3])

        if hInfoIndx:
            hInfo[0].Draw("PE same")    

        else:
            hInfo[0].Draw("PE same")

    numHist = ratioHistBinning.Clone()
    denHist = ratioHistBinning.Clone()

    for iBin in range(inputHists[0][0].GetN()):
        xValue = ROOT.Double(0)
        theEff = ROOT.Double(0)
        theEffErr = inputHists[0][0].GetErrorY(iBin)
        inputHists[0][0].GetPoint(iBin,xValue,theEff)
        #print iBin, xValue, theEff
        numHist.SetBinContent(numHist.FindBin(xValue), theEff)
        numHist.SetBinError(numHist.FindBin(xValue), theEffErr)

        
    for iBin in range(inputHists[1][0].GetN()):
        xValue = ROOT.Double(0)
        theEff = ROOT.Double(0)
        theEffErr = inputHists[1][0].GetErrorY(iBin)
        inputHists[1][0].GetPoint(iBin,xValue,theEff)
        #print iBin, xValue, theEff
        denHist.SetBinContent(denHist.FindBin(xValue), theEff)
        denHist.SetBinError(denHist.FindBin(xValue), theEffErr)

    histRatio = makeBayesLikeRatio(num = numHist,   den = denHist, histForXBarycenterCalc=histForXBarycenterCalc)

    #
    #  legend
    #
    if not leg:
        legInfo = []
        yWidth = 0
        for hInfo in inputHists:
            yWidth += 0.06
            print hInfo[1]
            legInfo.append((hInfo[0],"#scale[0.7]]{"+hInfo[1]+"}","LP"))
        #leg = getLegend([(effHist,"#scale[0.7]]{Data}","PE"),(effHistMC,"#scale[0.7]{t#bar{t} MC}","PE")],  xStart=0.2, xWidth=0.3, yStart=0.6, yWidth=0.16)
        leg = getLegend(legInfo,  xStart=xLeg, xWidth=0.3, yStart=yLeg-yWidth, yWidth=yWidth)
        leg.Draw("same")
        

    #
    #  CMS Text
    #
    cmsLines = getCMSText(xStart=0.2,yStart=0.86,subtext=cmsText,lumiText=lumiText,xLumiStart=0.7,yLumiStart=0.94)
    for cmsl in cmsLines:
        cmsl.Draw("same")


    #
    #  Other Text
    #
    if otherText:
        drawText(otherText,textsize=0.05,xStart=xStartOther,yStart=yStartCurrent)



    bottom_pad.cd()
    bottom_pad.SetTopMargin(2*axissep)
    bottom_pad.SetBottomMargin(canvas.GetBottomMargin()*1.0/split)
    bottom_pad.SetRightMargin(canvas.GetRightMargin())
    bottom_pad.SetLeftMargin(canvas.GetLeftMargin());
    bottom_pad.SetFillStyle(0) # transparent
    bottom_pad.SetBorderSize(0)

    ratio_axis = inputHists[0][0].GetHistogram().Clone()
    ratio_axis.GetXaxis().SetRangeUser(xMin, xMax)
    ratio_axis.GetYaxis().SetTitle("Data/MC")
    ratio_axis.GetXaxis().SetTitle(hInfo[0].GetXaxis().GetTitle())
    ratio_axis.GetYaxis().SetNdivisions(507)
    rMin = 0.5
    rMax = 1.5
    ratio_axis.GetYaxis().SetRangeUser(rMin, rMax)
    histRatio.GetYaxis().SetRangeUser(rMin, rMax)
    histRatio.GetYaxis().SetTitle(rTitle)
    
    ratio_axis.Draw("axis")
    if isinstance(histRatio, ROOT.TGraphAsymmErrors):
        histRatio.Draw("PE")
    else:
        histRatio.Draw("PE same")
        histRatio.Draw("PE same")
        oldSize = histRatio.GetMarkerSize()
        histRatio.SetMarkerSize(0)
        histRatio.DrawCopy("same e0")
        histRatio.SetMarkerSize(oldSize)
        histRatio.Draw("PE same")

    line = ROOT.TLine()
    line.DrawLine(hInfo[0].GetXaxis().GetXmin(), 1.0, hInfo[0].GetXaxis().GetXmax(), 1.0)


    ndivs=[505,503]

    pads = [top_pad, bottom_pad]
    factors = [0.8/(1.0-split), 0.7/split]
    for i_pad, pad in enumerate(pads):

        factor = factors[i_pad]
        ndiv   = ndivs[i_pad]
        
        prims = [ p.GetName() for p in pad.GetListOfPrimitives() ]
        
        #
        #  Protection for scaling hists multiple times
        #
        procedHist = []
        
        for pName in prims:
            
            if pName in procedHist: continue
            procedHist.append(pName)
        
            h = pad.GetPrimitive(pName)
            if isinstance(h, ROOT.TH1) or isinstance(h, ROOT.THStack) or isinstance(h, ROOT.TGraph) or isinstance(h, ROOT.TGraphErrors) or isinstance(h, ROOT.TGraphAsymmErrors):
                if isinstance(h, ROOT.TGraph) or isinstance(h, ROOT.THStack) or isinstance(h, ROOT.TGraphErrors) or isinstance(h, ROOT.TGraphAsymmErrors):
                    h = h.GetHistogram()
                #print "factor is",factor,h.GetName(),split
        
                if i_pad == 1:
                    h.SetLabelSize(h.GetLabelSize('Y')*factor, 'Y')
                    h.SetTitleSize(h.GetTitleSize('X')*factor, 'X')
                    h.SetTitleSize(h.GetTitleSize('Y')*factor, 'Y')
                    h.SetTitleOffset(h.GetTitleOffset('Y')/factor, 'Y')
                    
                if i_pad == 1:
                    h.GetYaxis().SetNdivisions(ndiv)
                h.GetXaxis().SetNdivisions()                
                if i_pad == 0:
                    h.SetLabelSize(0.0, 'X')
                    h.GetXaxis().SetTitle("")
                else:
                    h.SetLabelSize(h.GetLabelSize('X')*factor, 'X')
                    ## Trying to remove overlapping y-axis labels.  Doesn't work.
                    # h.GetYaxis().Set(4, h.GetYaxis().GetXmin(), h.GetYaxis().GetXmax()) 
                    # h.GetYaxis().SetBinLabel( h.GetYaxis().GetLast(), '')




    canvas.SaveAs(outDir+"/"+name+".pdf")
def drawComp(name,inputHists,yTitle,xTitle,outDir,otherText="",setLogy=1,yMax= 1,leg="",xMax=1,xMin = -0.2,yLeg=0.76,xLeg=0.2,xStartOther=0.5, yStartOther=0.9, doFit = False,cmsText="Preliminary", lumiText="",xLumiStart=0.7):




    canvas = makeCanvas(name, name)#, width=800, height=600)

    if isinstance(inputHists[0][0],ROOT.TGraphAsymmErrors):
        ratio_axis = inputHists[0][0].GetHistogram()
    else:
        ratio_axis = inputHists[0][0].Clone()
    ratio_axis.GetYaxis().SetTitle(yTitle)
    ratio_axis.GetXaxis().SetTitle(xTitle)
    ratio_axis.GetYaxis().SetNdivisions(507)
    yMin = 0
    
    ratio_axis.GetYaxis().SetRangeUser(yMin, yMax)
    print xMin,"to",xMax
    ratio_axis.GetXaxis().SetRangeUser(xMin, xMax)
    ratio_axis.Draw("axis")

        

    for hInfoIndx, hInfo  in enumerate(inputHists):
        #hInfo[0].GetYaxis().SetRangeUser(yMin, yMax)
        #hInfo[0].GetXaxis().SetRangeUser(xMin, xMax)
        hInfo[0].SetLineColor  (hInfo[2])
        hInfo[0].SetMarkerColor(hInfo[2])
        if len(hInfo) > 3:
            hInfo[0].SetMarkerStyle(hInfo[3])
            hInfo[0].SetFillStyle(hInfo[3])
        #hInfo[0].SetMarkerStyle(0)
        if hInfoIndx:
            if isinstance(inputHists[0][0],ROOT.TGraphAsymmErrors):
                hInfo[0].Draw("PE same")    
            else:
                hInfo[0].Draw("same")    
        else:
            if isinstance(inputHists[0][0],ROOT.TGraphAsymmErrors):
                hInfo[0].Draw("PE")


                if doFit:
                    xAve = (ratio_axis.GetXaxis().GetXmin() + ratio_axis.GetXaxis().GetXmax()) /2
                    xmin = max(30,ratio_axis.GetXaxis().GetXmin())
                    print "Setting Range",xmin, ratio_axis.GetXaxis().GetXmax()
                    sigmoid = ROOT.TF1("func", "(1.0/(1+ TMath::Exp(-[0]*(x-[1]))))", xmin, ratio_axis.GetXaxis().GetXmax()) 
                    sigmoid.SetParameters(0.01, xAve)
                    inputHists[0][0].Fit(sigmoid)
                    sigmoid.Draw("same")
                    
                    print hInfo[0].GetName(),":",
                    print sigmoid.GetParameter(0),
                    print sigmoid.GetParameter(1)
                    
                    textFits = []
                    for i in range(2):
                        yStartFit = 0.3-0.04*i
                        textFits.append(ROOT.TLatex(0.7, yStartFit, "p"+str(i)+" = "+str(round(sigmoid.GetParameter(i),3))))
                        textFits[-1].SetTextFont(42)
                        textFits[-1].SetTextSize(0.04)
                        textFits[-1].SetNDC()
                        textFits[-1].Draw("same")
                    


            else:
                hInfo[0].Draw("same")

                if doFit:
                    xAve = (ratio_axis.GetXaxis().GetXmin() + ratio_axis.GetXaxis().GetXmax()) /2
                    xmin = max(30,ratio_axis.GetXaxis().GetXmin())
                    print "Setting Range",xmin, ratio_axis.GetXaxis().GetXmax()
                    sigmoid = ROOT.TF1("func", "(1.0/(1+ TMath::Exp(-[0]*(x-[1]))))", xmin, ratio_axis.GetXaxis().GetXmax()) 
                    sigmoid.SetParameters(0.01, xAve)
                    inputHists[0][0].Fit(sigmoid,"q")
                    sigmoid.SetLineStyle(ROOT.kDashed)
                    sigmoid.SetLineColor(ROOT.kRed)
                    sigmoid.Draw("same")
                    
                    print hInfo[0].GetName(),":",
                    print sigmoid.GetParameter(0),
                    print sigmoid.GetParameter(1)
                    
                    textFits = []
                    for i in range(2):
                        yStartFit = 0.3-0.04*i
                        textFits.append(ROOT.TLatex(0.7, yStartFit, "p"+str(i)+" = "+str(round(sigmoid.GetParameter(i),3))))
                        textFits[-1].SetTextFont(42)
                        textFits[-1].SetTextSize(0.04)
                        textFits[-1].SetNDC()
                        textFits[-1].Draw("same")



            
    #effHistMC.Draw("PE same")

    
    #
    #  legend
    #
    if not leg:
        legInfo = []
        yWidth = 0
        for hInfo in inputHists:
            yWidth += 0.06
            print hInfo[1]
            legInfo.append((hInfo[0],"#scale[0.7]]{"+hInfo[1]+"}","LP"))
        #leg = getLegend([(effHist,"#scale[0.7]]{Data}","PE"),(effHistMC,"#scale[0.7]{t#bar{t} MC}","PE")],  xStart=0.2, xWidth=0.3, yStart=0.6, yWidth=0.16)
        leg = getLegend(legInfo,  xStart=xLeg, xWidth=0.3, yStart=yLeg-yWidth, yWidth=yWidth)
        leg.Draw("same")

    if leg == "special":
        hForLeg_Data = inputHists[0][0].Clone("leg_Data")
        hForLeg_Data.SetLineColor(ROOT.kBlack)
        hForLeg_Data.SetMarkerColor(ROOT.kBlack)
        legInfo = []
        legInfo.append((hForLeg_Data,"#scale[0.7]]{Data}","LP"))
        legData = getLegend(legInfo,  xStart=0.175, xWidth=0.3, yStart=0.76-0.08, yWidth=0.08)
        legData.Draw("same")

        hForLeg_MC = inputHists[0][0].Clone("leg_MC")
        hForLeg_MC.SetLineColor(ROOT.kBlack)
        hForLeg_MC.SetMarkerColor(ROOT.kBlack)
        hForLeg_MC.SetMarkerStyle(24)
        legInfo = []
        legInfo.append((hForLeg_MC,"#scale[0.7]]{MC  }","LP"))
        legMC = getLegend(legInfo,  xStart=0.3, xWidth=0.3, yStart=0.76-0.08, yWidth=0.08)
        legMC.Draw("same")

        textLoose = ROOT.TLatex(0.2, 0.77, "Loose")
        textLoose.SetTextFont(42)
        textLoose.SetTextSize(0.04)
        textLoose.SetTextColor(ROOT.kBlue)
        textLoose.SetNDC()
        textLoose.Draw("same")

        textMedium = ROOT.TLatex(0.3, 0.77, "Medium")
        textMedium.SetTextFont(42)
        textMedium.SetTextSize(0.04)
        textMedium.SetTextColor(ROOT.kGreen+1)
        textMedium.SetNDC()
        textMedium.Draw("same")

        textTight = ROOT.TLatex(0.43, 0.77, "Tight")
        textTight.SetTextFont(42)
        textTight.SetTextSize(0.04)
        textTight.SetTextColor(ROOT.kRed)
        textTight.SetNDC()
        textTight.Draw("same")
        

    #
    #  CMS Text
    #
    cmsLines = getCMSText(xStart=0.2,yStart=0.875,subtext=cmsText,lumiText=lumiText,xLumiStart=xLumiStart,yLumiStart=0.96)
    for cmsl in cmsLines:
        cmsl.Draw("same")

    if otherText:
        labels = drawText(otherText,textsize=0.05,xStart=xStartOther,yStart=yStartOther)


    canvas.SaveAs(outDir+"/"+name+".pdf")
Example #5
0
def plot_shared_axis(top_hists, bottom_hists, name='', split=0.5, **kw):

    # options with defaults
    axissep = kw.get('axissep', 0.0)
    ndivs = kw.get('ndivs', [503, 503])
    rLabel = kw.get("rlabel", "Ratio")
    rMin = kw.get("rMin", 0)
    rMax = kw.get("rMax", 2)
    bayesRatio = kw.get('bayesRatio', False)

    canvas = makeCanvas(name, name, width=600, height=600)
    top_pad = ROOT.TPad("pad1", "The pad 80% of the height", 0, split, 1, 1, 0)
    bottom_pad = ROOT.TPad("pad2", "The pad 20% of the height", 0, 0, 1, split,
                           0)
    top_pad.Draw()
    bottom_pad.Draw()

    top_pad.cd()
    top_pad.SetLogy(kw.get('logy', False))
    top_pad.SetTopMargin(canvas.GetTopMargin() * 1.0 / (1.0 - split))
    top_pad.SetBottomMargin(0.5 * axissep)
    top_pad.SetRightMargin(canvas.GetRightMargin())
    top_pad.SetLeftMargin(canvas.GetLeftMargin())
    top_pad.SetFillStyle(0)  # transparent
    top_pad.SetBorderSize(0)
    plot_hist_list(top_hists, **kw)

    bottom_pad.cd()
    bottom_pad.SetTopMargin(2 * axissep)
    bottom_pad.SetBottomMargin(canvas.GetBottomMargin() * 1.0 / split)
    bottom_pad.SetRightMargin(canvas.GetRightMargin())
    bottom_pad.SetLeftMargin(canvas.GetLeftMargin())
    bottom_pad.SetFillStyle(0)  # transparent
    bottom_pad.SetBorderSize(0)
    ratio_axis = top_hists[0].Clone()
    ratio_axis.GetYaxis().SetTitle(rLabel)
    ratio_axis.GetXaxis().SetTitle(top_hists[0].GetXaxis().GetTitle())
    ratio_axis.GetYaxis().SetNdivisions(507)
    ratio_axis.GetYaxis().SetRangeUser(rMin, rMax)
    bottom_hists.GetYaxis().SetRangeUser(rMin, rMax)
    bottom_hists.GetYaxis().SetTitle(rLabel)

    if bayesRatio:
        ratio_axis.Draw("axis")
        bottom_hists.Draw("PE")
        ratio_axis.Draw("axis same")
    else:
        bottom_hists.Draw("PE")
        if ("sys_band" in kw) and (not kw["sys_band"] == None):
            kw["sys_band"].Draw("E2 same")
        bottom_hists.Draw("PE same")
        oldSize = bottom_hists.GetMarkerSize()
        bottom_hists.SetMarkerSize(0)
        bottom_hists.DrawCopy("same e0")
        # bottom_hists.SetMarkerSize(oldSize)
        bottom_hists.SetMarkerSize(0.5)
        bottom_hists.Draw("PE same")

    line = ROOT.TLine()
    line.DrawLine(top_hists[0].GetXaxis().GetXmin(), 1.0,
                  top_hists[0].GetXaxis().GetXmax(), 1.0)

    pads = [top_pad, bottom_pad]
    factors = [0.8 / (1.0 - split), 0.7 / split]
    for i_pad, pad in enumerate(pads):

        factor = factors[i_pad]
        ndiv = ndivs[i_pad]

        prims = [p.GetName() for p in pad.GetListOfPrimitives()]

        #
        #  Protection for scaling hists multiple times
        #
        procedHist = []

        for name in prims:

            if name in procedHist: continue
            procedHist.append(name)

            h = pad.GetPrimitive(name)
            if isinstance(
                    h, ROOT.TH1) or isinstance(h, ROOT.THStack) or isinstance(
                        h, ROOT.TGraph) or isinstance(
                            h, ROOT.TGraphErrors) or isinstance(
                                h, ROOT.TGraphAsymmErrors):
                if isinstance(h, ROOT.TGraph) or isinstance(
                        h, ROOT.THStack) or isinstance(
                            h, ROOT.TGraphErrors) or isinstance(
                                h, ROOT.TGraphAsymmErrors):
                    h = h.GetHistogram()
                #print "factor is",factor,h.GetName(),split

                if i_pad == 1:
                    h.SetLabelSize(h.GetLabelSize('Y') * factor, 'Y')
                    h.SetTitleSize(h.GetTitleSize('X') * factor, 'X')
                    h.SetTitleSize(h.GetTitleSize('Y') * factor, 'Y')
                    h.SetTitleOffset(h.GetTitleOffset('Y') / factor, 'Y')

                if i_pad == 1:
                    h.GetYaxis().SetNdivisions(ndiv)
                h.GetXaxis().SetNdivisions()
                if i_pad == 0:
                    h.SetLabelSize(0.0, 'X')
                    h.GetXaxis().SetTitle("")
                else:
                    h.SetLabelSize(h.GetLabelSize('X') * factor, 'X')
                    ## Trying to remove overlapping y-axis labels.  Doesn't work.
                    # h.GetYaxis().Set(4, h.GetYaxis().GetXmin(), h.GetYaxis().GetXmax())
                    # h.GetYaxis().SetBinLabel( h.GetYaxis().GetLast(), '')

    return {
        'canvas': canvas,
        'ratio_axis': ratio_axis,
        "top_pad": top_pad,
        "bottom_pad": bottom_pad
    }
Example #6
0
def doVarRatio(var,
               binning,
               xTitle,
               setLogy=1,
               minX=None,
               maxX=None,
               minY=None,
               etaRange=None):
    if o.doCaloJets:
        offLF = getHist(inFile, "offJets_matchedCalo_L", var, binning,
                        ROOT.kBlack)
        hltLF = getHist(inFile, "offJets_matchedCaloJet_L", var, binning,
                        ROOT.kBlack)
        offBQ = getHist(inFile, "offJets_matchedCalo_B", var, binning,
                        ROOT.kRed)
        hltBQ = getHist(inFile, "offJets_matchedCaloJet_B", var, binning,
                        ROOT.kRed)
    elif o.doPuppiJets:
        if etaRange:
            offLF = getHist(inFile, "offJets_matchedPuppi_L" + etaRange, var,
                            binning, ROOT.kBlack)
            hltLF = getHist(inFile, "offJets_matchedPuppiJet_L" + etaRange,
                            var, binning, ROOT.kBlack)
            offBQ = getHist(inFile, "offJets_matchedPuppi_B" + etaRange, var,
                            binning, ROOT.kRed)
            hltBQ = getHist(inFile, "offJets_matchedPuppiJet_B" + etaRange,
                            var, binning, ROOT.kRed)
        else:
            offLF = getHist(inFile, "offJets_matchedPuppi_L", var, binning,
                            ROOT.kBlack)
            hltLF = getHist(inFile, "offJets_matchedPuppiJet_L", var, binning,
                            ROOT.kBlack)
            offBQ = getHist(inFile, "offJets_matchedPuppi_B", var, binning,
                            ROOT.kRed)
            hltBQ = getHist(inFile, "offJets_matchedPuppiJet_B", var, binning,
                            ROOT.kRed)
    else:
        if etaRange:
            offLF = getHist(inFile, "offJets_matched_L" + etaRange, var,
                            binning, ROOT.kBlack)
            hltLF = getHist(inFile, "offJets_matchedJet_L" + etaRange, var,
                            binning, ROOT.kBlack)
            offBQ = getHist(inFile, "offJets_matched_B" + etaRange, var,
                            binning, ROOT.kRed)
            hltBQ = getHist(inFile, "offJets_matchedJet_B" + etaRange, var,
                            binning, ROOT.kRed)
        else:
            offLF = getHist(inFile, "offJets_matched_L", var, binning,
                            ROOT.kBlack)
            hltLF = getHist(inFile, "offJets_matchedJet_L", var, binning,
                            ROOT.kBlack)
            offBQ = getHist(inFile, "offJets_matched_B", var, binning,
                            ROOT.kRed)
            hltBQ = getHist(inFile, "offJets_matchedJet_B", var, binning,
                            ROOT.kRed)

    maxY = max(offLF.GetMaximum(), offBQ.GetMaximum(), hltLF.GetMaximum(),
               hltBQ.GetMaximum())
    if setLogy:
        offLF.SetMaximum(4e0 * maxY)
        offLF.SetMinimum(1.01e-5)
    else:
        offLF.SetMaximum(1.2 * maxY)

    if not minY == None:
        offLF.SetMinimum(minY)

    offLF.GetYaxis().SetTitle("Simulated Tracks")
    offLF.GetXaxis().SetTitle(xTitle)

    if maxX:
        offLF.GetXaxis().SetRangeUser(minX, maxX)
        offBQ.GetXaxis().SetRangeUser(minX, maxX)
        hltLF.GetXaxis().SetRangeUser(minX, maxX)
        hltBQ.GetXaxis().SetRangeUser(minX, maxX)

    LFRatio = makeRatio(num=hltLF.Clone(), den=offLF.Clone())
    BQRatio = makeRatio(num=hltBQ.Clone(), den=offBQ.Clone())

    xpos = 0.2
    ypos = 0.07
    xwidth = 0.7
    ywidth = 0.1

    leg = ROOT.TLegend(xpos, ypos, xpos + xwidth, ypos + ywidth)
    leg.SetNColumns(2)
    leg.AddEntry(offBQ, "Offline tracks b-quark jets", "L")
    leg.AddEntry(offLF, "Offline tracks light-flavor jets", "L")
    leg.AddEntry(hltBQ, "HLT tracks b-quark jets", "PEL")
    leg.AddEntry(hltLF, "HLT tracks light-flavor jets", "PEL")

    canvas = makeCanvas(var, var, width=600, height=600)
    split = 0.3
    top_pad = ROOT.TPad("pad1", "The pad 80% of the height", 0, split, 1, 1, 0)
    bottom_pad = ROOT.TPad("pad2", "The pad 20% of the height", 0, 0, 1, split,
                           0)
    top_pad.Draw()
    bottom_pad.Draw()

    axissep = 0.02
    top_pad.cd()
    top_pad.SetLogy(setLogy)
    top_pad.SetTopMargin(canvas.GetTopMargin() * 1.0 / (1.0 - split))
    top_pad.SetBottomMargin(0.5 * axissep)
    top_pad.SetRightMargin(canvas.GetRightMargin())
    top_pad.SetLeftMargin(canvas.GetLeftMargin())
    top_pad.SetFillStyle(0)  # transparent
    top_pad.SetBorderSize(0)

    if var in maxDict.keys():
        offLF.GetXaxis().SetRangeUser(offLF.GetXaxis().GetXmin(), maxDict[var])

    offLF.Draw("hist")
    # hltLF.SetMarkerSize(0.75)
    hltLF.SetMarkerSize(0.5)
    #hltLF.SetMarkerStyle(21)
    hltLF.Draw("same pe")
    offBQ.Draw("hist same")
    hltBQ.SetMarkerSize(0.5)
    #hltBQ.SetMarkerStyle(21)
    hltBQ.Draw("same pe")
    leg.Draw("same")

    cmsLines = getCMSText(xStart=0.2, yStart=0.85, subtext=o.cmsText)
    for cmsl in cmsLines:
        cmsl.Draw("same")

    bottom_pad.cd()
    bottom_pad.SetTopMargin(2 * axissep)
    bottom_pad.SetBottomMargin(canvas.GetBottomMargin() * 1.0 / split)
    bottom_pad.SetRightMargin(canvas.GetRightMargin())
    bottom_pad.SetLeftMargin(canvas.GetLeftMargin())
    bottom_pad.SetFillStyle(0)  # transparent
    bottom_pad.SetBorderSize(0)
    ratio_axis = offLF.Clone()
    #ratio_axis.GetYaxis().SetTitle("PF to Calo")
    ratio_axis.GetYaxis().SetTitle("HLT to Offline")
    ratio_axis.GetXaxis().SetTitle(offLF.GetXaxis().GetTitle())
    ratio_axis.GetYaxis().SetNdivisions(507)
    rMin = 0
    rMax = 2

    if var in maxDict.keys():
        LFRatio.GetXaxis().SetRangeUser(LFRatio.GetXaxis().GetXmin(),
                                        maxDict[var])

    ratio_axis.GetYaxis().SetRangeUser(rMin, rMax)
    LFRatio.GetYaxis().SetRangeUser(rMin, rMax)
    #LFRatio.GetYaxis().SetTitle("Calo to Offline")
    #LFRatio.GetYaxis().SetTitle("PF to Calo")
    LFRatio.GetYaxis().SetTitle("HLT to Offline")

    LFRatio.Draw("PE")
    LFRatio.Draw("PE same")
    # oldSize = LFRatio.GetMarkerSize()
    oldSize = hltLF.GetMarkerSize()
    LFRatio.SetMarkerSize(0)
    LFRatio.DrawCopy("same e0")
    LFRatio.SetMarkerSize(oldSize)
    LFRatio.Draw("PE same")

    BQRatio.Draw("PE same")
    BQRatio.Draw("PE same")
    # oldSize = BQRatio.GetMarkerSize()
    oldSize = hltBQ.GetMarkerSize()
    BQRatio.SetMarkerSize(0)
    BQRatio.DrawCopy("same e0")
    BQRatio.SetMarkerSize(oldSize)
    BQRatio.Draw("PE same")

    line = ROOT.TLine()
    line.DrawLine(offLF.GetXaxis().GetXmin(), 1.0,
                  offLF.GetXaxis().GetXmax(), 1.0)

    ndivs = [505, 503]

    pads = [top_pad, bottom_pad]
    factors = [0.8 / (1.0 - split), 0.7 / split]
    for i_pad, pad in enumerate(pads):

        factor = factors[i_pad]
        ndiv = ndivs[i_pad]

        prims = [p.GetName() for p in pad.GetListOfPrimitives()]

        #
        #  Protection for scaling hists multiple times
        #
        procedHist = []

        for name in prims:

            if name in procedHist: continue
            procedHist.append(name)

            h = pad.GetPrimitive(name)
            if isinstance(
                    h, ROOT.TH1) or isinstance(h, ROOT.THStack) or isinstance(
                        h, ROOT.TGraph) or isinstance(
                            h, ROOT.TGraphErrors) or isinstance(
                                h, ROOT.TGraphAsymmErrors):
                if isinstance(h, ROOT.TGraph) or isinstance(
                        h, ROOT.THStack) or isinstance(
                            h, ROOT.TGraphErrors) or isinstance(
                                h, ROOT.TGraphAsymmErrors):
                    h = h.GetHistogram()
                #print "factor is",factor,h.GetName(),split

                if i_pad == 1:
                    h.SetLabelSize(h.GetLabelSize('Y') * factor, 'Y')
                    h.SetTitleSize(h.GetTitleSize('X') * factor, 'X')
                    h.SetTitleSize(h.GetTitleSize('Y') * factor, 'Y')
                    h.SetTitleOffset(h.GetTitleOffset('Y') / factor, 'Y')

                if i_pad == 1:
                    h.GetYaxis().SetNdivisions(ndiv)
                h.GetXaxis().SetNdivisions()
                if i_pad == 0:
                    h.SetLabelSize(0.0, 'X')
                    h.GetXaxis().SetTitle("")
                else:
                    h.SetLabelSize(h.GetLabelSize('X') * factor, 'X')
                    ## Trying to remove overlapping y-axis labels.  Doesn't work.
                    # h.GetYaxis().Set(4, h.GetYaxis().GetXmin(), h.GetYaxis().GetXmax())
                    # h.GetYaxis().SetBinLabel( h.GetYaxis().GetLast(), '')

    ##xatlas, yatlas = 0.18, 0.88
    ##atlas   = ROOT.TLatex(xatlas+0.01,   yatlas, "ATLAS")
    ###simulation = ROOT.TLatex(xatlas+0.11,   yatlas, "Simulation Internal")
    ##simulation = ROOT.TLatex(xatlas+0.11,   yatlas, "Simulation Preliminary")
    ##lumi    = ROOT.TLatex(xatlas+0.01,    yatlas-0.05, "#sqrt{s}=13 TeV, t#bar{t}")
    ##jetText = ROOT.TLatex(xatlas+0.02,   yatlas-0.1, "p_{T}^{jet} > 40 GeV, |#eta^{jet}| < 2.5" )
    ##wm      = [atlas, simulation, lumi, jetText]

    #watermarks = drawWaterMarks(wm)

    #varName = var.replace("tracks/","").replace("btags/","btags_")
    varName = var.replace("tracks/",
                          "track_").replace("btags/", "btag_").replace(
                              "btags_noV0/", "btag_noV0_")
    if etaRange:
        canvas.SaveAs(o.outDir + etaRange + "/" + varName + ".pdf")
        canvas.SaveAs(o.outDir + etaRange + "/" + varName + ".png")
    else:
        canvas.SaveAs(o.outDir + "/" + varName + ".pdf")
        canvas.SaveAs(o.outDir + "/" + varName + ".png")