示例#1
0
	def draw(self, log = False):
		self.setup_graphics()
		if log:
			self.c.SetLogy()

		for i in range(0, len(self.sequence)):
			if i == 0:
				self.hists[self.sequence[0]].Draw("MIN0 HIST E1")
			else:
				self.hists[self.sequence[i]].Draw("HIST E1 SAME")
		
		self.legend.Draw()
			
		if self.has_fit and self.draw_fit:
			self.func.Draw("same")
			
			doubling, oneday = print_slope(self.func)
			newpad = TPad("newpad","a transparent pad",0.15, 0.65, 0.4, 0.55);
			self.text = TPaveText(0.1, 0.1, 0.9, 0.9)
			self.text.AddText("Doubles every {} days".format(doubling))
			self.text.AddText("Multiplies by {} every day".format(oneday))
			newpad.SetFillStyle(4000);
			newpad.Draw()
			newpad.cd()
			self.text.Draw()
        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)
        pad2.SetTickx(0)
        pad2.SetTicky(0)

        pad1.Draw()
        pad2.Draw()

        oneLine = TF1("oneline", "1", -9e9, 9e9)
        oneLine.SetLineColor(kBlack)
        oneLine.SetLineWidth(1)
        oneLine.SetLineStyle(2)

        # errorband=stack.GetStack().Last().Clone("error")
    hist_mmtt_pt.SetFillColor(kRed)
    hist_mmtt_pt.SetLineColor(kRed)
    hist_mmtt_pt.SetFillStyle(3003)
    hist_mmtt_pt.Draw()
    c.SaveAs(region + "/mmtt_pt_histo_" + region + ".png")
    c.SaveAs(region + "/mmtt_pt_histo_" + region + ".root")

if args.nofit and args.nofitkk:

    ## Phi fitting

    kcanvas = TCanvas("kcanvas", "kcanvas", 1400, 800)

    pullpad = TPad("pullpad", "pullpad", 0.0, 0.05, 1.0, 0.33)
    plotpad = TPad("histopad", "histopad", 0.0, 0.35, 1.0, 1.0)
    plotpad.SetFillStyle(4004)
    pullpad.SetFillStyle(4004)
    plotpad.Draw()
    pullpad.Draw()

    traKFitData = theData.Clone("fitTrakData")

    if binnedfit:
        tt_mass.setBins(30)
        traKFitData = theData.binnedClone("binnedTrakData")

    phimean = 1.019
    gammavalue = 0.0012

    fitphimin = 1.00
    fitphimax = 1.04
示例#4
0
class CombinedResidualPlot(PlotBase):
    """"Plot residuals projected to radial and angular dimension.

    __init__: Initialize.
    draw: Draw the plots.
    """
    def __init__(self,
                 data,
                 model,
                 nbins=None,
                 maxr=None,
                 calcr=None,
                 calcphi=None,
                 skipzero=False,
                 fill=4954,
                 workinprogress=False):
        """Project residual histogram to one-dimensional plots."""
        PlotBase.__init__(self,
                          name='combinedRes',
                          fill=fill,
                          workinprogress=workinprogress)
        self._rad = RadialResidualPlot.create_residual(data,
                                                       model,
                                                       nbins=nbins,
                                                       maxr=maxr,
                                                       calcr=calcr,
                                                       skipzero=skipzero)
        self._ang = AngularResidualPlot.create_residual(data,
                                                        model,
                                                        nbins=nbins,
                                                        calcphi=calcphi,
                                                        skipzero=skipzero)
        self._rtitle = 'r [cm]'
        self._y1title = 'Pull'
        self._ptitle = '#phi [rad]'
        self._y2title = 'Pull'
        if maxr is None:
            self._rrange = None
        else:
            self._rrange = (0, maxr)
        self._prange = (-pi / 2, pi / 2)
        self._y1range = None
        self._y2range = None

    def SetName(self, name):
        PlotBase.SetName(self, name)
        self._rad.SetName('{0}_rad'.format(name))
        self._ang.SetName('{0}_ang'.format(name))

    def draw(self, canvas=None):
        if canvas is None:
            canvas = self
        canvas.Divide(1, 2)
        canvas.cd(1).SetMargin(0.1, 0.1, 0.05, 0.2)
        self._rad.Draw()
        canvas.cd(2).SetMargin(0.1, 0.1, 0.2, 0.05)
        self._ang.Draw()
        canvas.cd()
        canvas.Update()
        for c, axis in [('r', self._rad.GetXaxis()),
                        ('y1', self._rad.GetYaxis()),
                        ('p', self._ang.GetXaxis()),
                        ('y2', self._ang.GetYaxis())]:
            axis.SetLabelSize(0.05)
            axis.SetTitleSize(0.07)
            axis.SetLabelOffset(0.01)
            rng = getattr(self, '_{0}range'.format(c))
            if rng is not None:
                axis.SetRangeUser(rng[0], rng[1])
            ttl = getattr(self, '_{0}title'.format(c))
            if c.startswith('y') and ttl is not None:
                axis.SetTitle(ttl)
            if c.startswith('y'):
                axis.SetTitleOffset(0.6)
                axis.SetNdivisions(505)
        canvas.cd()
        self._pad = TPad('newpad', '', 0, 0, 1, 1)
        self._pad.SetFillStyle(4000)
        self._pad.Draw()
        self._pad.cd()
        if self._drawCMS:
            self.draw_cms()
        text = TLatex()
        text.SetNDC()
        text.SetTextFont(42)
        text.SetTextSize(0.035)
        text.SetTextAlign(13)
        text.SetTextAngle(90)
        if self._rtitle is not None:
            text.DrawLatexNDC(0.905, 0.54, self._rtitle)
        if self._ptitle is not None:
            text.DrawLatexNDC(0.905, 0.115, self._ptitle)
        for obj in self._container_draw:
            obj.Draw('SAME')
        for c in (canvas.cd(1), canvas.cd(2), canvas):
            c.Modified()
            c.Update()
        canvas.cd()
    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()

    parsBkg = background.getParameters(roohistBkg)
示例#6
0
			lm = c.GetLeftMargin()
			rm = c.GetRightMargin()
			to = c.GetTopMargin()
			x1 = p.GetXaxis().GetXmin()
			yf = p.GetYaxis().GetXmin()
			x2 = p.GetXaxis().GetXmax()
			y2 = p.GetYaxis().GetXmax()

			Xa = (x2-x1)/(1-lm-rm)-(x2-x1)
			Ya = (y2-yf)/(1-bm-to)-(y2-yf)
			LM = Xa*(lm/(lm+rm))
			RM = Xa*(rm/(lm+rm))
			BM = Ya*(bm/(bm+to))
			TM = Ya*(to/(bm+to))
			null2 = TPad("null2","",0,0,1,1)
			null2.SetFillStyle(0)
			null2.SetFrameFillStyle(0)
			null2.Draw()
			null2.cd()
			null2.Range(x1-LM,yf-BM,x2+RM,y2+TM)
			null2.SetRightMargin(0.20)
			null2.SetLeftMargin(margine)
			null2.SetTopMargin(0.10)
			null2.SetBottomMargin(margine)
			#exclusion.SetMinimum(the_minimum)
			#exclusion.SetMaximum(the_maximum)
			exclusion.GetXaxis().SetRangeUser(-0.05,1.05)
			exclusion.GetYaxis().SetRangeUser(-0.05,1.05)
			exclusion.GetXaxis().SetLabelOffset(100)
			exclusion.GetYaxis().SetLabelOffset(100)
			#exclusion.Draw('CONT3')
    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()
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()
示例#9
0
def write_rootdategraph_plusatten(vectorx, vectory, vectory2, graphtitle,
                                  xtitle, ytitle, rootdirectory):
    '''plot graph current + source'''

    arrayx = array('d')
    arrayy = array('d')
    arrayy2 = array('d')

    for x in vectorx:
        arrayx.append(x.Convert())

    for y in vectory:
        arrayy.append(y)

    for y2 in vectory2:
        arrayy2.append(y2)

    if ytitle[0] == "i":
        ytitle = ytitle + " (uA) "
        color = 2
        offset = 1.
        minimum = -1
        maximum = int(np.max(vectory) + 1.5)
        if maximum > 10:
            maximum = int(10)

    if ytitle == "v":
        ytitle = ytitle + " (V)"
        color = 4
        offset = 0.9
        minimum = 400
        maximum = 600
    c = TCanvas(graphtitle + "_canvas")
    pad1 = TPad("pad1", "", 0, 0, 1, 1)
    pad2 = TPad("pad2", "", 0, 0, 1, 1)
    pad2.SetFillStyle(4000)
    pad2.SetFrameFillStyle(0)

    #How many graph points
    n = len(vectorx)

    MyTGraph = TGraph(n, arrayx, arrayy)
    MyTGraph.SetName(graphtitle)

    MyTGraph2 = TGraph(n, arrayx, arrayy2)

    #Draw + DrawOptions

    Style = gStyle
    Style.SetPadLeftMargin(2.0)
    XAxis = MyTGraph.GetXaxis()  #TGraphfasthescin
    XAxis.SetTimeDisplay(1)
    XAxis.SetTimeFormat("#splitline{%d/%m}{%H:%M}")
    XAxis.SetLabelOffset(0.025)
    MyTGraph.SetMarkerColor(color)
    MyTGraph.SetMarkerStyle(1)
    MyTGraph.SetMarkerSize(1)
    MyTGraph.SetLineColor(color)
    MyTGraph.SetTitle(graphtitle + " V")
    #XAxis.SetTitle(xtitle)
    YAxis = MyTGraph.GetYaxis()
    YAxis.SetTitleOffset(offset)
    YAxis.SetTitleOffset(offset)
    YAxis.SetTitleColor(2)
    YAxis.SetTitle(ytitle)
    MyTGraph.GetHistogram().SetMinimum(-1.)
    MyTGraph.GetHistogram().SetMaximum(
        23.)  #modified to have also attenuation 22 displayed
    #MyTGraph.Draw("APL")
    MyTGraph2.SetMarkerColor(4)
    MyTGraph2.SetMarkerStyle(1)
    MyTGraph2.SetMarkerSize(1)
    MyTGraph2.SetLineColor(4)
    MyTGraph2.SetLineStyle(7)
    MyTGraph2.GetHistogram().SetMinimum(-1.)
    MyTGraph2.GetHistogram().SetMaximum(23.)
    MyTGraph2.GetXaxis().SetLabelSize(0)
    MyTGraph2.GetXaxis().SetNdivisions(0)
    MyTGraph2.GetYaxis().SetTitle("Attenuation factor")
    MyTGraph2.GetYaxis().SetTitleOffset(offset)
    MyTGraph2.GetYaxis().SetTitleColor(4)
    MyTGraph2.SetTitle("")

    pad1.Draw()
    pad1.cd()
    MyTGraph.Draw("APL")

    pad2.Draw()
    pad2.cd()
    #MyTGraph2.SetMarkerColor(4)
    MyTGraph2.Draw("APLY+")
    #MyTGraph2.Draw("same")

    rootdirectory.WriteTObject(c)
    #MyTGraph.Write(graphtitle)
    #MyTGraph.Draw("APL")
    if "D" not in graphtitle:
        c.SaveAs("GIF-" + graphtitle[0:9] + ".pdf")
    gPad.Close()
    h_signal_2017.SetMarkerStyle(20)
    h_signal_2017.SetMarkerColor(2)
    h_signal_2018.SetMarkerStyle(20)
    h_signal_2018.SetMarkerColor(1)
    h_signal_2016.GetXaxis().SetLabelOffset(999)
    h_signal_2016.GetXaxis().SetTitle("#it{m}_{#pi#gamma} (GeV)")
    h_signal_2016.GetYaxis().SetTitle("Events")
    h_signal_2016.Draw()
    h_signal_2017.Draw("SAME")
    h_signal_2018.Draw("SAME")
    legend_years.Draw("SAME")

    pad2.cd()
    pad2.SetTopMargin(0.03)
    pad2.SetFillColor(0)
    pad2.SetFillStyle(0)

    for entry in h_ratio_list:
        h_ratio_hists[entry].SetTitle("")
        h_ratio_hists[entry].SetMarkerStyle(8)
        h_ratio_hists[entry].SetLineColor(1)
        h_ratio_hists[entry].GetYaxis().SetLabelSize(0.1)
        h_ratio_hists[entry].GetYaxis().SetTitle("Ratio")
        h_ratio_hists[entry].GetYaxis().SetTitleSize(0.12)
        #h_ratio_hists[entry].GetYaxis().SetTitleOffset(0.98)
        h_ratio_hists[entry].GetYaxis().SetTitleOffset(0.25)
        h_ratio_hists[entry].GetYaxis().SetRangeUser(0.5, 1.5)
        h_ratio_hists[entry].GetYaxis().SetNdivisions(502, kFALSE)
        h_ratio_hists[entry].GetXaxis().SetLabelSize(0.10)
        h_ratio_hists[entry].GetXaxis().SetLabelOffset(0.03)
        h_ratio_hists[entry].GetXaxis().SetTitleSize(0.12)
示例#11
0
def PlotRatio(h_reco_unfolded,h_ptcl_or,h_reco_unfolded_roof, h_reco_unfolded_svd, h_reco_unfolded_T,h_reco_unfolded_Ids, svd_par, Ids_par ,outputname="test.png"):
    
    gStyle.SetPadLeftMargin(0.12)
    gStyle.SetPadRightMargin(0.12)
    c = TCanvas("canvas_"+outputname,"canvas_"+outputname,0,0,800, 800)
    c.cd()
    pad1 = TPad("pad1","pad1",0,0.40,1,1)
    pad1.SetTopMargin(0.15)
    pad1.SetBottomMargin(0.01)
    pad1.SetFillStyle(0)
    pad1.SetTicks(1,1)
    pad1.SetBorderMode(0)
    pad1.Draw()
    c.cd()
    pad2 = TPad("pad2","pad2",0,0.01,1,0.422)
    pad2.SetFillStyle(0)
    pad2.SetTopMargin(0.043)
    pad2.SetBottomMargin(0.2)
    pad2.SetBorderMode(0)
    pad2.SetTicks(1,1)
    pad2.Draw()
    pad2.Modified()
    c.cd()
    pad1.cd()
    gStyle.SetOptStat(0)
    h_ptcl_or.SetTitle("")
    h_ptcl_or.SetLineColor(2)
    #h_ptcl_or.GetYaxis().SetRangeUser(0,h_ptcl_or.GetMaximum()*1.5)
    h_ptcl_or.GetXaxis().SetTitleSize(34)
    h_ptcl_or.GetXaxis().SetTitleFont(43)
    h_ptcl_or.GetYaxis().SetTitleSize(27)
    h_ptcl_or.GetYaxis().SetTitleFont(43)
    h_ptcl_or.GetYaxis().SetTitleOffset(1.5)
    h_ptcl_or.GetYaxis().SetTitle("Events")
    h_ptcl_or.GetYaxis().SetLabelFont(43)
    h_ptcl_or.GetYaxis().SetLabelSize(25)
    legend = TLegend(0.55,0.5,0.85,0.8)
    legend.SetFillStyle(0)
    legend.AddEntry(h_ptcl_or,"Simulation")
    legend.AddEntry(h_reco_unfolded,"Fully Bayesian Unfolding","p")
    legend.AddEntry(h_reco_unfolded_roof,"D'Agostini RooUnfold, par. 4","p")
    legend.AddEntry(h_reco_unfolded_svd,"SVD RooUnfold, par. " + str(svd_par),"p")
    legend.AddEntry(h_reco_unfolded_T,"T RooUnfold","p")
    legend.AddEntry(h_reco_unfolded_Ids,"Ids RooUnfold, par. " + str(Ids_par),"p")
    legend.SetBorderSize(0)
    h_reco_unfolded.SetLineColor(1)
    h_reco_unfolded.SetMarkerColor(1)
    h_reco_unfolded.SetMarkerStyle(22)
    h_reco_unfolded_roof.SetMarkerColor(6)
    h_reco_unfolded_roof.SetLineColor(6)
    h_reco_unfolded_roof.SetMarkerStyle(20)
    h_reco_unfolded_svd.SetMarkerColor(4)
    h_reco_unfolded_svd.SetLineColor(4)
    h_reco_unfolded_svd.SetMarkerStyle(5)
    h_reco_unfolded_T.SetMarkerColor(7)
    h_reco_unfolded_T.SetLineColor(7)
    h_reco_unfolded_T.SetMarkerStyle(34)
    h_reco_unfolded_Ids.SetMarkerColor(8)
    h_reco_unfolded_Ids.SetLineColor(8)
    h_reco_unfolded_Ids.SetMarkerStyle(3)
    h_ptcl_or.Draw("hist")
    h_reco_unfolded.Draw("same p x0")
    h_reco_unfolded_roof.Draw("same p x0")
    h_reco_unfolded_svd.Draw("same p x0")
    h_reco_unfolded_T.Draw("same p x0")
    h_reco_unfolded_Ids.Draw("same p x0")
    legend.Draw("same")
    pad1.RedrawAxis()
    pad2.cd()
    h_ptcl_or_clone = h_ptcl_or.Clone(h_ptcl_or.GetName()+"_clone")
    h_reco_unfolded_clone = h_reco_unfolded.Clone(h_reco_unfolded.GetName()+"_clone")
    h_reco_unfolded_roof_clone = h_reco_unfolded_roof.Clone(h_reco_unfolded_roof.GetName()+"_clone")
    h_reco_unfolded_svd_clone = h_reco_unfolded_svd.Clone(h_reco_unfolded_svd.GetName()+"_clone")
    h_reco_unfolded_T_clone = h_reco_unfolded_T.Clone(h_reco_unfolded_T.GetName()+"_clone")
    h_reco_unfolded_Ids_clone = h_reco_unfolded_Ids.Clone(h_reco_unfolded_Ids.GetName()+"_clone")
    h_ptcl_or_clone.Divide(h_ptcl_or)
    h_reco_unfolded_clone.Divide(h_ptcl_or)
    h_reco_unfolded_roof_clone.Divide(h_ptcl_or)
    h_reco_unfolded_svd_clone.Divide(h_ptcl_or)
    h_reco_unfolded_T_clone.Divide(h_ptcl_or)
    h_reco_unfolded_Ids_clone.Divide(h_ptcl_or)
    
    h_ptcl_or_clone.GetXaxis().SetTitleSize(27)
    h_ptcl_or_clone.GetXaxis().SetTitleFont(43)
    h_ptcl_or_clone.GetYaxis().SetTitleSize(27)
    h_ptcl_or_clone.GetYaxis().SetTitleFont(43)
    
    h_ptcl_or_clone.GetXaxis().SetLabelFont(43)
    h_ptcl_or_clone.GetXaxis().SetLabelSize(25)
    h_ptcl_or_clone.GetYaxis().SetLabelFont(43)
    h_ptcl_or_clone.GetYaxis().SetLabelSize(25)
    
    h_ptcl_or_clone.SetMaximum(1.3)
    h_ptcl_or_clone.SetMinimum(0.7)
    
    h_ptcl_or_clone.GetXaxis().SetTitleOffset(2.5)
    h_ptcl_or_clone.GetXaxis().SetTitle(args.title)
    
    h_ptcl_or_clone.GetYaxis().SetTitle("#frac{Unfolded}{Simulation}      ")
    h_ptcl_or_clone.Draw("hist")
    h_reco_unfolded_clone.Draw("same p x0")
    h_reco_unfolded_roof_clone.Draw("same p x0")
    h_reco_unfolded_svd_clone.Draw("same p x0")
    h_reco_unfolded_T_clone.Draw("same p x0")
    h_reco_unfolded_Ids_clone.Draw("same p x0")
    pad2.RedrawAxis()
    c.Update()
    histograms.append(c) # here is the crash probably
    PrintCan(c, outputname)
示例#12
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')
示例#13
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...")
示例#14
0
   		rm = c.GetRightMargin()
   		to = c.GetTopMargin()
   		x1 = p.GetXaxis().GetXmin()
   		yf = p.GetYaxis().GetXmin()
   		x2 = p.GetXaxis().GetXmax()
   		y2 = p.GetYaxis().GetXmax()

   		Xa = (x2-x1)/(1-lm-rm)-(x2-x1)
   		Ya = (y2-yf)/(1-bm-to)-(y2-yf)
   		LM = Xa*(lm/(lm+rm))
   		RM = Xa*(rm/(lm+rm))
   		BM = Ya*(bm/(bm+to))
   		TM = Ya*(to/(bm+to))

		null2 = TPad("null2","",0,0,1,1)
   		null2.SetFillStyle(0)
   		null2.SetFrameFillStyle(0)
   		null2.Draw()
   		null2.cd()
   		null2.Range(x1-LM,yf-BM,x2+RM,y2+TM)
   		null2.SetRightMargin(0.20)
		null2.SetLeftMargin(margine)
		null2.SetTopMargin(0.10)
		null2.SetBottomMargin(margine)
		#exclusion.SetMinimum(the_minimum)
		#exclusion.SetMaximum(the_maximum)
		exclusion.GetXaxis().SetRangeUser(0,1)
		exclusion.GetYaxis().SetRangeUser(0,1)
		exclusion.GetXaxis().SetLabelOffset(100)
		exclusion.GetYaxis().SetLabelOffset(100)
		if tipo=='obs':
示例#15
0
                hxE.Fill(x, E)
    if (Nevents % Nprint == 0): print("Done %g out of %g" % (Nevents, Ntotal))
    if (Nevents == Nmax): break
    Nevents += 1

##################################################################

fOut = TFile(fr + "all.root", "RECREATE")
fOut.cd()

cnv = TCanvas("cnv_xyzE", "", 1000, 1000)
cnv.Divide(2, 1)
cnv.cd(1)
pad1 = TPad("pad1", "", 0, 0, 1, 1)
pad2 = TPad("pad2", "", 0, 0, 1, 1)
pad2.SetFillStyle(4000)  # will be transparent
pad1.Draw()
pad1.cd()
pad1.SetTicks(1, 1)
pad1.SetLogz()
pad1.SetGridy()
pad1.SetGridx()
hxz.SetTitle(ptitle + " for #it{B} = " + btitle)
hxz.Draw("col")
dipoleExit.Draw("same")
dipoleOutXZL.Draw("same")
dipoleOutXZR.Draw("same")
dipoleInXZ.Draw("same")
for i in range(len(staveInnerLXZ)):
    staveInnerLXZ[i].Draw("same")
    staveInnerRXZ[i].Draw("same")
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