def DrawRatio(self, opt=''): '''Draw ratios : h_i / h_0. h_0 is the histogram with the smallest layer, and h_i, i>0 are the other histograms. if the DataMCPlot object contains N histograms, N-1 ratio plots will be drawn. To take another histogram as the denominator, change the layer of this histogram by doing: dataMCPlot.Hist("histName").layer = -99 ''' same = '' denom = None self.ratios = [] for hist in self._SortedHistograms(): if denom == None: denom = hist continue ratio = copy.deepcopy(hist) ratio.obj.Divide(denom.obj) ratio.obj.Draw(same) self.ratios.append(ratio) if same == '': same = 'same' self.DrawLegend(ratio=True) if TPad.Pad(): TPad.Pad().Update() self.lastDraw = 'DrawRatio' self.lastDrawArgs = [opt]
def __init__(self): self.instantiationCount = TriggerRateComparisonPlot.instantiationCount TriggerRateComparisonPlot.instantiationCount += 1 splitPoint = 0.33 self.padRatio = (1 - splitPoint) / splitPoint self.canvas = TCanvas() # Use the instantiation count to give every instance unique names for the pads self.ratePad = TPad( "TriggerRateComparisonPlot(" + str(self.instantiationCount) + ").ratePad", "L1 rate", 0, splitPoint, 1, 1) self.ratioPad = TPad( "TriggerRateComparisonPlot(" + str(self.instantiationCount) + ").ratioPad", "L1 ratio", 0, 0, 1, splitPoint) self.ratePad.Draw() self.ratioPad.Draw() self.ratioPad.SetTopMargin(0) self.ratioPad.SetBottomMargin( self.ratePad.GetBottomMargin() * self.padRatio * 1.1) # A little 10% extra because some is cut off self.ratePad.SetBottomMargin( 0.15) # was zero before I wanted to see the axis self.ratePlot = TriggerRate(self.ratePad) self.ratioPlot = TriggerRateRatio(self.ratioPad)
def bookCanvas(self, xSize=1600, ySize=900): ''' @brief book a ROOT TCanvas @param xSize: size (in pixels) in the horizontal direction @param ySize: size (in pixels) in the vertical direction ''' self.canvas = TCanvas("TuDoUtils Canvas", "TuDoUtils Canvas", 10, 10, xSize, ySize) upheight=0.75 dwcorr=1.32 dwheight=(1-upheight)*dwcorr self.pad1 = TPad("pad1", "pad1",0.0,1-upheight,1.0,1.0) # self.pad1.SetTopMargin(0.05 * 20. / 13.) self.pad1.SetBottomMargin(-0.05) self.pad1.SetLeftMargin(0.12) self.pad1.SetRightMargin(0.05)# self.pad2 = TPad("pad2", "pad2", 0.0,0.0,1.0,dwheight) self.pad2.SetGridy(1) # self.pad2.SetTopMargin(0) self.pad2.SetBottomMargin(0.16*20/7) self.pad2.SetLeftMargin(0.12) self.pad2.SetRightMargin(0.05)
def DrawStack(self, opt='', xmin=None, xmax=None, ymin=None, ymax=None, factor=None, print_norm=False): '''Draw all histograms, some of them in a stack. if Histogram.stack is True, the histogram is put in the stack.''' self._BuildStack(self._SortedHistograms(), ytitle='Events') same = 'same' if len(self.nostack) == 0: same = '' self.supportHist = None for hist in self.nostack: # hist.Draw() if not self.supportHist: self.supportHist = hist self.stack.Draw(opt+same, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, factor=factor) if self.supportHist is None: self.supportHist = self.stack.totalHist if not self.axisWasSet: mxsup = self.supportHist.weighted.GetBinContent( self.supportHist.weighted.GetMaximumBin() ) mxstack = self.stack.totalHist.weighted.GetBinContent( self.stack.totalHist.weighted.GetMaximumBin() ) mx = max(mxsup, mxstack) if ymin is None: ymin = 0.01 if ymax is None: ymax = mx*1.3 self.supportHist.GetYaxis().SetRangeUser(ymin, ymax) self.axisWasSet = True for hist in self.nostack: # import pdb; pdb.set_trace() if self.blindminx: hist.Blind(self.blindminx, self.blindmaxx) # hist.Draw('same') # print 'Check', hist.name, self.signal2show if hist.name.find('LQ')!=-1 or hist.name.find('Zprime')!=-1: if hist.name in self.signal2show: # print 'PASS!!!!!!!!!!!!!!!!!!!!!!!' hist.Draw('same') else: hist.Draw('same') if self.supportHist.weighted.GetMaximumBin() < self.supportHist.weighted.GetNbinsX()/2: # self.legendBorders = 0.62, 0.46, 0.88, 0.89 self.legendPos = 'right' self.DrawLegend(print_norm=print_norm) if TPad.Pad(): TPad.Pad().Update()
def GetCanvas(self, padid, padOrCanvas=0): canvasname = "%s_canvas" % (self.Name) pad1name = "%s_pad1" % (self.Name) pad2name = "%s_pad2" % (self.Name) if not hasattr(self, "Canvas"): #print canvasname if padOrCanvas == 0: self.Canvas = TCanvas(canvasname) else: self.Canvas = gPad self.Canvas.cd() self.Pad1 = TPad(pad1name, pad1name, 0, 0.25, 1, 1) self.Pad1.SetBottomMargin(0.1) self.Pad1.Draw() self.Canvas.cd() self.Pad2 = TPad(pad2name, pad2name, 0, 0, 1, 0.24) self.Pad2.SetTopMargin(0.1) self.Pad2.SetBottomMargin(0.1) self.Pad2.Draw() if padid == 0: self.Canvas.cd() elif padid == 1: self.Pad1.cd() if padid == 2: self.Pad2.cd() return self.Canvas
def make_empty_canvas(self): """Instanciate canvas with two pads.""" # canvas self.decoratee.make_empty_canvas() if self.no_second_histo: return name = self.name self.main_pad = TPad( "main_pad_" + name, "main_pad_" + name, 0, 0.25, 1, 1 ) # main (upper) pad main_pad = self.main_pad main_pad.SetTopMargin(0.1) main_pad.SetBottomMargin(0.) main_pad.SetRightMargin(0.04) main_pad.SetLeftMargin(0.16) main_pad.Draw() # bottom pad self.canvas.cd() self.second_pad = TPad( "bottom_pad_" + name, "bottom_pad_" + name, 0, 0, 1, 0.25 ) second_pad = self.second_pad second_pad.SetTopMargin(0.) second_pad.SetBottomMargin(0.375) second_pad.SetRightMargin(0.04) second_pad.SetLeftMargin(0.16) second_pad.SetGridy() second_pad.Draw()
def DrawDataMinusMCOverData(self, ymin=-0.5, ymax=0.5): stackedHists = [] dataHist = None for hist in self._SortedHistograms(): if hist.stack is False: dataHist = hist continue stackedHists.append( hist ) self._BuildStack( stackedHists, ytitle='Data/MC') mcHist = copy.deepcopy(self.stack.totalHist) self.dataOverMCHist = copy.deepcopy(dataHist) # mcHist.Scale(self.dataOverMCHist.Integral()/mcHist.Integral()) self.dataOverMCHist.Add(mcHist, -1) self.dataOverMCHist.Divide( dataHist ) self.dataOverMCHist.Draw() yaxis = self.dataOverMCHist.GetYaxis() yaxis.SetRangeUser(ymin, ymax) yaxis.SetTitle('(data-MC)/data') yaxis.SetNdivisions(5) fraclines= 0.2 if ymax <= 0.2 or ymin>=-0.2: fraclines = 0.1 self.DrawRatioLines(self.dataOverMCHist, fraclines, 0.) if TPad.Pad(): TPad.Pad().Update()
def __init__(self, name, title, lumi, energy, simOnly): super(CanvasRatio, self).__init__(name, title) self.lumi = lumi self.energy = energy self.simOnly = simOnly bm_ = gStyle.GetPadBottomMargin() tm_ = gStyle.GetPadTopMargin() lm_ = gStyle.GetPadLeftMargin() rm_ = gStyle.GetPadRightMargin() self.splitPad = 0.34 self.cd() self.main = TPad("pMain","pMain", 0., self.splitPad ,1.,1.) self.ratio = TPad("pRatio","pRatio", 0., 0. ,1.,self.splitPad) self.main.SetLeftMargin(lm_) self.main.SetRightMargin(rm_) self.main.SetTopMargin(tm_/(1-self.splitPad) ) self.main.SetBottomMargin(0.02/(1-self.splitPad) ) self.ratio.SetLeftMargin(lm_) self.ratio.SetRightMargin(rm_) self.ratio.SetTopMargin(0.01/self.splitPad) self.ratio.SetBottomMargin(bm_/self.splitPad) self.main.Draw() # cmsPrel(25000., 8., True, self.splitPad) self.ratio.Draw()
def DrawStack(self, opt='', xmin=None, xmax=None, ymin=None, ymax=None): '''Draw all histograms, some of them in a stack. if Histogram.stack is True, the histogram is put in the stack.''' self._BuildStack(self._SortedHistograms(), ytitle='Events') same = 'same' if len(self.nostack) == 0: same = '' self.supportHist = None for hist in self.nostack: hist.Draw() if not self.supportHist: self.supportHist = hist self.stack.Draw(opt + same, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax) if self.supportHist is None: self.supportHist = self.stack.totalHist if not self.axisWasSet: mxsup = self.supportHist.weighted.GetBinContent( self.supportHist.weighted.GetMaximumBin()) mxstack = self.stack.totalHist.weighted.GetBinContent( self.stack.totalHist.weighted.GetMaximumBin()) mx = max(mxsup, mxstack) if ymin is None: ymin = 0.01 if ymax is None: ymax = mx * 1.3 self.supportHist.GetYaxis().SetRangeUser(ymin, ymax) self.axisWasSet = True for hist in self.nostack: if self.blindminx: hist.Blind(self.blindminx, self.blindmaxx) hist.Draw('same') self.DrawLegend() if TPad.Pad(): TPad.Pad().Update()
def DrawRatioStack(self, opt='', xmin=None, xmax=None, ymin=None, ymax=None): '''Draw ratios. The stack is considered as a single histogram.''' denom = None # import pdb; pdb.set_trace() histForRatios = [] denom = None for hist in self._SortedHistograms(): if hist.stack is False: # if several unstacked histograms, the highest layer is used denom = hist continue histForRatios.append(hist) self._BuildStack(histForRatios, ytitle='MC/Data') self.stack.Divide(denom.obj) if self.blindminx and self.blindmaxx: self.stack.Blind(self.blindminx, self.blindmaxx) self.stack.Draw(opt, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax) self.ratios = [] for hist in self.nostack: if hist is denom: continue ratio = copy.deepcopy(hist) ratio.obj.Divide(denom.obj) ratio.obj.Draw('same') self.ratios.append(ratio) self.DrawLegend(ratio=True) self.DrawRatioLines(denom, 0.2, 1) if TPad.Pad(): TPad.Pad().Update()
def bookCanvas(self, xSize=1600, ySize=900): ''' @brief book a ROOT TCanvas @param xSize: size (in pixels) in the horizontal direction @param ySize: size (in pixels) in the vertical direction It is necessary to set self.middlePositions and self.middleSize to the desired values before calling this as it sets up the middle pad ''' if self.middlePositions[0]+self.middleSize[0] > 1: raise(ValueError("Inner plot exceeds right boundary!")) if self.middlePositions[1]+self.middleSize[1] > 1: raise(ValueError("Inner plot exceeds top boundary!")) self.canvas = TCanvas("TuDoUtils Canvas", "TuDoUtils Canvas", 10, 10, xSize, ySize) self.pad1 = TPad("pad1", "pad1", 0, 0, 1, 1, 0, 0, 0) self.pad2 = TPad("pad2", "pad2", self.middlePositions[0], self.middlePositions[1], self.middlePositions[0]+self.middleSize[0], self.middlePositions[1]+self.middleSize[1]) margin = 0.2 # self.pad1.SetLeftMargin(margin) # self.pad1.SetRightMargin(margin) self.pad2.SetLeftMargin(0.15) self.pad2.SetBottomMargin(0.2) self.xRangeMiddle=self.xRange
def DrawDataOverMCMinus1(self, ymin=-0.5, ymax=0.5): stackedHists = [] dataHist = None for hist in self._SortedHistograms(): if hist.stack is False: dataHist = hist continue stackedHists.append(hist) self._BuildStack(stackedHists, ytitle='Data/MC') mcHist = self.BGHist() if dataHist == None: dataHist = mcHist # this was added to avoid crashes for SR plots (without data) self.dataOverMCHist = copy.deepcopy(dataHist) # self.dataOverMCHist.Add(mcHist, -1) self.dataOverMCHist.Divide(mcHist) self.dataOverMCHist.Draw() yaxis = self.dataOverMCHist.GetYaxis() yaxis.SetRangeUser(ymin + 1., ymax + 1.) yaxis.SetTitle('Data/MC') yaxis.SetNdivisions(5) fraclines = 0.2 if ymax <= 0.2 or ymin >= -0.2: fraclines = 0.1 self.DrawRatioLines(self.dataOverMCHist, fraclines, 1.) if TPad.Pad(): TPad.Pad().Update()
def draw_histos(self): for i in range(self.planes): self.histos.append([]) self.pads.append([]) self.canvas.cd(i+1) name = 'ROC' + str(i) p = TPad('name','',0,0,1,1) p.SetRightMargin(0.15) self.pads[i].append(p) p.Draw() p.cd() th2 = TH2F(name, name, self.data[i].shape[0], 0, 53, self.data[i].shape[1], 0, 81) th2.SetStats(False) th2.SetDirectory(0) th2.SetMarkerSize(10) th2.GetXaxis().SetTitle('pixels x') th2.GetYaxis().SetTitle('pixels y') th2.GetYaxis().SetTitleOffset(1.2) th2.GetYaxis().CenterTitle() th2.GetXaxis().CenterTitle() th2.GetZaxis().SetTitle('pulse height') th2.GetZaxis().SetTitleOffset(1.2) th2.GetZaxis().CenterTitle() th2.SetDrawOption('COLZ') self.histos[i].append(th2) for ix, x in enumerate(self.data[i]): for iy, y in enumerate(x): th2.SetBinContent(ix, iy, y) th2.Draw('COLZ') self.canvas.Update()
def DrawStack(self, opt='hist', xmin=None, xmax=None, ymin=None, ymax=None, print_norm=False, scale_signal=''): '''Draw all histograms, some of them in a stack. if Histogram.stack is True, the histogram is put in the stack. scale_signal: mc_int -> scale to stack integral''' self._BuildStack(self._SortedHistograms(), ytitle='Events') same = 'same' if len(self.nostack) == 0: same = '' self.supportHist = None for hist in self.nostack: if hist.style.drawAsData: hist.Draw('SAME' if self.supportHist else '') else: if scale_signal == 'mc_int': hist.Scale(hist.Yield(weighted=True)/self.stack.integral) hist.Draw('SAME HIST' if self.supportHist else 'HIST') if not self.supportHist: self.supportHist = hist self.stack.Draw(opt+same, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax) if self.supportHist is None: self.supportHist = self.BGHist() if not self.axisWasSet: mxsup = self.supportHist.weighted.GetBinContent( self.supportHist.weighted.GetMaximumBin() ) mxstack = self.BGHist().weighted.GetBinContent( self.BGHist().weighted.GetMaximumBin() ) mx = max(mxsup, mxstack) if ymin is None: ymin = 0.01 if ymax is None: ymax = mx*1.3 # centrality = self.supportHist.weighted.GetRMS()/(self.supportHist.weighted.GetXaxis().GetXmax() - self.supportHist.weighted.GetXaxis().GetXmin()) # if centrality > 0.15: # ymax = mx*2.0 self.supportHist.GetYaxis().SetRangeUser(ymin, ymax) self.axisWasSet = True for hist in self.nostack: if self.blindminx and hist.style.drawAsData: hist.Blind(self.blindminx, self.blindmaxx) if hist.style.drawAsData: hist.Draw('SAME') else: hist.Draw('SAME HIST') ## if self.supportHist.weighted.GetMaximumBin() < self.supportHist.weighted.GetNbinsX()/2: ## self.legendBorders = 0.62, 0.46, 0.88, 0.89 ## self.legendPos = 'right' self.DrawLegend(print_norm=print_norm) if TPad.Pad(): TPad.Pad().Update()
def main(): f = TFile("ScanXsec.root","recreate") c1 = TCanvas( 'c1', 'A Simple Graph', 200, 10, 1600, 900 ) c1.SetGrid(0,0) gStyle.SetPaintTextFormat(".2e") gStyle.SetOptStat(0) gStyle.SetMarkerSize(0.9) hAList30 = gethAList(hA_files30) hAList34 = gethAList(hA_files34) histo_hA030 = TH2F('xsec1','Xsec(gz=0.8, tb=1.0) pdf setting 263000',17,500,4100,6,250,850) histo_hA034 = TH2F('xsec2','Cross-Section(pb) with PDF Setting: 263400(CMS), 263000(ATLAS and containing b quarks) and #DeltaCS',17,500,4100,6,250,850) histo_hA0Rate = TH2F('xsec3','Xsec(gz=0.8, tb=1.0) Rate',17,500,4100,6,250,850) histo_hA034.SetXTitle("M_{Zp} (GeV)") histo_hA034.SetYTitle("M_{A0} (GeV)") for a in hAList30: histo_hA030.Fill(a.zpMass,a.ma0Mass,a.weight) for b in hAList34: if (a.zpMass==b.zpMass and a.ma0Mass==b.ma0Mass): histo_hA034.Fill(b.zpMass,b.ma0Mass,b.weight) a.rate = a.weight/b.weight b.rate = b.weight/a.weight histo_hA0Rate.Fill(b.zpMass,b.ma0Mass,abs(a.rate-1)) histo_hA034.SetBarOffset(0.2) histo_hA0Rate.SetBarOffset(-0.2) histo_hA034.GetYaxis().SetTickLength(0.) histo_hA034.Draw("colztext") histo_hA030.Draw("textsame") histo_hA0Rate.Draw("textsame") p = TPad("p","p",0.,0.,1.,1.) p.SetFillStyle(0) p.Draw("same") p.cd() pt1 = TPaveText(0.574,0.55,0.8,0.75) pt2 = TPaveText(0.795,0.55,0.897,0.75) pt1.SetTextSize(0.02) pt1.AddText("Each bin contains 3 values,") pt1.AddText("they are the cross-section (CS)") pt1.AddText("with pdf = 263400(CMS), 263000+b(ATLAS)") pt1.AddText("and the difference between 2 pdf settings,") pt1.AddText(" #DeltaCS = |CS_{CMS} - CS_{ATLAS}|/CS_{CMS}") pt2.SetTextSize(0.02) pt2.AddText("#scale[1.3]{CS_{CMS}}") pt2.AddText("#scale[1.3]{CS_{ATLAS}}") pt2.AddText("#scale[1.3]{#DeltaCS}") pt2.AddText("( 2% < #DeltaCS < 7% )") pt1.Draw() pt2.Draw() c1.SaveAs("pdfDiff.png") c1.Print("pdfDiff.pdf") f.Write() f.Close() c1.Update()
def __init__(self, filename): self._canvas = TCanvas("canvas", "canvas", 800, 450) self._canvas.cd() self._pad = TPad("pad", "", 0, 0, 1, 0.95) self._pdf = TPDF("%s.pdf" % filename) self._subCanvas = 0 self._nCanvasPerPage = 0 self._nx = 1 self._ny = 1
def DrawNormalized(self, opt=''): '''All histograms are drawn as PDFs, even the stacked ones''' same = '' for hist in self._SortedHistograms(): hist.obj.DrawNormalized(same + opt) if same == '': same = 'same' self.DrawLegend() if TPad.Pad(): TPad.Pad().Update()
def BuildTPad(Properties, padname, xlow, ylow, xup, yup): """builds and returns a TPad taking the properties from a dictionary""" #READ FROM DICTIONARY OR TAKE DEFAULTS pad_xlow = Properties.get(padname + '_xlow', xlow) pad_ylow = Properties.get(padname + '_ylow', ylow) pad_xup = Properties.get(padname + '_xup', xup) pad_yup = Properties.get(padname + '_yup', yup) pad_settickx = Properties.get(padname + '_settickx', 1) pad_setticky = Properties.get(padname + '_setticky', 1) pad_logy = Properties.get(padname + '_logy', 0) pad_setbottommargin = Properties.get(padname + '_setbottommargin', 0.1) pad_settopmargin = Properties.get(padname + '_settopmargin', 0.1) pad_setleftmargin = Properties.get(padname + '_setleftmargin', 0.0) pad_setrightmargin = Properties.get(padname + '_setrightmargin', 0.0) # # # pad = TPad("pad", "pad", pad_xlow, pad_ylow, pad_xup, pad_yup) pad.SetTickx(pad_settickx) pad.SetTicky(pad_setticky) # pad.SetLogy(pad_logy) # pad.SetBottomMargin(pad_setbottommargin) pad.SetTopMargin(pad_settopmargin) pad.SetLeftMargin(pad_setleftmargin) pad.SetRightMargin(pad_setrightmargin) # # return pad
def Draw(self, pad_name = 'bottom_pad', pad_title = 'Bottom Pad', pad_x1 = 0, pad_y1 = 0, pad_x2 = 1, pad_y2 = 1, pad_border_size = 1, pad_ratio_order = REFERENCE_IS_DENOMINATOR, pad_bottom_margin = 0, pad_top_margin = 0, pad_left_margin = 0, pad_right_margin = 0, yaxis_min = 0.9, yaxis_max = 1.1, y_ndiv = None, y_title = None, ratio_factor = 2, ): # create the pad self.pad = TPad(pad_name, pad_title, pad_x1, pad_y1, pad_x2, pad_y2, pad_border_size, 0 ) self.pad.SetMargin(pad_left_margin,pad_right_margin,pad_bottom_margin,pad_top_margin) self.pad.SetFillColor(0) self.pad.Draw() self.pad.cd() # create ratio plot for reference self.reference_plot.CreateRatio(self.reference_plot,pad_ratio_order) # the ratio plot will be plotted first so it determines the axes self.reference_plot.ratio.SetMaximum(yaxis_max) self.reference_plot.ratio.SetMinimum(yaxis_min) # here I setup the ratio to show up self.reference_plot.ratio.GetXaxis().SetLabelSize(self.reference_plot.ratio.GetXaxis().GetLabelSize()*ratio_factor) self.reference_plot.ratio.GetYaxis().SetLabelSize(self.reference_plot.ratio.GetYaxis().GetLabelSize()*ratio_factor) self.reference_plot.ratio.GetXaxis().SetTitleSize(self.reference_plot.ratio.GetXaxis().GetTitleSize()*ratio_factor) self.reference_plot.ratio.GetYaxis().SetTitleSize(self.reference_plot.ratio.GetYaxis().GetTitleSize()*ratio_factor) if y_ndiv is not None: self.reference_plot.ratio.GetYaxis().SetNdivisions(y_ndiv) if y_title is not None: self.reference_plot.ratio.GetYaxis().SetTitle(y_title) self.reference_plot.DrawRatio() for plot in self.plots: plot.CreateRatio(self.reference_plot,pad_ratio_order) plot.DrawRatio(same=True)
def make_spectral_plot(image_name, stack, legend): """ :param image_name: name of output image (ext. ".png" will be added) :type image_name: str :param stack: stack of histograms to plot :type stack: THStack :param legend: legend to accompany histograms in stack :type legend: TLegend """ ROOT.gROOT.SetStyle("Plain") gStyle.SetCanvasBorderMode(0) gStyle.SetPadBorderMode(0) gStyle.SetPadColor(0) gStyle.SetCanvasColor(0) gStyle.SetOptTitle(0) gStyle.SetLabelSize(0.06, "xyz") gStyle.SetTitleSize(0.06, "xyz") gStyle.SetOptStat("") c1 = TCanvas("canvas", "canvas", 1200, 900) c1.cd() p1 = TPad("p1", "Region of Interest", 0.0, 0.5, 0.7, 1.0, 0) p1.SetBottomMargin(0.15) p1.SetLeftMargin(0.15) p1.Draw() p2 = TPad("p2", "Key", 0.7, 0.5, 1.0, 1.0, 0) p2.SetBottomMargin(0.15) p2.SetTopMargin(0.15) p2.SetLeftMargin(0.05) p2.SetRightMargin(0.05) p2.Draw() p3 = TPad("p3", "Full Spectrum", 0.0, 0.0, 1.0, 0.5, 0) p3.SetBottomMargin(0.15) p3.SetLeftMargin(0.15) p3.Draw() p3.cd() gStyle.SetOptStat(0) p3.SetLogy() stack.Draw("nostack") stack.GetXaxis().SetTitle("E (MeV)") stack.GetYaxis().SetTitle("Events/(0.02 MeV)") stack.SetMinimum(0.1) p1.cd() gStyle.SetOptStat(0) p1.SetLogy() stack_zoomed = stack.Clone() x_axis = stack_zoomed.GetXaxis() bin_width = x_axis.GetBinWidth(0) # assume uniform e_lo = 2.0 # MeV e_hi = 3.5 # MeV x_axis.SetRange(int(e_lo/bin_width), int(e_hi/bin_width)) stack_zoomed.SetMaximum(5e3) stack_zoomed.Draw("nostack") p2.cd() legend.Draw() c1.Draw() image_path = image_name + ".png" c1.Print(image_path) raw_input("RETURN to exit")
def __init__(self, name='', yMargin = 0.2 ): self.name = name self.frame = TCanvas(name,name) # in case set the width above SetOwnership(self.frame,False) self.mainPad = TPad(name+'mainPad', '' ,0.01,yMargin,0.99,0.99) self.mainPad.SetBottomMargin(0) self.comparisonPad = TPad(name+'comparisonPad', '' ,0.01,0.01,0.99,yMargin) self.comparisonPad.SetTopMargin(0) self.comparisonPad.SetBottomMargin(0.33); self.comparisonPad.SetGridy() self.draw()
def __init__(self, ncanvas, npads=[1], pcoords=None): """ Arguments: -> ncanvas: number of canvases that the instance will have -> npads: list number of pads per canvas, where each element in the list refers to a different canvas -> pcoords: list of list of the coordinates of the pads, where each sublist refers to a different canvas """ if ncanvas <= 0: raise ValueError('The object needs to possess at least one canvas') if type(npads) is int: npads = [npads] if any(_i <= 0 for _i in npads): raise ValueError('The object needs to possess at least one pad') if any(_i == 1 for _i in npads) and pcoords is None: raise ValueError( 'Please specify the coordinates associated to each pad.') if pcoords is not None and len(pcoords) != ncanvas: raise ValueError( 'The dimensions of your coordinate vector do not match the' 'number of canvases that was specified.') for _ic in range(ncanvas): if len(pcoords[_ic]) != npads[_ic]: raise ValueError('') self._c = [ TCanvas('c', 'c', 200, 10, 700, 900) for _ in range(ncanvas) ] self._p = [[] for _ in range(ncanvas)] if pcoords == None: for _ic in range(ncanvas): for _ip in range(npads[_ic]): self._c[_ic].cd() self._p[_ic].append( TPad('pad' + str(_ic) + '_' + str(_ip), 'pad' + str(_ic) + '_' + str(_ip), 0.03, 0.03, 0.97, 0.8, 21)) else: for _ic in range(ncanvas): for _ip in range(npads[_ic]): self._c[_ic].cd() self._p[_ic].append( TPad('pad' + str(_ic) + '_' + str(_ip), 'pad' + str(_ic) + '_' + str(_ip), pcoords[_ic][_ip][0], pcoords[_ic][_ip][1], pcoords[_ic][_ip][2], pcoords[_ic][_ip][3], 21)) for _ic in range(ncanvas): for _ip in range(npads[_ic]): self._c[_ic].cd() self._p[_ic][_ip].Draw() self._p[_ic][_ip].cd() self._p[_ic][_ip].GetFrame().SetFillColor(18)
def __init__(self, maxpoints=60): self.maxpoints = maxpoints self.gq = False self.canvas = TCanvas('c1', 'A Simple Graph Example', 200, 10, 700, 500) self.canvas_1 = TPad("c1_1", "c1_1", 0.01, 0.67, 0.99, 0.99) self.canvas_2 = TPad("c1_2", "c1_2", 0.01, 0.01, 0.99, 0.66) self.canvas_1.SetGrid() self.canvas_2.SetGridx() self.canvas_1.Draw() self.canvas_2.Draw() self.data = [0] self.data_time = [time.time()] n = 1 x = array('d') y = array('d') x.append(0) y.append(0) self.canvas_1.cd() self.graph = TGraph(n, x, y) self.graph.SetLineColor(2) self.graph.SetLineWidth(4) self.graph.SetMarkerColor(4) self.graph.SetMarkerStyle(2) self.graph.SetTitle('EEG Signal') self.graph.GetXaxis().SetTitle('Time') self.graph.GetYaxis().SetTitle('Amplitude') self.graph.GetYaxis().SetRangeUser(-2000, 2000) self.graph.Draw('ACP') self.canvas_2.cd() TVirtualFFT.SetTransform(0) self.fft = TH1F("fft", "eeg_fft", 3, 0, 3) self.fft.SetTitle("EEG FFT") self.fft.Fill("1 Hz", 0) self.fft.Fill("2 Hz", 0) self.fft.SetMinimum(0) self.fft.SetMaximum(100000) self.fft.SetFillStyle(3001) self.fft.SetFillColor(30) self.fft.Draw("B HIST") self.ampmax = 100000 self.fft.SetStats(False) self.fft.GetXaxis().SetLabelSize(0.05) self.fft.GetYaxis().SetLabelSize(0.05)
def setcanvas(c1, pad): c1.SetLeftMargin(0.0) c1.SetTopMargin(0.00) c1.SetRightMargin(0.00) c1.SetBottomMargin(0.0) pad[0] = TPad("pad0", "pad", 0, 0.67, 0.5, 1.0) pad[1] = TPad("pad1", "pad", 0.5, 0.67, 1.0, 1.0) pad[2] = TPad("pad2", "pad", 0, 0.33, 0.5, 0.67) pad[3] = TPad("pad3", "pad", 0.5, 0.33, 1.0, 0.67) pad[4] = TPad("pad4", "pad", 0., 0., 0.5, 0.33) for k in range(5): pad[k].Draw()
def plotZoom(hist): pad = TPad('pad', '', 0.2, 0.55, 0.6, 0.89) pad.Draw() pad.cd() hist2 = hist.Clone() hist2.SetTitle('') hist2.Draw() hist2.GetXaxis().SetRangeUser(10, 100) for axis in [hist2.GetXaxis(), hist2.GetYaxis()]: axis.SetTitle('') axis.SetNdivisions(505) axis.SetLabelOffset(0.02) hist2.SetStats(False) return pad, hist2
def DrawNormalizedStack(self, opt='', xmin=None, xmax=None, ymin=0.001, ymax=None): '''Draw all histograms, some of them in a stack. if Histogram.stack is True, the histogram is put in the stack. all histograms out of the stack, and the stack itself, are shown as PDFs.''' self._BuildStack(self._SortedHistograms(), ytitle='p.d.f.') self.stack.DrawNormalized(opt, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax) for hist in self.nostack: hist.obj.DrawNormalized('same') self.DrawLegend() if TPad.Pad(): TPad.Pad().Update()
def Draw(self, opt=''): '''All histograms are drawn.''' same = '' self.supportHist = None for hist in self._SortedHistograms(): if self.supportHist is None: self.supportHist = hist hist.Draw(same + opt) if same == '': same = 'same' yaxis = self.supportHist.GetYaxis() yaxis.SetRangeUser(0.01, ymax(self._SortedHistograms())) self.DrawLegend() if TPad.Pad(): TPad.Pad().Update()
def compare_tof(tdir, title=''): from ROOT import TCanvas, TPad # tdir.Get("Tracks/pass").ls() eta_pt = tdir.Get("Tracks/pass/EtaPt") # eta_pt = tdir.Get("Tracks/pass/PtPhi") events = tdir.Get("Event/pass/cent_mult") print(events, events.GetEntries()) pt = eta_pt.ProjectionY("pt") pt.SetTitle(title) pt.Scale(1.0 / events.GetEntries()) c = TCanvas() plot = PlotData(c) pt.Draw('H') plot.pt = pt plot.subpad = TPad('subpad', '', 0.4, 0.4, 0.75, 0.85) plot.subpad.cd() eta_pt.Draw("COL") c.cd() plot.subpad.Draw() return plot
def createCanvasPads(): c = TCanvas("c", "canvas", 900, 700) # Upper histogram plot is pad1 pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.SetBottomMargin(0) # joins upper and lower plot pad1.Draw() # Lower ratio plot is pad2 c.cd() # returns to main canvas before defining pad2 pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3) pad2.SetTopMargin(0) # joins upper and lower plot pad2.SetBottomMargin(0.3) pad2.Draw() return c, pad1, pad2
def buildCanvas(): global can, pad, padr can = TCanvas('can','',800,800) can.cd() can.Draw() sep = 0.35 pad = TPad('pad','',0.01,sep,0.99, 0.99) pad.SetBottomMargin(0.04) padr = TPad('padr','',0.01, 0.01, 0.99, sep) padr.SetTopMargin(0.04) padr.SetBottomMargin(0.3) pad.Draw() padr.Draw() return can, pad, padr
def main(progname, file_name, number): myFile1 = TFile.Open("%s" % (file_name), "READ") hist1 = myFile1.Get("Data_s%s" % (number)) myFile2 = TFile.Open("%s" % (file_name), "READ") hist2 = myFile2.Get("Model_cat1_s%s" % (number)) c1 = TCanvas("c1", "fit", 1000, 4000) hist1.Sumw2() hist1.SetLineColor(ROOT.kOrange + 10) hist1.SetMarkerStyle(20) hist1.SetLineWidth(1) hist1.SetMarkerSize(0.7) hist1.SetMarkerColorAlpha(ROOT.kOrange + 10, 1) # hist1.SetFillColorAlpha(ROOT.kOrange + 10, 0.4) hist1.SetStats(False) hist2.SetLineColor(ROOT.kViolet + 10) hist2.SetLineStyle(1) hist2.Sumw2() hist2.SetMarkerStyle(20) hist2.SetMarkerSize(0.7) hist2.SetLineWidth(1) hist2.SetMarkerColorAlpha(ROOT.kViolet + 10, 1) hist2.SetStats(False) #Create pad1 pad1 = TPad("pad1", "", 0, 0, 1, 1) pad1.SetLeftMargin(0.1) pad1.SetRightMargin(0.1) pad1.SetTopMargin(0.1) pad1.SetBottomMargin(0.1) pad1.Draw() pad1.cd() hist1.Draw("E1") hist2.Draw("E1 same") #Add the legend legend = TLegend(0.65, 0.75, 0.89, 0.89) legend.AddEntry(hist1, "LHCb data", "lpe") legend.AddEntry(hist2, "AmpGen fitter", "lpe") legend.SetTextFont(133) legend.SetTextSize(30) legend.SetLineColor(0) legend.Draw() c1.SaveAs("compare%s.png" % (number))
def makeAndDivideCanvas(width, height, lower_pad_fraction): c = TCanvas("", "", width, height) upper_pad = TPad("", "", 0, lower_pad_fraction, 1, 1) upper_pad.SetBottomMargin(0.03) upper_pad.SetTopMargin(0.08) lower_pad = TPad("", "", 0, 0, 1, lower_pad_fraction) lower_pad.SetTopMargin(0.01) lower_pad.SetBottomMargin(0.4) return c, upper_pad, lower_pad
def bookCanvas(self, xSize=1600, ySize=900): ''' @brief book a ROOT TCanvas @param xSize: size (in pixels) in the horizontal direction @param ySize: size (in pixels) in the vertical direction ''' self.canvas = TCanvas("TuDoUtils Canvas", "TuDoUtils Canvas", 10, 10, xSize, ySize) self.pad1 = TPad("pad1", "pad1", 0, 0, 1, 1, 0, 0, 0) self.pad2 = TPad("pad2", "pad2", 0, 0, 1, 1) margin = 0.08 self.pad1.SetLeftMargin(margin) self.pad1.SetRightMargin(margin) self.pad2.SetLeftMargin(margin) self.pad2.SetRightMargin(margin)
def __init__(self, infos, run_mode, number): self.number = number self.runmode = run_mode self.infos = infos if self.infos.single_mode: self.c = TCanvas("c", self.canvas_name(), 1500, 1000) else: self.c = TCanvas("c", self.canvas_name(), 1000, 1000) # dividing canvas into pads self.p5 = TPad("p5", "", space, space, 1 - space, title / 3 - space / 2) self.p6 = TPad("p6", "", space, title / 3 + space / 2, 1 - space, title * 2 / 3 - space / 2) self.p7 = TPad("p7", "", space, title * 2 / 3 + space / 2, 1 - space, title - space / 2) if number == "1": self.p7 = TPad("p7", "", space, space, 1 - space, title - space / 2) if number == "2": padsize = (title - 2 * space) / 2 self.p7 = TPad("p7", "", space, 2 * space + padsize, 1 - space, 2 * space + 2 * padsize) self.p6 = TPad("p6", "", space, space, 1 - space, space + padsize) self.p8 = TPad("p8", "", 0, title, 1, 1) self.draw_pads() # title texts self.t2 = TPaveText(0, 0, 1, 0.7, "NB") self.t3 = TPaveText(0.5, 0, 1, 0.7, "NB") self.draw_titles() # graphs self.g1 = {} self.g2 = {} self.make_graphs() # graph pads self.p1 = {} self.p2 = {} self.p3 = {} self.p11 = {} self.p22 = {} self.p33 = {} self.make_pads() # margins self.ymin = {} self.xmin = {} self.ymax = {} self.xmax = {} self.make_margins() # second axis self.a1 = {} self.make_axis() # box self.b1 = self.make_box() # pad titles self.t1 = {} self.make_pad_title() # run lines self.run_lines = [] self.pt = TPaveLabel(.01, .01, .1, .1, "", "NDC") self.pt.ResetBit(kCanDelete) self.pt.SetFillColor(0) self.pt.SetShadowColor(0) self.pt.SetBorderSize(0)
def makeTwoScalesGraph(file): print(file) ch1 = OPData.fromPath('../data/part3/%s' % file, 1) ch2 = OPData.fromPath('../data/part3/%s' % file, 2) print('make canvas + pad') c = TCanvas('c-%s' % file, '', 1280, 720) pad = TPad('pad-%s' % file, '', 0, 0, 1, 1) pad.Draw() pad.cd() print('frame') frame = pad.DrawFrame(0, min(ch1.getY()) * 1.1, 0.051, max(ch1.getY()) * 1.1) frame.SetXTitle('Zeit t / s') frame.GetXaxis().CenterTitle() frame.SetYTitle('Spannung Spule 2: U_{2} / V') frame.GetYaxis().CenterTitle() frame.GetYaxis().SetLabelColor(4) frame.GetYaxis().SetTitleColor(4) print('g1') g1 = ch1.makeGraph('g1-%s' % file) prepareGraph(g1) g1.Draw('PX') print('overlay') c.cd() overlay = TPad('overlay-%s' % file, '', 0, 0, 1, 1) overlay.SetFillStyle(4000) # transparent overlay.SetFillColor(0) # white overlay.SetFrameFillStyle(4000) # transparent overlay.Draw() overlay.cd() print('g2') g2 = ch2.makeGraph('g2-%s' % file) prepareGraph(g2, 2) g2ymin = min(ch2.getY()) xmin = pad.GetUxmin() xmax = pad.GetUxmax() ymin = 1.1 * g2ymin ymax = abs(ymin) if file == '07.tab': # same scale like 06.tab ymin, ymax = -0.07128, 0.07128 oframe = overlay.DrawFrame(xmin, ymin, xmax, ymax) oframe.GetXaxis().SetLabelOffset(99) oframe.GetYaxis().SetLabelOffset(99) oframe.GetYaxis().SetTickLength(0) g2.Draw('PX') print('axis') axis = TGaxis(xmax, ymin, xmax, ymax, ymin, ymax, 510, "+L") axis.SetTitle('Spannung Photodiode: U_{ph} / V') axis.CenterTitle() axis.SetTitleOffset(1.2) axis.Draw() print('print') c.Update() c.Print('../img/part3/%s.pdf' % file[:-4], 'pdf')
def overlayAndRatio(canvas, min_ratio, max_ratio, h1, h2): canvas.ResetAttPad() canvas.Clear() pad = TPad("main","main", 0, 0.3, 1, 1) pad.SetBottomMargin(0.05); pad.Draw() pad.cd() h1.Draw() h2.SetLineColor(kOrange+10) h2.Draw('SAME') canvas.cd() ratio = TPad("ratio","ratio", 0, 0.05, 1, 0.3); ratio.SetTopMargin(0.05); ratio.Draw() ratio.cd() if isinstance(h1, TProfile) and isinstance(h2, TProfile): h1_p = h1.ProjectionX() h2_p = h2.ProjectionX() h1_p.Divide(h2_p) h1_p.SetMaximum(max_ratio) h1_p.SetMinimum(min_ratio) h1_p.SetMarkerStyle(kFullCircle) h1_p.SetMarkerSize(0.6) h1_p.SetTitle('') h1_p.GetXaxis().SetLabelFont(42) h1_p.GetXaxis().SetLabelSize(0.1) h1_p.GetYaxis().SetLabelFont(42) h1_p.GetYaxis().SetLabelSize(0.1) h1_p.GetYaxis().SetNdivisions(505) equality = TLine() h1_p.Draw("SAME HIST P") equality.SetLineColor(kOrange+10) equality.DrawLine(h1_p.GetXaxis().GetXmin(), 1, h1_p.GetXaxis().GetXmax(), 1)
def setupCanvas(self): # setup ATLAS plotting style self.logger.info("Load ATLAS plotting style") atlas_style() # create canvas self.logger.info("Begin to define canvas") # If want ratio plot to be shown at the bottom, define its fraction first if self.ratio<=0: canvas_w,canvas_h=800,600 elif self.ratio>0: canvas_w,canvas_h=800,int(600*(1+self.ratio)) else: self.logger.error("The scale of RATIO plot is wrongly defined: %.4f".format(self.ratio)) sys.exit(-1) # Define canvas and create sub pad if needed gStyle.SetPadLeftMargin(0.15) gStyle.SetPadRightMargin(0.10) gStyle.SetPadTopMargin(0.06) gStyle.SetPadBottomMargin(0.15) self.MyC=TCanvas('MyC','MyC',canvas_w,canvas_h) self.MyC.SetTicks(1,1) if self.ratio>0: fraction=self.ratio+0.2 self.Pad1 = TPad("p1","p1",0,fraction*1.0/(fraction+1),1,1,0,0) # x1,y1,x2,y2 self.Pad1.SetMargin(0.15,0.10,0.03,0.05) # left, right, bottom, top self.Pad2 = TPad("p2","p2",0,0,1,fraction*1.0/(fraction+1),0,0) self.Pad2.SetMargin(0.15,0.10,0.15/fraction,0) self.Pad1.Draw() self.Pad2.Draw() self.Pad2.SetGrid() self.logger.info("Canvas is defined as (width={0},height={1}): Ratio Plot Pad / Main Pad = {2:0.3f}".format(canvas_w,canvas_h,self.ratio)) else: self.logger.info("Canvas is defined as (width={0},height={1})".format(canvas_w,canvas_h)) # put a end mark return
def draw(self, title): ''' draws regression and residuals in one canvas ''' self.residuals() from ROOT import TCanvas, TPad, TLine from random import randint from sys import maxint random_name = randint(0,maxint) self.canvas = TCanvas("canvas{}".format( random_name), "Linear Regression", 1300, 800) self.canvas.SetBatch() hPad = TPad("fitPad{}".format( random_name ), "Fit", 0, 0.3, 1, 1) hPad.SetFillStyle(4000) hPad.SetBorderSize(0) hPad.SetBottomMargin(0) hPad.Draw() hPad.cd() self.graph.SetTitle( title ) self.resgraph.GetXaxis().SetTitle("") self.graph.Draw("ap") self.canvas.cd() residualPad = TPad("resPad{}".format( random_name ), "Residuals", 0, 0, 1, 0.3) residualPad.SetFillStyle(4000) residualPad.SetFrameFillStyle(4000) residualPad.SetBorderSize(0) residualPad.Draw() residualPad.cd() # get y-label for residuals from re import match try: splittitle = title.split(';') val, unit = match( '(.*)\[(.*)\]', splittitle[2] ).groups() restitle = splittitle[0] + ';' + splittitle[1] + ';' + val + '- fit [' + unit + ']' self.resgraph.SetTitle( restitle ) except: self.resgraph.SetTitle( title + ' - fit' ) xaxis = self.resgraph.GetXaxis() xaxis.SetTitleSize(.15) xaxis.SetTitleOffset(.3) xaxis.SetLabelSize(.1) self.resgraph.GetYaxis().SetNdivisions( 8,0 ,0 ) self.resgraph.GetYaxis().SetTitleSize(.18) self.resgraph.GetYaxis().SetTitleOffset(.23) self.resgraph.GetYaxis().SetLabelSize(.2) self.resgraph.Draw("ap") self.line = TLine( xaxis.GetXmin(), 0, xaxis.GetXmax(), 0 ) self.line.Draw()
def drawCanvas2(): c1 = TCanvas("c1", "c1", 700, 700) pad1 = TPad("pad1", "top pad" , 0.0, 0.3, 1.0, 1.0) pad1.SetBottomMargin(0.0) pad1.SetNumber(1) pad1.Draw() pad1.cd() c1.cd() pad2 = TPad("pad2", "bottom pad", 0.0, 0.0, 1.0, 0.3) pad2.SetTopMargin(0.0) pad2.SetBottomMargin(0.35) pad2.SetNumber(2) pad2.Draw() pad2.cd() c1.cd() return c1
def make_KLZ_spectral_plot(image_name, stack, legend): """ :param image_name: name of output image (ext. ".png" will be added) :type image_name: str :param stack: stack of histograms to plot :type stack: THStack :param legend: legend to accompany histograms in stack :type legend: TLegend """ ROOT.gROOT.SetStyle("Plain") gStyle.SetCanvasBorderMode(0) gStyle.SetPadBorderMode(0) gStyle.SetPadColor(0) gStyle.SetCanvasColor(0) gStyle.SetOptTitle(0) gStyle.SetLabelSize(0.06, "xyz") gStyle.SetTitleSize(0.06, "xyz") c1 = TCanvas("canvas", "canvas", 1200, 600) c1.cd() p1 = TPad("p1", "Full Spectrum", 0.0, 0.0, 1.0, 1.0, 0) p1.SetBottomMargin(0.15) p1.SetLeftMargin(0.15) p1.Draw() p2 = TPad("p2", "Key", 0.5, 0.6, 0.9, 0.9, 0) p2.SetBottomMargin(0.2) p2.SetTopMargin(0.2) p2.Draw() p2.cd() legend.SetTextSize(0.08) legend.SetNColumns(2) legend.SetEntrySeparation(0.01) legend.Draw() p1.cd() gStyle.SetOptStat(0) p1.SetLogy() stack.Draw("nostack") stack.GetXaxis().SetTitle("E (MeV)") stack.GetYaxis().SetTitle("Events/(0.05 MeV)") stack.SetMinimum(0.1) c1.Draw() image_path = image_name + ".png" c1.Print(image_path) raw_input("RETURN to exit")
def plot_data_vs_refold(args, regularisation_settings, tau): ''' Plot the differences between the unfolded and refolded distributions TODO Include also with best tau - redo unfolding with best tau then come here ''' tau = str(tau).replace('.', 'p') # data = hist_to_value_error_tuplelist(regularisation_settings.h_data) # measured = hist_to_value_error_tuplelist(regularisation_settings.h_measured) variable = regularisation_settings.variable channel = regularisation_settings.channel plot_outpath = regularisation_settings.outpath.replace('tables/', 'plots/')+variable+'/' make_folder_if_not_exists(plot_outpath) outfile = plot_outpath+channel+'_unfold_refold_test_tau_'+tau+'.pdf' if args.run_measured_as_data: outfile = plot_outpath+channel+'_run_measured_as_data_tau_'+tau+'.pdf' c = TCanvas('c1','c1',600,400) c.SetFillColor(2); p1 = TPad("pad1", "p1",0.0,0.2,1.0,1.0,21) p2 = TPad("pad2", "p2",0.0,0.0,1.0,0.2,22) p1.SetFillColor(0); p2.SetFillColor(0); p1.Draw() p2.Draw() p1.cd() regularisation_settings.h_refolded.SetMarkerStyle(10); regularisation_settings.h_refolded.SetMarkerColor(4); # regularisation_settings.h_refolded.SetMarkerSize(10); regularisation_settings.h_refolded.Draw() regularisation_settings.h_data.SetFillColor(3); regularisation_settings.h_data.Draw("hist same"); p2.cd() h_ratio = regularisation_settings.h_data.Clone() h_ratio.Divide(regularisation_settings.h_refolded) h_ratio.SetMarkerSize(0.1); h_ratio.Draw() c.SaveAs(outfile) c.Delete() return
def show(self, outDir): if len(self.mc)==0: print '%s has no MC!' % self.name return htype=self.mc[0].ClassName() if htype.find('TH2')>=0: print 'Skipping TH2' return ROOT.gStyle.SetOptTitle(0) ROOT.gStyle.SetOptStat(0) ROOT.gROOT.SetBatch(1) canvas = TCanvas('c_'+self.name,'C',800,800) canvas.cd() t1 = TPad("t1","t1", 0.0, 0.20, 1.0, 1.0) t1.SetBottomMargin(0) t1.Draw() t1.cd() self._garbageList.append(t1) frame = None # Decide which backgrounds are visible maxint = max([x.Integral() for x in self.mc]) hists_to_add = [h for h in self.mc if h.Integral() > 0.005*maxint] # Make the legend with the correct size leg = TLegend(0.75, 0.74-0.04*max(len(hists_to_add)-2,0), .89, 0.89) leg.SetBorderSize(0) leg.SetFillStyle(0) leg.SetTextFont(43) leg.SetTextSize(20) nlegCols = 0 maxY = 1.0 if self.data is not None: leg.AddEntry( self.data, self.data.GetTitle(),'p') frame = self.dataH.Clone('frame') self._garbageList.append(frame) maxY = self.dataH.GetMaximum() frame.Reset('ICE') elif self.dataH is not None: leg.AddEntry( self.dataH, self.dataH.GetTitle(),'p') frame = self.dataH.Clone('frame') self._garbageList.append(frame) maxY = self.dataH.GetMaximum() frame.Reset('ICE') # Add the legend entries for the visible backgrounds for h in sorted(hists_to_add, key=lambda x: x.Integral(), reverse=True): leg.AddEntry(h, h.GetTitle(), 'f') nlegCols = nlegCols+1 # Build the stack to plot from all backgrounds totalMC = None stack = THStack('mc','mc') for h in sorted(self.mc, key=lambda x: x.Integral()): stack.Add(h,'hist') if totalMC is None: totalMC = h.Clone('totalmc') self._garbageList.append(totalMC) totalMC.SetDirectory(0) else: totalMC.Add(h) if totalMC is not None: maxY = max(totalMC.GetMaximum(),maxY) if frame is None: frame = totalMC.Clone('frame') frame.Reset('ICE') self._garbageList.append(frame) if self.data is not None or self.dataH is not None: nlegCols = nlegCols+1 if nlegCols == 0: print '%s is empty'%self.name return frame.GetYaxis().SetTitleSize(0.045) frame.GetYaxis().SetLabelSize(0.04) frame.GetYaxis().SetRangeUser(0.5, 1.2*maxY) frame.GetYaxis().SetNoExponent() frame.SetDirectory(0) frame.Draw() frame.GetYaxis().SetTitleOffset(1.6) stack.Draw('hist same') if self.data is not None: self.data.Draw('P') elif self.dataH is not None: self.dataH.Draw('e1same') # leg.SetNColumns(nlegCols) leg.Draw() redrawBorder(t1) ## Draw CMS Preliminary label CMS_lumi(pad=t1,iPeriod=2,iPosX=0,extraText='Work in Progress') if self.normalizedToData: txt=TLatex() txt.SetNDC(True) txt.SetTextFont(42) txt.SetTextColor(ROOT.kGray+1) txt.SetTextSize(0.035) txt.SetTextAngle(90) txt.SetTextAlign(12) txt.DrawLatex(0.05,0.05,'#it{Normalized to data}') if totalMC is None or (self.data is None and self.dataH is None): t1.SetPad(0,0,1,1) t1.SetBottomMargin(0.12) else: canvas.cd() t2 = TPad("t2","t2", 0.0, 0.0, 1.0, 0.2) self._garbageList.append(t2) t2.SetTopMargin(0) t2.SetBottomMargin(0.4) t2.SetGridy() t2.Draw() t2.cd() ratioframe=self.dataH.Clone('ratioframe') ratioframe.Reset('ICE') ratioframe.Draw() ratioframe.GetYaxis().SetRangeUser(self.ratiorange[0], self.ratiorange[1]) ratioframe.GetYaxis().SetTitle('Obs./Exp.') ratioframe.GetYaxis().SetNdivisions(5) ratioframe.GetYaxis().SetLabelSize(0.15) ratioframe.GetXaxis().SetLabelSize(0.15) ratioframe.GetYaxis().SetTitleSize(0.18) ratioframe.GetXaxis().SetLabelSize(0.18) ratioframe.GetXaxis().SetTitleSize(0.18) ratioframe.GetYaxis().SetTitleOffset(0.4) ratioframe.GetXaxis().SetTitleOffset(0.9) gr=ROOT.TGraphAsymmErrors() gr.SetName("data2bkg") gr.SetMarkerStyle(self.dataH.GetMarkerStyle()) gr.SetMarkerSize(self.dataH.GetMarkerSize()) gr.SetMarkerColor(self.dataH.GetMarkerColor()) gr.SetLineColor(self.dataH.GetLineColor()) gr.SetLineWidth(self.dataH.GetLineWidth()) bkgUncGr=ROOT.TGraphErrors() bkgUncGr.SetName('bkgunc') bkgUncGr.SetMarkerColor(920) bkgUncGr.SetMarkerStyle(1) bkgUncGr.SetLineColor(920) bkgUncGr.SetFillColor(920) bkgUncGr.SetFillStyle(3001) for xbin in xrange(1,self.dataH.GetXaxis().GetNbins()+1): x = self.dataH.GetXaxis().GetBinCenter(xbin) dx = self.dataH.GetXaxis().GetBinWidth(xbin) dataCts = self.dataH.GetBinContent(xbin) if self.data: data_err_low = self.data.GetErrorYlow(xbin-1) #get errors from the graph data_err_up = self.data.GetErrorYhigh(xbin-1) else: data_err_low=self.dataH.GetBinError(xbin) data_err_up=data_err_low bkgCts = totalMC.GetBinContent(xbin); bkgCts_err = totalMC.GetBinError(xbin); if bkgCts==0 : continue errLo=math.sqrt(math.pow(data_err_low*bkgCts,2) + math.pow(dataCts*bkgCts_err,2))/math.pow(bkgCts,2) errHi=math.sqrt(math.pow(data_err_up*bkgCts,2) + math.pow(dataCts*bkgCts_err,2))/math.pow(bkgCts,2) np=gr.GetN() gr.SetPoint(np,x,dataCts/bkgCts) gr.SetPointError(np,0,0,errLo,errHi) bkgUncGr.SetPoint(np,x,1) bkgUncGr.SetPointError(np,dx,bkgCts_err/bkgCts) bkgUncGr.Draw('2') gr.Draw('p') redrawBorder(t2) canvas.cd() canvas.Modified() canvas.Update() for ext in self.plotformats : canvas.SaveAs(os.path.join(outDir, self.name+'.'+ext)) if self.savelog: t1.cd() t1.SetLogy() frame.GetYaxis().SetRangeUser(1000,10*maxY) canvas.cd() for ext in self.plotformats : canvas.SaveAs(os.path.join(outDir, self.name+'_log.'+ext))
def plotEfficiencyForPt(folder,pt): if(DEBUG): print prefix + 'was called' #Set plot style if(DEBUG): print prefix + "Getting histogram: %s" % ("hoMuonAnalyzer/efficiency/GenAndL1MuonPt" + str(pt) + "_Efficiency") l1Muon = fileHandler.getHistogram("hoMuonAnalyzer/efficiency/GenAndL1MuonPt" + str(pt) + "_Efficiency") l1MuonAndHo = fileHandler.getHistogram("hoMuonAnalyzer/efficiency/L1MuonHoRecoPt" + str(pt) + "_Efficiency") if(DEBUG): print prefix + "Getting histogram: %s" % ("hoMuonAnalyzer/efficiency/GenAndL1MuonAndHoAboveThrPt" + str(pt) + "_Efficiency") l1MuonAndHoAboveThr = fileHandler.getHistogram("hoMuonAnalyzer/efficiency/GenAndL1MuonAndHoAboveThrPt" + str(pt) + "_Efficiency") canv = TCanvas("efficiencyCanvas" + str(pt),'efficiencyCanvas' + str(pt),1200,1200) l1Muon.SetMarkerStyle(markerpairs[pt/5 -1][0]) l1MuonAndHo.SetMarkerStyle(21) l1MuonAndHoAboveThr.SetMarkerStyle(markerpairs[pt/5 -1][1]) l1Muon.SetMarkerColor(colorRwthDarkBlue) l1MuonAndHo.SetMarkerColor(ROOT.kBlue) l1MuonAndHoAboveThr.SetMarkerColor(colorRwthMagenta) l1Muon.SetLineColor(colorRwthDarkBlue) l1MuonAndHo.SetLineColor(ROOT.kBlue) l1MuonAndHoAboveThr.SetLineColor(colorRwthMagenta) upperPad = TPad("upperPad", "upperPad", .005, .25, .995, .995); lowerPad = TPad("lowerPad", "lowerPad", .005, .005, .995, .25); upperPad.SetBottomMargin(0) lowerPad.SetTopMargin(0) upperPad.Draw() lowerPad.Draw() upperPad.cd() l1Muon.Draw() # l1MuonAndHo.Draw('same') l1MuonAndHoAboveThr.Draw('same') canv.Update() l1Muon.GetPaintedGraph().GetYaxis().SetTitleFont(62) l1Muon.GetPaintedGraph().GetYaxis().SetLabelFont(62) l1Muon.GetPaintedGraph().GetXaxis().SetRangeUser(0,50) #.GetPaintedGraph() l1Muon.SetTitle("Efficiency, p_{T} = " + str(pt) + " GeV;p_{T};Eff.") canv.Update() line = TLine(pt,0,pt,1) line.SetLineColor(ROOT.kRed) line.SetLineWidth(2) line.Draw() legend = TLegend(0.5,0.1,0.9,0.35) legend.AddEntry(l1Muon,'L1 Efficiency','ep') legend.AddEntry(l1MuonAndHoAboveThr,'L1 + HO hits > 0.2 GeV','ep') legend.AddEntry(line,'Trg. threshold','e') legend.Draw() integralL1 = 0 integralL1AndHo = 0 for i in range(0,pt+1): integralL1 += l1Muon.GetPassedHistogram().GetBinContent(pt+1) integralL1AndHo += l1MuonAndHoAboveThr.GetPassedHistogram().GetBinContent(pt+1) paveText = TPaveText(0.5,0.35,0.9,0.4,'NDC') if(not integralL1 == 0): paveText.AddText('%s: %.2f%% #pm %.2f%%' % ('Reduction below threshold',100 - integralL1AndHo/integralL1*100,calcSigma(integralL1AndHo, integralL1)*100)) paveText.SetBorderSize(1) paveText.Draw() label = drawLabelCmsPrivateSimulation() ##### Try creating residuals lowerPad.cd() l1MuonGraph = l1Muon.GetPaintedGraph() l1MuonAndHoAboveThrGraph = l1MuonAndHoAboveThr.GetPaintedGraph() newGraph = TGraph() x1 = Double(0) y1 = Double(0) x2 = Double(0) y2 = Double(0) for i in range(0,50): l1MuonGraph.GetPoint(i,x1,y1) l1MuonAndHoAboveThrGraph.GetPoint(i,x2,y2) newGraph.SetPoint(i,x1,(y1-y2)*100) newGraph.SetMarkerStyle(20) newGraph.GetYaxis().SetTitle("%") newGraph.Draw("a,p") newGraph.GetXaxis().SetLimits(0,50) line2 = TLine(0,0,50,0) line2.SetLineColor(ROOT.kRed) line2.SetLineWidth(2) line2.Draw() ##### Finally save the stuff canv.SaveAs("plots/efficiency/efficiency" + str(pt) + ".png") canv.SaveAs("plots/efficiency/efficiency" + str(pt) + ".pdf") f = TFile.Open("plots/efficiency/efficiency" + str(pt) + ".root","RECREATE") canv.Write() f.Close() return [l1Muon,l1MuonAndHoAboveThr,canv,legend,line,paveText,label,newGraph]
def savePlot(plot,plotPull,filename,longPlot=True): if plotPull: plotPull.GetYaxis().SetRangeUser(-5,5) plotPull.SetMarkerStyle(2) cNorm.Clear() cLong.Clear() plotPullTh1 = False tmpLogy = False tmpLogx = False plot.GetXaxis().SetDecimals(True) plot.GetXaxis().SetLabelOffset(0.023) if plotPull: tmpLogy = gPad.GetLogy() tmpLogx = gPad.GetLogx() gPad.SetLogy(False) gPad.SetLogx(False) pNorm1 = TPad("pNorm1","pNorm1",0,0.28,1,1) pNorm2 = TPad("pNorm2","pNorm2",0,0,1,0.28) cNorm.cd() pNorm1.Draw() pNorm2.Draw() pNorm1.SetFillColor(0) pNorm2.SetFillColor(0) pNorm2.SetBottomMargin(0.33) pNorm1.SetLogy(tmpLogy) pNorm1.SetLogx(tmpLogx) pNorm2.SetLogx(tmpLogx) #pNorm1.SetBottomMargin(0.00001) pNorm1.SetBottomMargin(0.025) pNorm1.SetBorderMode(0) pNorm2.SetTopMargin(0.01) #pNorm2.SetTopMargin(0.05) #pNorm2.SetBottomMargin(0.1) pNorm2.SetBorderMode(0) plot.GetXaxis().SetLabelOffset(0.023) plot.GetXaxis().SetLabelSize(0.06) plot.GetXaxis().SetTitleOffset(1.1) plot.GetYaxis().SetLabelSize(0.06) plot.GetXaxis().SetNdivisions(511) pNorm1.SetLeftMargin(0.13) pNorm2.SetLeftMargin(0.13) pxa = plot.GetXaxis() plotPullTh1 = TH1D("plotPullTh1","plotPullTh1",100,pxa.GetBinLowEdge(pxa.GetFirst()),pxa.GetBinUpEdge(pxa.GetLast())) plotPullTh1.SetStats(False) plotPullTh1.GetXaxis().SetDecimals(True) if plotPull: plotPullTh1.GetYaxis().SetRangeUser(-5,5) plotPullTh1.GetXaxis().SetTitle(plot.GetXaxis().GetTitle()) plotPullTh1.GetXaxis().SetNdivisions(511) plotPullTh1.GetXaxis().SetTickLength(0.1) plotPullTh1.GetYaxis().SetTitle("Pull / #sigma") plotPullTh1.GetYaxis().SetTitleFont(132) plotPullTh1.GetYaxis().SetNdivisions(205) plotPullTh1.GetXaxis().SetLabelSize(0.15) plotPullTh1.GetXaxis().SetLabelOffset(0.022) plotPullTh1.GetXaxis().SetTitleSize(0.18) plotPullTh1.GetXaxis().SetTitleOffset(0.78) plotPullTh1.GetXaxis().SetTitleFont(132) plotPullTh1.GetYaxis().SetLabelSize(0.15) plotPullTh1.GetYaxis().SetLabelOffset(0.009) plotPullTh1.GetYaxis().SetTitleSize(0.17) plotPullTh1.GetYaxis().SetTitleOffset(0.32) ##plotPull.GetZaxis().SetLabelSize(0.05) ##plotPull.GetZaxis().SetTitleSize(0.06) ##plotPull.GetZaxis().SetTitleFont(42) plot.GetYaxis().SetTitleOffset(1) plot.GetXaxis().SetTitleSize(0.06) plot.GetYaxis().SetTitleSize(0.06) plot.GetXaxis().SetTitleFont(132) plot.GetYaxis().SetTitleFont(132) plot.GetXaxis().SetLabelFont(132) plot.GetYaxis().SetLabelFont(132) tl = False #if "asym" not in filename and "data" not in filename and "nll" not in filename: #tl = genLegend(plot) cNorm.cd() if plotPull: pNorm1.cd() gPad.SetTopMargin(0.12) plot.Draw() gPad.Update() #if "asym" not in filename and "nll" not in filename: ##if gPad.GetLogy(): ##plot.GetYaxis().SetRangeUser(.8,plot.GetMinimum()*1.3) ##else: ##plot.GetYaxis().SetRangeUser(plot.GetMinimum()*.8,plot.GetMinimum()*1.3) ##if gPad.GetLogy(): ##plot.GetYaxis().SetRangeUser(.8,plot.GetBinContent(plot.GetMinimumBin())*1.3) ##else: ##plot.GetYaxis().SetRangeUser(plot.GetBinContent(plot.GetMinimumBin())*.8,plot.GetBinContent(plot.GetMinimumBin())*1.3) #gPad.Update() ##if "mass" in filename: ##plot.GetYaxis().SetRangeUser(200,150000) ##if removeThings(filename) not in resizedOnce: ##resizedOnce.append(removeThings(filename)) ##if tmpLogy:#gPad.GetLogy(): ##print "FIND: ",gPad.GetLogy(),gPad.GetUymin(), gPad.GetUymax() ###if gPad.GetUymax() < 10: ###plot.GetYaxis().SetRangeUser(0.8,10**(gPad.GetUymax()*1.15)) ###else: ###plot.GetYaxis().SetRangeUser(.8,gPad.GetUymax()*1.15) ####plot.GetYaxis().SetRangeUser(10**gPad.GetUymin(),10**gPad.GetUymax()*1) ##else: ###if gPad.GetUymax() < 10: ###plot.GetYaxis().SetRangeUser(pNorm1.GetUymin(),pNorm1.GetUymax()*1.15) ###else: ##plot.GetYaxis().SetRangeUser(gPad.GetUymin(),gPad.GetUymax()*1.15) gPad.Update() #if "data" in filename: #if "mass" in filename: #if "log" in filename: #plot.GetYaxis().SetRangeUser(1000,100000) #gPad.Update() #elif "time" in filename: #if "log" in filename and not "logx" in filename: #plot.GetYaxis().SetRangeUser(10,30000) #gPad.Update() #plot.Draw() #if plot.getObject(int(plot.numItems())-1).ClassName() == "TPave": #plot.getObject(int(plot.numItems())-1).Draw() if tl: tl.Draw() gPad.Update() if plotPull: pNorm2.cd() plotPullTh1.Draw("AXIS") plotPull.Draw("P") print " ","autoPlots/"+filename+".pdf" cNorm.SaveAs("autoPlots/"+filename+".pdf") cNorm.SaveAs("autoPlots/"+filename+".png") if longPlot and plotPull: cLong.cd() gPad.SetTopMargin(0.12) plot.Draw() if tl: tl.Draw() print " ","autoPlots/"+filename+"-nopull.pdf" cLong.SaveAs("autoPlots/"+filename+"-nopull.pdf") cLong.SaveAs("autoPlots/"+filename+"-nopull.png")
def plot_nice1D(channel, var, bin, low, high, ylabel, xlabel, save, setLog = False, finalcuts = False): result = true # Choose 1, ratio or pull drawPull = False drawRatio = True #folder = 'Trig_Sys' folder = 'JEC_CR1' #folder = 'Preliminary' #folder = 'Lepton_CR' #folder = 'ModelIndep' #folder = 'SusyHiggs' #folder = 'Sys' #No Tau List = [ 'DiPhotonJets','DiphotonBox_Pt_25to250','DiphotonBox_Pt_250toInf','WtoLNuMu','WtoLNuTau','WGamma','ZGToLLG','ZGamma_Inclusive','efake_dd','qcd_dd','GJets_HT_40To100','GJets_HT_100To200','GJets_HT_200To400','GJets_HT_400','SinglePhotonParked','DM','MChi_70'] SF_photon = "( (0.99 * 0.97 * (Pho_Pt>40 && Pho_Pt<50)) + (0.99 * 1.01 * (Pho_Pt>=50) ) )" cut_GGFTrig = " && (hltmatched==1)" stack = THStack('a', 'a') added = TH1D('a', 'a',bin,low,high) added.Sumw2() added_mconly = TH1D('added_mconly', 'added_mconly',bin,low,high) added_mconly.Sumw2() added_nogjets = TH1D('added_nogets', 'added_nogjets',bin,low,high) added_nogjets.Sumw2() justGJets = TH1D('justGJets', 'justGJets',bin,low,high) justGJets.Sumw2() Variables = {} efficiency ={} totalbkg = 0 diphoton = 0. gamma_jet = 0. print ' ' print var for Type in List: pu_weight = "MyWeightData_new" #pu_weight = "MyWeightData_new_sys" #What i used for the pre-approval trig_met = "((0.5*0.977*(1+TMath::Erf( (MET - 28.23) / (25.0*sqrt(2))))) * (MET>40.) )" trig_phoid = "((0.5*0.892*(1+TMath::Erf( (Pho_Pt + 36.8) / (43.8*sqrt(2))))) * (Pho_Pt >30.) )" #Shift up, met #trig_met = "((0.5*0.98*(1+TMath::Erf( (MET - 28.33) / (25.3*sqrt(2))))) * (MET>40.) )" #trig_phoid = "((0.5*0.892*(1+TMath::Erf( (Pho_Pt + 36.8) / (43.8*sqrt(2))))) * (Pho_Pt >30.) )" #Shift down, met #trig_met = "((0.5*0.98*(1+TMath::Erf( (MET - 28.33) / (25.3*sqrt(2))))) * (MET>40.) )" #trig_phoid = "((0.5*0.892*(1+TMath::Erf( (Pho_Pt + 36.8) / (43.8*sqrt(2))))) * (Pho_Pt >30.) )" #trig_phoid = "((0.5*0.89*(1+TMath::Erf( (Pho_Pt - 19.44) / (7.15*sqrt(2))))) * (Pho_Pt >30.) )" #trig_met = "((0.5*0.977*(1+TMath::Erf( (MET - 28.23) / (25.0*sqrt(2))))) * (MET>40.) )" #trig_phoid = "((0.5*0.892*(1+TMath::Erf( (Pho_Pt + 36.8) / (43.8*sqrt(2))))) * (Pho_Pt >30.) )" #trig_met = "((0.5*0.986*(1+TMath::Erf( (MET - 28.0) / (26.0*sqrt(2))))) * (MET>40.) )" puweight = "(1.0)" #dphi_weight = "(0.380604 - 0.162698*TMath::Abs(dphi_pho_met) + 1.36338*pow(TMath::Abs(dphi_pho_met),2) - 0.446155*pow(TMath::Abs(dphi_pho_met),3)- 0.183011*pow(TMath::Abs(dphi_pho_met),4) + 0.103991*pow(TMath::Abs(dphi_pho_met),5) -0.0126396*pow(TMath::Abs(dphi_pho_met),6))" if (Type.startswith('GJets')): other_weight = "(1.7 * (n_jets_mva_loose == 0) + 1.1 * (n_jets_mva_loose > 0))" dphi_weight = "(0.378403 - 0.159585*TMath::Abs(dphi_pho_met) + 1.35184*pow(TMath::Abs(dphi_pho_met),2) - 0.423989*pow(TMath::Abs(dphi_pho_met),3)- 0.19808*pow(TMath::Abs(dphi_pho_met),4) + 0.108294*pow(TMath::Abs(dphi_pho_met),5) - 0.0130729*pow(TMath::Abs(dphi_pho_met),6))" else: other_weight = "(1.0)" dphi_weight = "(1.0)" #PRELIMINARY cut_standard ="(Pho_Pt > 45 && Pho_R9>0.9 &&TMath::Abs(Pho_Eta)<1.442 && sigmaIEtaIEta > 0.001 && sqrt(sigmaIPhiIPhi) > 0.001 && Pho_R9<1.0 && seedCrystalEnergy/(e1x3+e1x5-seedCrystalEnergy) < 0.9 && MET>40. && loose_mu_10==0 && foundvetoEl_10==0 )" #LEPTON_CR #cut_standard= "(Pho_Pt > 45 && Pho_R9>0.9 &&TMath::Abs(Pho_Eta)<1.442 && sigmaIEtaIEta > 0.001 && sqrt(sigmaIPhiIPhi) > 0.001 && seedCrystalEnergy/(e1x3+e1x5-seedCrystalEnergy) < 0.9 && Pho_R9<1.0 && MET>40. && (loose_mu_10==1 || foundvetoEl_10 == 1) )" #MODELINDEP #cut_standard ="(Pho_Pt > 45 && Pho_R9>0.9 &&TMath::Abs(Pho_Eta)<1.442 && sigmaIEtaIEta > 0.001 && sqrt(sigmaIPhiIPhi) > 0.001 && Pho_R9<1.0 && seedCrystalEnergy/(e1x3+e1x5-seedCrystalEnergy) < 0.9 && MET>140. && loose_mu_10==0 && foundvetoEl_10==0 && n_jets_mva_loose < 2 && (TMath::Abs(dphi_jet_pho) <2.5 || dphi_jet_pho == -99) )" #SUSYHIGGS #cut_standard= "(Pho_Pt > 45 && Pho_Pt<60. && Pho_R9>0.9 &&TMath::Abs(Pho_Eta)<1.442 && sigmaIEtaIEta > 0.001 && sqrt(sigmaIPhiIPhi) > 0.001 && seedCrystalEnergy/(e1x3+e1x5-seedCrystalEnergy) < 0.9 && Pho_R9<1.0 && MET>40. && MetSig > 20 && loose_mu_10==0 && foundvetoEl_10 == 0 && MT > 100. && HT < 100. && minMET > 45 && TMath::Abs(TMath::Log10(pvalue)) > 2 && angle>1.2)" #angle>1.2 #minMET>45. && angle > 1.2 && TMath::Abs(TMath::Log10(pvalue)) > 2 && HT < 100.)" weight = "(" + pu_weight + "*"+ other_weight + "*" + dphi_weight + "*" + trig_phoid + "*" +trig_met + "*" +SF_photon+")" Variables[Type] = TH1F(Type+save+channel, Type+save+channel, bin, low, high) Variables[Type].Sumw2() histName = Type+save+channel if Type.startswith("DiPhoton") or Type.startswith("DiphotonBox"): Variables[Type].SetFillColor(ROOT.kMagenta-2) Variables[Type].SetLineColor(ROOT.kMagenta-2) Trees[Type].Draw(var + " >> " + histName, "(" + cut_standard + " ) * 1 *"+weight , "goff") Variables[Type].Scale(lumi / Nevents[Type] * xsec[Type]) stack.Add(Variables[Type],"hist") added.Add(Variables[Type]) added_mconly.Add(Variables[Type]) added_nogjets.Add(Variables[Type]) if Type.startswith("WtoLNuMu"): Variables[Type].SetFillColor(ROOT.kMagenta-2) Variables[Type].SetLineColor(ROOT.kMagenta-2) Trees[Type].Draw(var + " >> " + histName , "(" + cut_standard + " )* 1 *" +weight,"goff") Variables[Type].Scale(lumi / Nevents[Type] * xsec[Type]) stack.Add(Variables[Type],"hist") added.Add(Variables[Type]) added_mconly.Add(Variables[Type]) added_nogjets.Add(Variables[Type]) if Type.startswith("WtoLNuTau"): Variables[Type].SetFillColor(ROOT.kMagenta-2) Variables[Type].SetLineColor(ROOT.kMagenta-2) Trees[Type].Draw(var + " >> " + histName , "(" + cut_standard + " && ( TMath::Abs(gen_pdg) < 15 ) )* 1 *" +weight,"goff") Variables[Type].Scale(lumi / Nevents[Type] * xsec[Type]) stack.Add(Variables[Type],"hist") added.Add(Variables[Type]) added_mconly.Add(Variables[Type]) added_nogjets.Add(Variables[Type]) if Type.startswith("WGamma"): Variables[Type].SetFillColor(ROOT.kGreen-3) Variables[Type].SetLineColor(ROOT.kGreen-3) Trees[Type].Draw(var + " >> " + histName, "(" + cut_standard + ") * 1.05 *"+weight , "goff") Variables[Type].Scale(lumi / Nevents[Type] * xsec[Type]) stack.Add(Variables[Type],"hist") added.Add(Variables[Type]) added_mconly.Add(Variables[Type]) added_nogjets.Add(Variables[Type]) if Type.startswith('ZGamma_Inclusive'): Variables[Type].SetFillColor(ROOT.kYellow-4) Variables[Type].SetLineColor(ROOT.kYellow-4) Trees[Type].Draw(var + " >> " + histName, "(" + cut_standard + " && isZnn==1 ) * 1.2 * "+weight , "goff") Variables[Type].Scale(lumi / Nevents[Type] * xsec[Type]) stack.Add(Variables[Type],"hist") added.Add(Variables[Type]) added_mconly.Add(Variables[Type]) added_nogjets.Add(Variables[Type]) if Type.startswith('ZGToLLG'): Variables[Type].SetFillColor(ROOT.kYellow-4) Variables[Type].SetLineColor(ROOT.kYellow-4) Trees[Type].Draw(var + " >> " + histName, "(" + cut_standard + ")*"+weight , "goff") Variables[Type].Scale(lumi / Nevents[Type] * xsec[Type]) stack.Add(Variables[Type],"hist") added.Add(Variables[Type]) added_mconly.Add(Variables[Type]) added_nogjets.Add(Variables[Type]) if Type.startswith("qcd"): Variables[Type].SetFillColor(9) Variables[Type].SetLineColor(9) Trees[Type].Draw(var + " >> " + histName,"(" +cut_standard +cut_GGFTrig + "&& (HoE < 0.05 && sigmaIEtaIEta < 0.015 ))* (1.503 + 981./pow(Pho_Pt,1.75))" , "goff") stack.Add(Variables[Type],"hist") added.Add(Variables[Type]) added_nogjets.Add(Variables[Type]) # if Type.startswith("PJets_"): if Type.startswith("GJets_"): Variables[Type].SetFillColor(ROOT.kRed-7) Variables[Type].SetLineColor(ROOT.kRed-7) Trees[Type].Draw(var + " >> " + histName, "(" + cut_standard + ") * 1.0 * "+weight , "goff") Variables[Type].Scale(lumi / Nevents[Type] * xsec[Type]) stack.Add(Variables[Type],"hist") added.Add(Variables[Type]) added_mconly.Add(Variables[Type]) justGJets.Add(Variables[Type]) if Type.startswith("efake_dd"): Variables[Type].SetFillColor(7) Variables[Type].SetLineColor(7) Trees[Type].Draw(var + " >> " + histName , "(" + cut_standard + ") * (0.0238) ","goff") stack.Add(Variables[Type],"hist") added.Add(Variables[Type]) added_nogjets.Add(Variables[Type]) ## if Type.startswith("MChi_120"): ## Variables[Type].SetLineColor(1) ## Variables[Type].SetLineWidth(3) ## Variables[Type].SetLineStyle(5) ## Trees[Type].Draw(var + " >> " + histName, "(" + cut_standard + ") *"+weight , "goff") ## Variables[Type].Scale(lumi / Nevents[Type] * xsec[Type]) if Type.startswith("MChi_70"): Variables[Type].SetLineColor(1) Variables[Type].SetLineWidth(3) Variables[Type].SetLineStyle(8) Trees[Type].Draw(var + " >> " + histName, "(" + cut_standard + ") *"+weight , "goff") Variables[Type].Scale(lumi / Nevents[Type] * xsec[Type]) ## if Type.startswith("MChi_90"): ## Variables[Type].SetLineColor(1) ## Variables[Type].SetLineWidth(3) ## Variables[Type].SetLineStyle(8) ## Trees[Type].Draw(var + " >> " + histName, "(" + cut_standard + ") *"+weight , "goff") ## Variables[Type].Scale(lumi / Nevents[Type] * xsec[Type]) ## if Type.startswith("MChi_80"): ## Variables[Type].SetLineColor(1) ## Variables[Type].SetLineWidth(3) ## Variables[Type].SetLineStyle(8) ## Trees[Type].Draw(var + " >> " + histName, "(" + cut_standard + ") *"+weight , "goff") ## Variables[Type].Scale(lumi / Nevents[Type] * xsec[Type]) ## if Type.startswith("MChi_100"): ## Variables[Type].SetLineColor(1) ## Variables[Type].SetLineWidth(3) ## Variables[Type].SetLineStyle(8) ## Trees[Type].Draw(var + " >> " + histName, "(" + cut_standard + ") *"+weight , "goff") ## Variables[Type].Scale(lumi / Nevents[Type] * xsec[Type]) if Type.startswith("DM"): Variables[Type].SetLineColor(2) Variables[Type].SetLineWidth(3) Variables[Type].SetLineStyle(8) Trees[Type].Draw(var + " >> " + histName, "(" + cut_standard + ") *"+weight , "goff") Variables[Type].Scale(lumi / Nevents[Type] * xsec[Type] * 1000) if Type.startswith("SinglePhotonParked"): Variables[Type].SetMarkerStyle(20) Trees[Type].Draw(var + " >> " + histName, "(" + cut_standard + cut_GGFTrig +")" , "goff") # if Type.startswith("PJets_"): if Type.startswith("GJets_"): gamma_jet += round(Variables[Type].Integral(0,bin+1),2) if Type.startswith("Di"): diphoton += round(Variables[Type].Integral(0,bin+1),2) if Variables[Type].Integral(0,bin+1) != 0: if not (Type.startswith("MChi") or Type.startswith("DM") or Type.startswith("SinglePhoton")): totalbkg+= Variables[Type].Integral(0,bin+1) efficiency[Type] = Variables[Type].Integral()/Nevents[Type] lumi_error = 0.026 qcd_error = 0.35 efake_error = 0.06 pjets_error = 0.16 pscale_error = 0.04 met_error = 0.04 kfac_error = 0.05 ratiosys = TH1D('Ratio2', 'Ratio2', bin, low, high) ratiosys = Variables['SinglePhotonParked'].Clone() uncert_list = [] uncertband = added.Clone(); List_1 = ['DiPhotonJets', 'DiphotonBox_Pt_25to250','DiphotonBox_Pt_250toInf', 'WtoLNuMu','WtoLNuTau' ,'GJets_HT_40To100','GJets_HT_100To200','GJets_HT_200To400','GJets_HT_400','WGamma','ZGamma_Inclusive','qcd_dd','efake_dd','ZGToLLG'] #List_1 = ['DiPhotonJets', 'DiphotonBox_Pt_25to250','DiphotonBox_Pt_250toInf', 'WtoLNuMu','GJets_HT_40To100','GJets_HT_100To200','GJets_HT_200To400','GJets_HT_400','WGamma','ZGamma_Inclusive','qcd_dd','efake_dd','ZGToLLG'] fullbin = 0. fullbinerror = 0. qcd_uncert = 0. efake_uncert = 0. GJets_uncert = 0. Wg_uncert = 0. Zg_uncert = 0. if folder.startswith('Susy'): MC_error = 0.075 else: MC_error = 0.05 for hbin in range(0,uncertband.GetNbinsX()+1): uncert = 0.0 totalbin = 0. for i in List_1: #print i,Variables[i].GetBinContent(hbin+1) if (i.startswith('qcd')): #print 'QCD loop : ' , Variables[i].GetBinContent(hbin+1) ,' +/- ' , (Variables[i].GetBinContent(hbin+1)*qcd_error) , ' % ', round((Variables[i].GetBinContent(hbin+1)*qcd_error)/Variables[i].GetBinContent(hbin+1),2)*100 qcd_uncert += (Variables[i].GetBinContent(hbin+1)*qcd_error) uncert += (Variables[i].GetBinContent(hbin+1)*qcd_error) #uncert_stat += Variables[i].GetBinError(hbin+1)**2 elif (i.startswith('efake')): efake_uncert += (Variables[i].GetBinContent(hbin+1)*efake_error) uncert += (Variables[i].GetBinContent(hbin+1)*efake_error) #uncert_stat += Variables[i].GetBinError(hbin+1)**2 else: if (i.startswith('GJets')): GJets_uncert += Variables[i].GetBinContent(hbin+1)*0.16 uncert += Variables[i].GetBinContent(hbin+1)*0.16 else: uncert += Variables[i].GetBinContent(hbin+1)*MC_error if (i.startswith('WGamma')): Wg_uncert += Variables[i].GetBinContent(hbin+1)*MC_error if (i.startswith('ZGamma_Inclusive')): Zg_uncert += Variables[i].GetBinContent(hbin+1)*MC_error #uncert_stat += Variables[i].GetBinError(hbin+1)**2 totalbin += round( Variables[i].GetBinContent(hbin+1),2) #print added.GetBinContent(hbin+1) uncert = sqrt( uncert**2 + added.GetBinError(hbin+1)**2 ) #print ' ' #if (totalbin>0.0): # print 'Bin Content Bkg : ', totalbin, ' ', uncert, ' % ' , round(uncert/totalbin,2)*100 #else: # print 'Bin Content Bkg : ', totalbin, ' ', uncert, ' % 0.0 ' #print 'Bin Content Data: ', round(Variables['SinglePhotonParked'].GetBinContent(hbin+1),2), ' ',round(Variables['SinglePhotonParked'].GetBinError(hbin+1),2) , ' % ' , round(Variables['SinglePhotonParked'].GetBinError(hbin+1)/Variables['SinglePhotonParked'].GetBinContent(hbin+1),2)*100 #print ' ' fullbin += totalbin fullbinerror += uncert #print 'Total : ' , fullbin ,' +/- ' ,fullbinerror, ' % ' , round(uncert/totalbin,2)*100 #print 'QCD : ' , Variables['qcd_dd'].Integral(0,hbin+1), ' +/- ' ,qcd_uncert, ' % ' , round(qcd_uncert/Variables['qcd_dd'].Integral(0,hbin+1),2)*100 #print 'Efake : ' , Variables['efake_dd'].Integral(0,hbin+1), ' +/- ' ,efake_uncert, ' % ' , round(efake_uncert/Variables['efake_dd'].Integral(0,hbin+1),2)*100 #print 'PJets : ' , gamma_jet, ' +/- ' ,GJets_uncert, ' % ' , round(GJets_uncert/gamma_jet,2)*100 #print 'ZGamm : ' , Variables['ZGamma_Inclusive'].Integral(0,hbin+1), ' +/- ' ,Zg_uncert, ' % ' , round(Zg_uncert/Variables['ZGamma_Inclusive'].Integral(0,hbin+1),2)*100 #print 'WGamm : ' , Variables['WGamma'].Integral(0,hbin+1), ' +/- ' ,Wg_uncert, ' % ' , round(Wg_uncert/Variables['WGamma'].Integral(0,hbin+1),2)*100 #print ' ' #lumi_error = 0.026 #qcd_error = 0.35 #efake_error = 0.06 #other_error = 0.05 #pjets_error = 0.20 #ratiosys = TH1D('Ratio2', 'Ratio2', bin, low, high) #ratiosys = Variables['SinglePhotonParked'].Clone() #uncert_list = [] #uncertband = added.Clone(); #List_1 = ['DiPhotonJets', 'DiphotonBox_Pt_25to250','DiphotonBox_Pt_250toInf', 'WtoLNuMu','WtoLNuTau' ,'GJets_HT_40To100','GJets_HT_100To200','GJets_HT_200To400','GJets_HT_400','WGamma','ZGamma_Inclusive','qcd_dd','efake_dd','ZGToLLG'] #List_1 = ['DiPhotonJets', 'DiphotonBox_Pt_25to250','DiphotonBox_Pt_250toInf', 'WtoLNuMu','GJets_HT_40To100','GJets_HT_100To200','GJets_HT_200To400','GJets_HT_400','WGamma','ZGamma_Inclusive','qcd_dd','efake_dd','ZGToLLG'] #for hbin in range(0,uncertband.GetNbinsX()+1): #uncert_lumi = 0.026 #uncert_qcd = 0.35 #uncert_efake = 0.1 #uncert_other = 0.05 #uncert_stat = 0. #uncert_pjets = 0.2 #totalbin = 0. #for i in List_1: # if (i.startswith('qcd')): # uncert_qcd += (Variables[i].GetBinContent(hbin+1)*qcd_error) # uncert_stat += Variables[i].GetBinError(hbin+1)**2 # test = sqrt( ((Variables[i].GetBinContent(hbin+1)*qcd_error))**2 + (Variables[i].GetBinError(hbin+1))**2 ) # elif (i.startswith('efake')): # uncert_efake += (Variables[i].GetBinContent(hbin+1)*efake_error) # uncert_stat += Variables[i].GetBinError(hbin+1)**2 # test = sqrt( (Variables[i].GetBinContent(hbin+1)*efake_error)**2 + (Variables[i].GetBinError(hbin+1))**2 ) # elif (i in xsec.keys()): # if(i.startswith('GJet')): # uncert_pjets +=(Variables[i].GetBinContent(hbin+1)*pjets_error) # uncert_lumi += (efficiency[i]*xsec[i]) # uncert_other += (Variables[i].GetBinContent(hbin+1)*other_error) # uncert_stat += Variables[i].GetBinError(hbin+1)**2 # test = sqrt( (lumi_error*((efficiency[i]*xsec[i])))**2 + ((Variables[i].GetBinContent(hbin+1)*other_error))**2 + (Variables[i].GetBinError(hbin+1))**2 ) #print "bin number: " ,hbin+1, " sample: " ,i," number of events: " , Variables[i].GetBinContent(hbin+1) , " uncert_efake: ", uncert_efake," uncert_qcd: ",uncert_qcd," uncert_other: ",uncert_other," uncert_stat: ", uncert_stat," uncert_lumi: ",uncert_lumi #print i, " bin content: ",round( Variables[i].GetBinContent(hbin+1),2), " error: " , round(test,2), " %: " , round(test/(Variables[i].GetBinContent(hbin+1) +1),2) * 100 # totalbin += round( Variables[i].GetBinContent(hbin+1),2) #uncert = sqrt( (lumi_error*uncert_lumi)**2 + uncert_qcd**2 + uncert_efake**2 + uncert_other**2 + uncert_stat + uncert_pjets**2) #print ' ' #print 'Bin Content Bkg : ', totalbin, ' ', uncert, ' % ' , round(uncert/totalbin,2)*100 #print 'Bin Content Data: ', round(Variables['SinglePhotonParked'].GetBinContent(hbin+1),2), ' ',round(Variables['SinglePhotonParked'].GetBinError(hbin+1),2) , ' % ' , round(Variables['SinglePhotonParked'].GetBinError(hbin+1)/Variables['SinglePhotonParked'].GetBinContent(hbin+1),2)*100 #print ' ' #print "bin number: " ,hbin+1," total bkg. ",added.GetBinContent(hbin+1)," +/- ",uncert #sys = sqrt( (lumi_error**2)*uncert_lumi + uncert_qcd**2 + uncert_efake**2 + uncert_other**2 ) ratiosys.SetBinContent(hbin+1,0.0) if (added.GetBinContent(hbin+1)>0): #ratiosys.SetBinError(hbin+1,sys/added.GetBinContent(hbin+1)) ratiosys.SetBinError(hbin+1,uncert/added.GetBinContent(hbin+1)) else: ratiosys.SetBinError(hbin+1,0) if uncertband.GetBinContent(hbin+1) != 0: dummy = 1.0 #print uncertband.GetBinContenthbin+1),'+/-',uncert,'(',100*uncert/uncertband.GetBinContent(hbin+1),'%)' uncertband.SetBinError(hbin+1,uncert); added.SetBinError(hbin+1,uncert); uncert_list.append(uncert) if save.startswith('Pho_Pt'): print ' ' print 'Total : ' , fullbin ,' +/- ' ,fullbinerror, ' % ' #, round(uncert/totalbin,2)*100 print 'QCD : ' , Variables['qcd_dd'].Integral(0,hbin+1), ' +/- ' ,qcd_uncert, ' % ' #, round(qcd_uncert/Variables['qcd_dd'].Integral(0,hbin+1),2)*100 print 'Efake : ' , Variables['efake_dd'].Integral(0,hbin+1), ' +/- ' ,efake_uncert, ' % ' #, round(efake_uncert/Variables['efake_dd'].Integral(0,hbin+1),2)*100 print 'PJets : ' , gamma_jet, ' +/- ' ,GJets_uncert, ' % ' #, round(GJets_uncert/gamma_jet,2)*100 print 'ZGamm : ' , Variables['ZGamma_Inclusive'].Integral(0,hbin+1), ' +/- ' ,Zg_uncert, ' % ' #, round(Zg_uncert/Variables['ZGamma_Inclusive'].Integral(0,hbin+1),2)*100 print 'WGamm : ' , Variables['WGamma'].Integral(0,hbin+1), ' +/- ' ,Wg_uncert, ' % ' #, round(Wg_uncert/Variables['WGamma'].Integral(0,hbin+1),2)*100 print ' ' Pull = TH1D('Pull', 'Pull', bin, low, high) Pull.Sumw2() Pull = Variables['SinglePhotonParked'].Clone() Pull.Add(added,-1) Ratio = TH1D('Ratio', 'Ratio', bin, low, high) Ratio.Sumw2() Ratio = Variables['SinglePhotonParked'].Clone() Ratio.Add(added,-1) Ratio.Divide(added) uncertband.SetFillStyle(3244); uncertband.SetFillColor(33); gStyle.SetHatchesLineWidth(1) legend = TLegend(.60,.60,.92,.92) legend. AddEntry(Variables['GJets_HT_40To100'],"#gamma + Jets" , "f") legend . AddEntry( Variables['qcd_dd'], "Jet Faking Photon" , "f") # legend . AddEntry( Variables['PJets_50to80'], "#gamma + Jets" , "f") legend . AddEntry( Variables['efake_dd'], "Electron Faking Photon" , "f") #legend . AddEntry( Variables['W2lnuEl'], "W #rightarrow l #nu" , "f") legend . AddEntry( Variables['ZGamma_Inclusive'],"Z #gamma","f") legend . AddEntry( Variables['WGamma'], "W #gamma #rightarrow l #nu #gamma" , "f") #legend . AddEntry( Variables['DiPhotonJets'], "#gamma #gamma" , "f") legend . AddEntry( Variables['WtoLNuMu'], "W #rightarrow #mu(#tau) #nu & #gamma #gamma " , "f") #legend . AddEntry( Variables['WtoLNuTau'], "W #rightarrow #tau #nu" , "f") #legend . AddEntry( Variables['ZGToLLG'],"Z #rightarrow l l #gamma","f") #legend . AddEntry( Variables['DoubleMu'], "Data Driven Z #rightarrow #nu #nu #gamma","f") #legend . AddEntry( Variables['Signal_GluGlu'], "GGF Signal X 1K", "l") #legend . AddEntry( Variables['MChi_120'], "M_{#Chi} = 120", "l") legend . AddEntry( Variables['DM'], "Dark Matter", "l") legend . AddEntry( Variables['MChi_70'], "M_{#Chi} = 70","l") legend . AddEntry( Variables['SinglePhotonParked'], "Data", "p") c4 = TCanvas("c4","c4", 900, 1000) c4.SetBottomMargin(0.3) c4.SetRightMargin(0.06) #stack.SetMaximum( stack.GetMaximum() + 10*stack.GetMaximum() ) #stack.SetMaximum( 0.01*stack.GetMaximum()) #stack.SetMaximum(Variables['SinglePhotonParked'].GetMaximum()*10 ) if save.startswith('ratio') or save.startswith('dphi_pfmetg'): stack.SetMaximum(Variables['SinglePhotonParked'].GetMaximum()*100 ) stack.SetMinimum(0.1) if setLog: c4.SetLogy() stack.SetMaximum( stack.GetMaximum() + 100*stack.GetMaximum() ) stack.Draw() #stack.GetYaxis().CenterTitle() stack.GetYaxis().SetTitle(ylabel) stack.GetYaxis().CenterTitle() stack.GetXaxis().SetTitle(xlabel) if(result): stack.GetXaxis().SetLabelSize(0) stack.GetXaxis().SetTitle('') uncertband.Draw("samee2") if(result): Variables['SinglePhotonParked'].Draw("Esame") #Variables['MChi_120'].Draw("same") Variables['MChi_70'].Draw("same") Variables['DM'].Draw("same") #print "looking at stack first bin: " #print added.GetBinContent(6), added.GetBinContent(7),added.GetBinContent(8),added.GetBinContent(9),added.GetBinContent(10) #print Variables['SinglePhotonParked'].GetBinContent(6), Variables['SinglePhotonParked'].GetBinContent(7),Variables['SinglePhotonParked'].GetBinContent(8),Variables['SinglePhotonParked'].GetBinContent(9),Variables['SinglePhotonParked'].GetBinContent(10) legend.SetShadowColor(0); legend.SetFillColor(0); legend.SetLineColor(0); #legend.Draw("same") #if save.startswith('MT') or save.startswith('MET') or save.startswith('njets') or save.startswith('Pho_Pt'): #legend.Draw("same") latex2 = TLatex() latex2.SetNDC() latex2.SetTextSize(0.035) latex2.SetTextAlign(31) # align right latex2.DrawLatex(0.87, 0.95, lumi_str+" fb^{-1} (8 TeV)"); latex3 = TLatex() latex3.SetNDC() latex3.SetTextSize(0.75*c4.GetTopMargin()) latex3.SetTextFont(62) latex3.SetTextAlign(11) # align right latex3.DrawLatex(0.22, 0.85, "CMS"); latex3.SetTextSize(0.5*c4.GetTopMargin()) latex3.SetTextFont(52) latex3.SetTextAlign(11) latex3.DrawLatex(0.20, 0.8, "Preliminary"); toterr = 0 for i in range(bin): i += 1 toterr += added.GetBinError(i) #print i,' ',added.GetBinContent(i),' +/- ',added.GetBinError(i), ' Data is: ', Variables['SinglePhotonParked'].GetBinContent(i) if Variables['SinglePhotonParked'].GetBinContent(i) != 0 : #if Pull.GetBinContent(i) != 0: Pull.SetBinContent(i,Pull.GetBinContent(i)/Pull.GetBinError(i)) else: Pull.SetBinContent(i,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) if (drawPull): Pull.SetMarkerStyle(20) Pull.SetMaximum(5.0 ) Pull.SetMinimum(-5.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(6) Pull.Draw("HIST") if (drawRatio): ratiosys.SetFillColor(33) #SetFillColor(ROOT.kYellow) ratiosys.SetLineColor(33) #SetLineColor(1) ratiosys.SetLineWidth(1) ratiosys.SetMaximum(2) ratiosys.SetMinimum(-2) ratiosys.GetXaxis().SetTitle(xlabel) ratiosys.GetYaxis().SetTitleSize(0.04) ratiosys.GetYaxis().SetTitle('Data-Bkg/Bkg.') ratiosys.GetYaxis().SetNdivisions(5) ratiosys.SetMarkerSize(0) if(result): ratiosys.Draw("e2") Ratio.SetMarkerStyle(20) Ratio.SetMarkerColor(1) Ratio.SetLineColor(1) Ratio.SetMarkerSize(0.8) if(result): Ratio.Draw("esame") f1 = TF1("f1","0",0,5000); f1.SetLineColor(4); f1.SetLineStyle(2); f1.SetLineWidth(2); f1.Draw("same") if (drawRatio): c4.SaveAs(folder+'/StackedHisto_' + save + '.pdf') if (drawPull): c4.SaveAs(folder+'/StackedHisto_' + save + '.pdf') if save.startswith('Pho_Pt'): print "*******************************************************" print "bkg scaled to ",lumi,"/pb: " ,round(totalbkg,2) , " +/- ", sqrt(toterr**2) print "Data: ", Variables['SinglePhotonParked'].Integral(0,bin+1) # print "Mchi 120: ", lumi,"/pb: ",round(Variables['MChi_120'].Integral(0,bin+1),2),"Significance: ",round(Variables['MChi_120'].Integral(0,bin+1)/sqrt(totalbkg),2) print "Mchi 70: ", lumi,"/pb: " ,round(Variables['MChi_70'].Integral(0,bin+1),2), "Significance: ", round(Variables['MChi_70'].Integral(0,bin+1)/sqrt(totalbkg),2) # print "Mchi 80: ", lumi,"/pb: " ,round(Variables['MChi_80'].Integral(0,bin+1),2), "Significance: ", round(Variables['MChi_80'].Integral(0,bin+1)/sqrt(totalbkg),2) # print "Mchi 90: ", lumi,"/pb: " ,round(Variables['MChi_90'].Integral(0,bin+1),2), "Significance: ", round(Variables['MChi_90'].Integral(0,bin+1)/sqrt(totalbkg),2) # print "Mchi 100: ", lumi,"/pb: " ,round(Variables['MChi_100'].Integral(0,bin+1),2), "Significance: ", round(Variables['MChi_100'].Integral(0,bin+1)/sqrt(totalbkg),2) print "Gamma + Jet: " , gamma_jet, " $\pm$ " ,round(gamma_jet/round(totalbkg,2),2) * 100 print "Diphoton: ", diphoton, " $\pm$ " ,round(diphoton/round(totalbkg,2),2) * 100 print "E fake: ", round(Variables['efake_dd'].Integral(0,bin+1),2)," $\pm$ " , round(round(Variables['efake_dd'].Integral(0,bin+1),2)/round(totalbkg,2),2) * 100 print "Jet fake: ", round(Variables['qcd_dd'].Integral(0,bin+1),2)," $\pm$ " , round(round(Variables['qcd_dd'].Integral(0,bin+1),2)/round(totalbkg,2),2) * 100 print "Wgamma : ", round(Variables['WGamma'].Integral(0,bin+1),2), " $\pm$ " ,round(round(Variables['WGamma'].Integral(0,bin+1),2)/round(totalbkg,2),2) * 100 print "ZGamma : ", round(Variables['ZGamma_Inclusive'].Integral(0,bin+1),2)," $\pm$ " , round( round(Variables['ZGamma_Inclusive'].Integral(0,bin+1),2)/round(totalbkg,2),2) * 100 print "WtoLNuMu : ", round(Variables['WtoLNuMu'].Integral(0,bin+1),2)," $\pm$ " , round(round(Variables['WtoLNuMu'].Integral(0,bin+1),2)/round(totalbkg,2),2) * 100 print "WtoLNuTau : ", round(Variables['WtoLNuTau'].Integral(0,bin+1),2)," $\pm$ " , round(round(Variables['WtoLNuTau'].Integral(0,bin+1),2)/round(totalbkg,2),2) * 100 print "ZGToLLG: ", round(Variables['ZGToLLG'].Integral(0,bin+1),2)," $\pm$ " , round(round(Variables['ZGToLLG'].Integral(0,bin+1),2)/round(totalbkg,2),2) * 100 del c4 del stack del Variables del var
def __init__(self, title = '', x_title = None, y_title = None, plot_header = True, ratio = False, x_range = None, y_max = None, y_log_scale = False): """Initializes a new instance of the Plot class. Args: title: The title to set for the histogram plot_header: Whether or not to include whitespace at the top of the plot for the ATLAS label and legend ratio: Whether or not to include a ratio plot x_range: A tuple of (x_min, x_max) y_max: The maximum Y axis value y_log_scale: Use log scale for Y axis """ # Store the title self._title = title self._x_title, self._y_title = x_title, y_title # Store whether or not the user wants to create a plot header self._plot_header = plot_header # Calculate a unique name for the plot components name = _rand_uuid() # Create a canvas self._canvas = TCanvas(name + '_canvas', name, int(self.PLOT_WIDTH), int(self.PLOT_HEIGHT)) SetOwnership(self._canvas, False) # Create the main plot and draw it self._plot = TPad( name + '_plot', name, 0.0, (self.PLOT_RATIO_FRACTION if ratio else 0.0), 1.0, 1.0 ) SetOwnership(self._plot, False) self._plot.SetMargin(*(self.PLOT_MARGINS_WITH_RATIO if ratio else self.PLOT_MARGINS)) self._plot.Draw() # HACK: Draw the plot title. # https://root.cern.ch/phpBB3/viewtopic.php?t=18282. Wonderful. self._draw_title() # Store ranges self._x_range = x_range if y_max is not None: self._set_maximum_value(y_max) # Store log scale self._y_log_scale = y_log_scale # Switch back to the context of the canvas self._canvas.cd() # Create a ratio plot and draw it if requested if ratio: self._ratio_plot = TPad( name + '_ratio', name, 0.0, 0.0, 1.0, self.PLOT_RATIO_FRACTION ) SetOwnership(self._ratio_plot, False) self._ratio_plot.SetMargin(*self.PLOT_RATIO_MARGINS) self._ratio_plot.SetGridy(True) self._ratio_plot.Draw() else: self._ratio_plot = None # Track whether or not we've already drawn to the main pad self._drawn = False # Track whether or not we've already drawn to the ratio pad self._ratio_drawn = False # Track that object which sets up the axes in the main plot self._axes_object = None # Create a structure to track any histograms we generate internally # which need to be added to any legends created self._legend_extras = [] # Create lists of the cloned drawables, just to be certain self._drawables = [] self._ratio_drawables = []
class Plot(object): """Structural class for representing, accessing, and maintaining references to ROOT graphical elements forming a plot, potentially with a ratio subplot. """ # Plotting 'constants' for the plot class. Ideally, one would allow these # to be flexible, but unfortunately ROOT's coordinate system is extremely # inconsistent and fragile, so it is best to fix these values here. You # can change them dynamically with Plot.Whatever = value, but it is # probably best to leave them alone. # TODO: 600x600 and 800x600 are the ATLAS default for square and # rectangular plots respectively. Fix this when everything is calm. PLOT_WIDTH = 1280 # px PLOT_HEIGHT = 1024 # px #PLOT_MARGINS = (0.125, 0.05, 0.1, 0.1) # Left, Right, Bottom, Top PLOT_MARGINS = (0.125, 0.05, 0.1, 0.07) # Left, Right, Bottom, Top PLOT_MARGINS_WITH_RATIO = (0.125, 0.05, 0.025, 0.1) PLOT_RATIO_MARGINS = (0.125, 0.05, 0.325, 0.05) PLOT_TITLE_X = 0.5 PLOT_TITLE_Y = 0.95 PLOT_TITLE_TEXT_SIZE = 0.04 PLOT_TITLE_TEXT_COLOR = 1 PLOT_TITLE_TEXT_FONT = 42 PLOT_HEADER_HEIGHT = 400 # px PLOT_LEGEND_LEFT = 0.45 PLOT_LEGEND_RIGHT = 0.95 PLOT_LEGEND_BOTTOM = 0.7 PLOT_LEGEND_BOTTOM_WITH_RATIO = 0.63 PLOT_LEGEND_TOP = 0.90 PLOT_LEGEND_TOP_WITH_RATIO = 0.86 PLOT_LEGEND_TEXT_SIZE = 0.025 PLOT_LEGEND_TEXT_SIZE_WITH_RATIO = 0.03 PLOT_LEGEND_ROW_SIZE = 0.04 PLOT_LEGEND_ROW_SIZE_WITH_RATIO = 0.045 PLOT_LEGEND_N_COLUMNS = 1 PLOT_LEGEND_PIVOT_COLUMNS = True PLOT_STAT_LEFT = 0.55 PLOT_STAT_LEFT_WITH_RATIO = 0.60 PLOT_STAT_RIGHT = 0.85 PLOT_STAT_RIGHT_WITH_RATIO = 0.93 PLOT_STAT_BOTTOM = 0.15 PLOT_STAT_BOTTOM_WITH_RATIO = 0.07 PLOT_STAT_TOP = 0.4 PLOT_STAT_TOP_WITH_RATIO = 0.45 PLOT_STAT_TEXT_FONT = 42 PLOT_STAT_TEXT_SIZE = 0.03 PLOT_STAT_TEXT_SIZE_WITH_RATIO = 0.04 PLOT_RATIO_FRACTION = 0.3 # fraction of canvas height PLOT_X_AXIS_TITLE_SIZE = 0.042 PLOT_X_AXIS_TITLE_SIZE_WITH_RATIO = 0.14 PLOT_X_AXIS_TITLE_OFFSET = 0.95 PLOT_X_AXIS_TITLE_OFFSET_WITH_RATIO = 0.96 PLOT_X_AXIS_LABEL_SIZE_WITH_RATIO = 0.12 PLOT_Y_AXIS_LABEL_OFFSET = 0.01 PLOT_Y_AXIS_TITLE_SIZE = 0.042 PLOT_Y_AXIS_TITLE_SIZE_WITH_RATIO = 0.06 PLOT_Y_AXIS_TITLE_OFFSET = 1.0 PLOT_Y_AXIS_TITLE_OFFSET_WITH_RATIO = 0.95 PLOT_Y_AXIS_LABEL_SIZE_WITH_RATIO = 0.05 PLOT_RATIO_Y_AXIS_TITLE_SIZE = 0.12 PLOT_RATIO_Y_AXIS_TITLE_OFFSET = 0.40 PLOT_RATIO_Y_AXIS_LABEL_SIZE = 0.12 PLOT_RATIO_Y_AXIS_LABEL_OFFSET = PLOT_Y_AXIS_LABEL_OFFSET PLOT_RATIO_Y_AXIS_NDIVISIONS = 504 PLOT_RATIO_Y_AXIS_MINIMUM = 0.6 PLOT_RATIO_Y_AXIS_MAXIMUM = 1.4 PLOT_ERROR_BAND_FILL_STYLE = 3254 # Diagonal lines PLOT_ERROR_BAND_FILL_COLOR = 13 # Gray PLOT_ERROR_BAND_LINE_WIDTH = 0 PLOT_ERROR_BAND_LINE_COLOR = 0 PLOT_RATIO_ERROR_BAND_FILL_STYLE = 3254 # Diagonal lines PLOT_RATIO_ERROR_BAND_FILL_COLOR = 807 # Orange PLOT_RATIO_ERROR_BAND_LINE_WIDTH = 0 PLOT_RATIO_ERROR_BAND_LINE_COLOR = 0 # Stamp settings PLOT_ATLAS_STAMP_TEXT_SIZE = 0.035 PLOT_ATLAS_STAMP_TEXT_SIZE_WITH_RATIO = 0.05 PLOT_ATLAS_STAMP_TEXT_COLOR = 1 PLOT_ATLAS_STAMP_TEXT_FONT = 42 PLOT_ATLAS_STAMP_LEFT = 0.18 PLOT_ATLAS_STAMP_TOP = 0.875 PLOT_ATLAS_STAMP_TOP_WITH_RATIO = 0.82 # Stamp specializations PLOT_ATLAS_STAMP_ATLAS_TEXT_FONT = 72 PLOT_ATLAS_STAMP_ATLAS_LABEL_LEFT = 0.28 PLOT_ATLAS_STAMP_LUMINOSITY_OFFSET = 0.036 PLOT_ATLAS_STAMP_LUMINOSITY_OFFSET_WITH_RATIO = 0.05 PLOT_ATLAS_STAMP_LUMINOSITY_SIZE = 0.062 PLOT_ATLAS_STAMP_LUMINOSITY_SIZE_WITH_RATIO = 0.085 def __init__(self, title = '', x_title = None, y_title = None, plot_header = True, ratio = False, x_range = None, y_max = None, y_log_scale = False): """Initializes a new instance of the Plot class. Args: title: The title to set for the histogram plot_header: Whether or not to include whitespace at the top of the plot for the ATLAS label and legend ratio: Whether or not to include a ratio plot x_range: A tuple of (x_min, x_max) y_max: The maximum Y axis value y_log_scale: Use log scale for Y axis """ # Store the title self._title = title self._x_title, self._y_title = x_title, y_title # Store whether or not the user wants to create a plot header self._plot_header = plot_header # Calculate a unique name for the plot components name = _rand_uuid() # Create a canvas self._canvas = TCanvas(name + '_canvas', name, int(self.PLOT_WIDTH), int(self.PLOT_HEIGHT)) SetOwnership(self._canvas, False) # Create the main plot and draw it self._plot = TPad( name + '_plot', name, 0.0, (self.PLOT_RATIO_FRACTION if ratio else 0.0), 1.0, 1.0 ) SetOwnership(self._plot, False) self._plot.SetMargin(*(self.PLOT_MARGINS_WITH_RATIO if ratio else self.PLOT_MARGINS)) self._plot.Draw() # HACK: Draw the plot title. # https://root.cern.ch/phpBB3/viewtopic.php?t=18282. Wonderful. self._draw_title() # Store ranges self._x_range = x_range if y_max is not None: self._set_maximum_value(y_max) # Store log scale self._y_log_scale = y_log_scale # Switch back to the context of the canvas self._canvas.cd() # Create a ratio plot and draw it if requested if ratio: self._ratio_plot = TPad( name + '_ratio', name, 0.0, 0.0, 1.0, self.PLOT_RATIO_FRACTION ) SetOwnership(self._ratio_plot, False) self._ratio_plot.SetMargin(*self.PLOT_RATIO_MARGINS) self._ratio_plot.SetGridy(True) self._ratio_plot.Draw() else: self._ratio_plot = None # Track whether or not we've already drawn to the main pad self._drawn = False # Track whether or not we've already drawn to the ratio pad self._ratio_drawn = False # Track that object which sets up the axes in the main plot self._axes_object = None # Create a structure to track any histograms we generate internally # which need to be added to any legends created self._legend_extras = [] # Create lists of the cloned drawables, just to be certain self._drawables = [] self._ratio_drawables = [] def save(self, path, extensions = ['pdf']): """Saves this plot to file. Args: path: The path where the plot should be saved. """ # Force an update of the canvas self._canvas.Update() # Save to file for e in extensions: self._canvas.SaveAs(path + '.' + e) def _get_maximum_value(self): """Returns the currently set maximum value (possibly None). """ if hasattr(self, '_maximum_value'): return self._maximum_value return None def _set_maximum_value(self, value): """Sets the current maximum value, possibly including room for a plot header. Args: value: The value to set """ # Check if the current value is not None, and if so, throw an error # because this property should not be set twice if self._get_maximum_value() is not None: raise RuntimeError('maximum value should not be set twice') # If the value is None, ignore it if value is None: return # If the user wants a plot header, then add space for one if self._plot_header: # Grab the plot pad height (in pixels) plot_height = ( self.PLOT_HEIGHT * (self._plot.GetY2() - self._plot.GetY1()) ) # Adjust the height value *= (plot_height + self.PLOT_HEADER_HEIGHT) / plot_height # Set the value self._maximum_value = value def draw(self, *drawables_styles_options): """Plots a collection of plottables to the main plot pad. All TH1 objects are drawn with error bars. THStack elements are only drawn with an error band if one is provided. This method may only be called once Args: drawables_styles_options: Each argument of this function must be of the form (object, style, options), where object is one of the following: - A TH1 object - A TH2 object - A THStack object - A tuple of the form (THStack, TGraph) where the latter represents error bars - A TGraph object - A TLine object style is a tuple of the form (line_color, fill_color, marker_style), and options is a string which will be used for the options argument of the object's Draw method. Plottables will be rendered in the order provided. Axes drawing options (e.g. 'a' or 'same' should not be provided and will be set automatically). A TLine may not be the first drawable element. """ # Make sure there are drawables if len(drawables_styles_options) == 0: raise ValueError('must provide at least one plottable') # Check if we've already drawn if self._drawn: raise RuntimeError('cannot draw twice to a plot') self._drawn = True # Remove None-valued drawables drawables_styles_options = tuple(( (d,s,o) for d,s,o in drawables_styles_options if valid_drawable(d))) # Extract drawables drawables, _, _ = zip(*drawables_styles_options) # Check if there is a maximum value set, and if not, set it if self._get_maximum_value() is None: self._set_maximum_value(maximum_value(drawables)) # Move to the context of the plot pad self._plot.cd() # Iterate through and draw drawables based on type first = True for drawable, style, option in drawables_styles_options: # Check if this a tuple of histogram, error_band if isinstance(drawable, tuple): drawable, error_band = drawable else: error_band = None # Make a clone of the drawable so we don't modify it o = clone(drawable) SetOwnership(o, False) # Add it to the list of drawables self._drawables.append(o) # Set the title appropriately if not is_line(o): o.SetTitle(drawable.GetTitle()) # Style the drawable before it is drawn if style is not None: if is_line(drawable) or is_function(drawable): if isinstance(style, dict): style_line(o, **style) else: style_line(o, *style) else: if isinstance(style, dict): style_histogram(o, **style) else: style_histogram(o, *style) # Set the maximum value of the drawable if supported # HACK: I wish this could go into _handle_axes, but apparently it # can't because ROOT sucks and this has to be set on EVERY # drawable, not just the one with the axes. if is_scatter(o): o.SetMinimum(1 if self._y_log_scale else 0) if is_histo(o) or is_graph(o) or is_stack(o) or is_function(o): o.SetMaximum(self._get_maximum_value()) # With TGraph, this is sometimes necessary. Perhaps with TH1 # too. I'm not sure what happens if we set log scale, but # we'll cross that bridge then. o.SetMinimum(1 if self._y_log_scale else 0) # Include axes if we need to. Store the x-axis range. if first: if is_line(o): raise ValueError('TLine may not be first drawable') if is_graph(o): option += 'a' else: option += 'same' first = False # Draw the drawable o.Draw(option) # TODO: This method of plotting the stats box is a huge hack. We # should plot fit functions separately, and move the stats box # plotting to its own function. Home grow everything, the only # way you can make ROOT work. if is_graph(o) or is_histo(o): if len(o.GetListOfFunctions()) > 0: # HACK: Need to call Update() to paint the fit stats self._plot.Update() stats = o.FindObject("stats") if stats: stats.SetTextFont(Plot.PLOT_STAT_TEXT_FONT) stats.SetTextSize((Plot.PLOT_STAT_TEXT_SIZE_WITH_RATIO if self._ratio_plot else Plot.PLOT_STAT_TEXT_SIZE)) stats.SetX1NDC((Plot.PLOT_STAT_LEFT_WITH_RATIO if self._ratio_plot else Plot.PLOT_STAT_LEFT)) stats.SetY1NDC((Plot.PLOT_STAT_BOTTOM_WITH_RATIO if self._ratio_plot else Plot.PLOT_STAT_BOTTOM)) stats.SetX2NDC((Plot.PLOT_STAT_RIGHT_WITH_RATIO if self._ratio_plot else Plot.PLOT_STAT_RIGHT)) stats.SetY2NDC((Plot.PLOT_STAT_TOP_WITH_RATIO if self._ratio_plot else Plot.PLOT_STAT_TOP)) # Handle axes if not is_line(o): self._handle_axes(o, option) # If there is an error band, draw it if error_band is not None: self._draw_error_band(error_band) if self._y_log_scale: self._plot.SetLogy(1) # TODO: Verify this. It breaks 2D plotting. # HACK: Need to force a redraw of plot axes due to issue with ROOT: # http://root.cern.ch/phpBB3/viewtopic.php?f=3&t=14034 #self._plot.RedrawAxis() def _handle_axes(self, drawable, option): """If there is no object currently registered as the owner of the axes drawn on the main plot, then this will set it. Args: drawable: The graph, histogram or stack whose axes were ALREADY drawn option: The option with which to draw the axes """ # If we already have an axes object, ignore this one if self._axes_object is not None: return # Grab the histogram used for axes style/range manipulation if is_stack(drawable) or is_graph(drawable): axes_histogram = drawable.GetHistogram() else: axes_histogram = drawable self._axes_object = axes_histogram # Grab the histogram used for title manipulation if is_stack(drawable): title_histogram = drawable.GetHists()[0] else: title_histogram = drawable # Grab axes x_axis, y_axis = axes_histogram.GetXaxis(), axes_histogram.GetYaxis() # Grab titles from first histogram if not set explicitly if self._x_title is None: self._x_title = title_histogram.GetXaxis().GetTitle() if self._y_title is None: self._y_title = title_histogram.GetYaxis().GetTitle() if self._x_range is not None: #x_axis.SetRangeUser(*self._x_range) x_axis.SetLimits(*self._x_range) # Style x-axis, or hide it if this plot has a ratio plot if self._ratio_plot: x_axis.SetLabelOffset(999) x_axis.SetTitleOffset(999) else: x_axis.SetTitle(self._x_title) x_axis.SetTitleSize(self.PLOT_X_AXIS_TITLE_SIZE) x_axis.SetTitleOffset(self.PLOT_X_AXIS_TITLE_OFFSET) # Style y-axis if self._ratio_plot: y_axis.SetLabelSize(self.PLOT_Y_AXIS_LABEL_SIZE_WITH_RATIO) y_axis.SetLabelOffset(self.PLOT_Y_AXIS_LABEL_OFFSET) y_axis.SetTitle(self._y_title) y_axis.SetTitleSize( (self.PLOT_Y_AXIS_TITLE_SIZE_WITH_RATIO if self._ratio_plot else self.PLOT_Y_AXIS_TITLE_SIZE) ) y_axis.SetTitleOffset( (self.PLOT_Y_AXIS_TITLE_OFFSET_WITH_RATIO if self._ratio_plot else self.PLOT_Y_AXIS_TITLE_OFFSET) ) # Redraw the drawable with the new style drawable.Draw(option) def _draw_error_band(self, error_band): """Draws an error band on top of histogram objects. Args: error_band: The error band to draw (a TGraphAsymmErrors) """ # Style it # HACK: Setting the marker style to 0 specifies this should be filled # in the legend error_band.SetMarkerStyle(0) error_band.SetMarkerSize(0) error_band.SetFillStyle(self.PLOT_ERROR_BAND_FILL_STYLE) error_band.SetFillColor(self.PLOT_ERROR_BAND_FILL_COLOR) error_band.SetLineWidth(self.PLOT_ERROR_BAND_LINE_WIDTH) error_band.SetLineColor(self.PLOT_ERROR_BAND_LINE_COLOR) # Draw it error_band.Draw('e2same') # Add it to the list of things we need to add to the legend self._legend_extras.append(error_band) def draw_ratio_histogram(self, histogram, draw_unity = True, error_band = None): """Draws a ratio histogram to the ratio pad. Args: histogram: The ratio histogram to draw (use ratio_histogram) draw_unity: Whether or not to draw a line at 1 error_band: An error band to draw under the ratio histogram (see owls_hep.uncertainty.ratio_uncertainty_band) The histogram X axis title is set by draw_histogram if not set explicitly. draw_ratio_histogram should therefore be called after draw_histogram. """ # Check if we've already drawn if self._ratio_drawn: raise RuntimeError('cannot draw twice to a plot') self._ratio_drawn = True # Switch to the context of the ratio pad self._ratio_plot.cd() # Clone the histogram histogram = histogram.Clone(_rand_uuid()) SetOwnership(histogram, False) # Style it x_axis, y_axis = histogram.GetXaxis(), histogram.GetYaxis() x_axis.SetTitleSize(self.PLOT_X_AXIS_TITLE_SIZE_WITH_RATIO) x_axis.SetTitleOffset(self.PLOT_X_AXIS_TITLE_OFFSET_WITH_RATIO) x_axis.SetLabelSize(self.PLOT_X_AXIS_LABEL_SIZE_WITH_RATIO) x_axis.SetTitle(self._x_title) if self._x_range: x_axis.SetLimits(*self._x_range) #x_axis.SetRangeUser(*self._x_range) else: x_axis.SetLimits(self._axes_object.GetXaxis().GetXmin(), self._axes_object.GetXaxis().GetXmax()) #x_axis.SetRangeUser(self._axes_object.GetXaxis().GetXmin(), #self._axes_object.GetXaxis().GetXmax()) y_axis.SetTitleSize(self.PLOT_RATIO_Y_AXIS_TITLE_SIZE) y_axis.SetTitleOffset(self.PLOT_RATIO_Y_AXIS_TITLE_OFFSET) y_axis.SetLabelSize(self.PLOT_RATIO_Y_AXIS_LABEL_SIZE) y_axis.SetLabelOffset(self.PLOT_RATIO_Y_AXIS_LABEL_OFFSET) y_axis.SetRangeUser(self.PLOT_RATIO_Y_AXIS_MINIMUM, self.PLOT_RATIO_Y_AXIS_MAXIMUM) y_axis.SetNdivisions(self.PLOT_RATIO_Y_AXIS_NDIVISIONS, False) # Draw it # NOTE: Have to specify E0 or points out of the vertical range won't # have their error bars drawn: # https://root.cern.ch/phpBB3/viewtopic.php?f=3&t=13329 # histogram.Draw('e0p') # NOTE: Or live with it and get rid of points from zero value bins histogram.Draw('ep') # Draw a line at unity if requested if draw_unity: # Calculate the line coordinates line_min = histogram.GetBinLowEdge(1) max_bin = histogram.GetNbinsX() line_max = (histogram.GetBinLowEdge(max_bin) + histogram.GetBinWidth(max_bin)) # Create and draw the line unit_line = TLine(line_min, 1.0, line_max, 1.0) SetOwnership(unit_line, False) unit_line.SetLineColor(2) # Red unit_line.SetLineWidth(2) unit_line.Draw('same') # If an error band was provided, draw it and add it to our legend # elements if error_band: # Keep ownership of the error band SetOwnership(error_band, False) # Style it error_band.SetMarkerSize(0) error_band.SetFillStyle(self.PLOT_RATIO_ERROR_BAND_FILL_STYLE) error_band.SetFillColor(self.PLOT_RATIO_ERROR_BAND_FILL_COLOR) error_band.SetLineWidth(self.PLOT_RATIO_ERROR_BAND_LINE_WIDTH) error_band.SetLineColor(self.PLOT_RATIO_ERROR_BAND_LINE_COLOR) # Draw it error_band.Draw('e2same') # Now, if we've drawn unity or an error band, redraw our ratio # histogram so that its point lie on top of the unity line or error # band, but use 'same' so that the axes/ticks don't cover the red line if draw_unity or error_band: # histogram.Draw('e0psame') histogram.Draw('epsame') def draw_ratios(self, drawables_styles_options, draw_unity = True, y_range = None, y_title = None): """Draws a drawable to the ratio pad. Args: drawable: The drawable to draw draw_unity: Whether or not to draw a line at 1 """ # Check if we've already drawn if self._ratio_drawn: raise RuntimeError('cannot draw twice to a plot') self._ratio_drawn = True # Switch to the context of the ratio pad self._ratio_plot.cd() # Iterate through and draw drawables based on type first = True for drawable, style, option in drawables_styles_options: # Make a clone of the drawable so we don't modify it o = clone(drawable) SetOwnership(o, False) # Add it to the list of drawables self._ratio_drawables.append(o) # Set the title appropriately if not is_line(o): o.SetTitle(drawable.GetTitle()) # Style the drawable before it is drawn if style is not None: if is_line(drawable) or is_function(drawable): style_line(o, *style) else: style_histogram(o, *style) if not is_line(o): if y_range is not None: o.SetMinimum(y_range[0]) o.SetMaximum(y_range[1]) # Include axes if we need if first: if is_line(o): raise ValueError('TLine may not be first drawable') x_axis, y_axis = o.GetXaxis(), o.GetYaxis() if is_graph(o): option += 'a' else: option += 'same' first = False # Draw the drawable o.Draw(option) x_axis.SetTitleSize(self.PLOT_X_AXIS_TITLE_SIZE_WITH_RATIO) x_axis.SetTitleOffset(self.PLOT_X_AXIS_TITLE_OFFSET_WITH_RATIO) x_axis.SetLabelSize(self.PLOT_X_AXIS_LABEL_SIZE_WITH_RATIO) x_axis.SetTitle(self._x_title) if self._x_range: x_axis.SetLimits(*self._x_range) #x_axis.SetRangeUser(*self._x_range) else: x_axis.SetLimits(self._axes_object.GetXaxis().GetXmin(), self._axes_object.GetXaxis().GetXmax()) #x_axis.SetRangeUser(self._axes_object.GetXaxis().GetXmin(), #self._axes_object.GetXaxis().GetXmax()) y_axis.SetTitleSize(self.PLOT_RATIO_Y_AXIS_TITLE_SIZE) y_axis.SetTitleOffset(self.PLOT_RATIO_Y_AXIS_TITLE_OFFSET) y_axis.SetLabelSize(self.PLOT_RATIO_Y_AXIS_LABEL_SIZE) y_axis.SetLabelOffset(self.PLOT_RATIO_Y_AXIS_LABEL_OFFSET) y_axis.SetNdivisions(self.PLOT_RATIO_Y_AXIS_NDIVISIONS, False) if y_title is not None: y_axis.SetTitle(y_title) self._ratio_plot.Update() def _draw_title(self): """Draws a title on the plot. """ title = TLatex() title.SetTextColor(self.PLOT_TITLE_TEXT_COLOR) title.SetTextFont(self.PLOT_TITLE_TEXT_FONT) title.SetNDC() title.SetTextSize(self.PLOT_TITLE_TEXT_SIZE) title.SetTextAlign(22) title.DrawLatex( self.PLOT_TITLE_X, self.PLOT_TITLE_Y, self._title ) def draw_atlas_label(self, luminosity = None, sqrt_s = None, custom_label = None, atlas_label = None): """Draws an ATLAS stamp on the plot, with an optional categorization label. It is recommended that you construct the Plot with plot_header = True in order to make space for the label. Args: luminosity: The integrated luminosity, in pb^-1 sqrt_s: The center of mass energy, in MeV label: The label to put after 'ATLAS', None to exclude the 'ATLAS' categorization entirely """ # Change context to the plot pad self._plot.cd() # Create the latex object # TODO: Consider using TPaveText to overwrite drawn graphs and # histograms. At least for scatter plots. # TODO: Increase readability: Create two sets of constants - # one for plots with ratio and one for plots without. Select the # correct one in draw_ratio_histogram. stamp = TLatex() # Style it stamp.SetTextColor(self.PLOT_ATLAS_STAMP_TEXT_COLOR) stamp.SetTextSize((self.PLOT_ATLAS_STAMP_TEXT_SIZE_WITH_RATIO if self._ratio_plot else self.PLOT_ATLAS_STAMP_TEXT_SIZE)) stamp.SetTextFont(self.PLOT_ATLAS_STAMP_TEXT_FONT) stamp.SetNDC() top = (self.PLOT_ATLAS_STAMP_TOP_WITH_RATIO if self._ratio_plot else self.PLOT_ATLAS_STAMP_TOP) # Print an ATLAS label on top if atlas_label is not None: # Draw the label stamp.SetTextFont(self.PLOT_ATLAS_STAMP_ATLAS_TEXT_FONT) stamp.DrawLatex(self.PLOT_ATLAS_STAMP_LEFT, top, 'ATLAS') stamp.SetTextFont(self.PLOT_ATLAS_STAMP_TEXT_FONT) stamp.DrawLatex(self.PLOT_ATLAS_STAMP_ATLAS_LABEL_LEFT, top, atlas_label) top -= (self.PLOT_ATLAS_STAMP_TEXT_SIZE_WITH_RATIO if self._ratio_plot else self.PLOT_ATLAS_STAMP_TEXT_SIZE) * 1.3 # Draw the luminosity and sqrt(s) if luminosity is not None or sqrt_s is not None: text = '' if sqrt_s is not None: text += '#sqrt{{s}} = {0:.0f} TeV'.format(sqrt_s / 1.0e6) if luminosity is not None: text += ', ' if luminosity is not None: if luminosity >= 1000.0: text += '{0:.1f} fb^{{-1}}'.format(luminosity / 1000.0) elif luminosity > 100.0: text += '{0:.2f} fb^{{-1}}'.format(luminosity / 1000.0) else: text += '{0:.1f} pb^{{-1}}'.format(luminosity) stamp.DrawLatex(self.PLOT_ATLAS_STAMP_LEFT, top, text) top -= (self.PLOT_ATLAS_STAMP_TEXT_SIZE_WITH_RATIO if self._ratio_plot else self.PLOT_ATLAS_STAMP_TEXT_SIZE) * 1.3 # If requested, draw the custom label or the 'ATLAS' label, # preferring the former if custom_label is not None: # Draw each line of text, decreasing top for each step for text in [t for t in custom_label if t is not None]: stamp.DrawLatex(self.PLOT_ATLAS_STAMP_LEFT, top, text) top -= (self.PLOT_ATLAS_STAMP_TEXT_SIZE_WITH_RATIO if self._ratio_plot else self.PLOT_ATLAS_STAMP_TEXT_SIZE) * 1.3 def draw_pave(self, texts, position): """Draw a text box at the position and fill it with text. Args: texts: String or N-tuple of strings. positon: Absolute position of the form (x1, x2, y1, y2) as an N-tuple of floats, or a string with one of the values "{top,bottom}{left,right}" """ if isinstance(position, basestring): if position == 'topleft': position = (0.15, 0.35, 0.85, 0.75) elif position == 'topright': position = (0.95, 0.75, 0.95, 0.85) elif position == 'bottomleft': position = (0.05, 0.25, 0.05, 0.15) elif position == 'topright': position = (0.95, 0.75, 0.05, 0.15) # Switch to the context of the main plot self._plot.cd() # Create the pave self._pave = TPaveText(position[0], position[2], position[1], position[3], 'NDC') SetOwnership(self._pave, False) # Add the text if isinstance(texts, basestring): self._pave.AddText(texts) else: for t in texts: self._pave.AddText(t) # Draw the pave self._pave.Draw() def draw_legend(self, use_functions = False, legend_entries = None): """Draws a legend onto the plot with the specified histograms. It is recommended that you construct the Plot with plot_header = True in order to make space for the legend. Args: drawables: The elements to include in the legend (via AddEntry) use_functions: Add associated functions to the legend """ # Check if we already have a legend if hasattr(self, '_legend'): raise RuntimeError('legend already exists on this plot') # Check if the plot has been drawn if not self._drawn: raise RuntimeError('plot must be drawn before the legend') # Remove None-valued drawables drawables = tuple((d for d in self._drawables if d is not None)) # Remove TLine objects drawables = tuple((d for d in drawables if not is_line(d))) # If we shouldn't add functions to the legend, remove them if not use_functions: drawables = tuple((d for d in drawables if not isinstance(d, TF1))) # Use only certain entries if legend_entries is not None: def get_drawable_by_title(title): for d in drawables: if d.GetTitle() == title: return d return None drawables = tuple((get_drawable_by_title(e.GetTitle()) for e in legend_entries if e is not None)) drawables = tuple((d for d in drawables if d is not None)) # Switch to the context of the main plot self._plot.cd() # Create the legend self._legend = TLegend(self.PLOT_LEGEND_LEFT, (self.PLOT_LEGEND_BOTTOM_WITH_RATIO if self._ratio_plot else self.PLOT_LEGEND_BOTTOM), self.PLOT_LEGEND_RIGHT, (self.PLOT_LEGEND_TOP_WITH_RATIO if self._ratio_plot else self.PLOT_LEGEND_TOP)) SetOwnership(self._legend, False) # Style it self._legend.SetTextSize(( self.PLOT_LEGEND_TEXT_SIZE_WITH_RATIO if self._ratio_plot else self.PLOT_LEGEND_TEXT_SIZE )) self._legend.SetBorderSize(0) self._legend.SetFillStyle(0) # transparent self._legend.SetNColumns(self.PLOT_LEGEND_N_COLUMNS) # Create a chained list of all drawables. We decompose THStack # objects in reverse order, i.e. top-to-bottom. drawables = \ list(chain(*(drawable_iterable(h, True, True) for h in drawables))) # Add anything to this list that we created internally drawables.extend(self._legend_extras) # Because ROOT draws legend entries from left-to-right across rows and # not top-to-bottom along columns, we need to do a bit of a pivot on # the list so that the histograms appear in the vertical order of the # stack if self.PLOT_LEGEND_PIVOT_COLUMNS: n_entries = len(drawables) n_col = self.PLOT_LEGEND_N_COLUMNS n_row = int(ceil(float(n_entries) / n_col)) self._legend.SetY1(self._legend.GetY2() - n_row * (self.PLOT_LEGEND_ROW_SIZE_WITH_RATIO if self._ratio_plot else self.PLOT_LEGEND_ROW_SIZE)) legend_order = [] for r in xrange(0, n_row): for c in xrange(0, n_col): if (r * n_col + c) == n_entries: # Don't need an outer break, this would only happen on the # last row if n_row * n_col != n_entries break legend_order.append(drawables[r + c * n_row]) else: legend_order = drawables # Add the drawables for drawable in legend_order: SetOwnership(drawable, False) title = drawable.GetTitle() # HACK: Convention: legend for drawables with a non-default # marker style (data) to be drawn as line with point, and with # empty fill (signal) to be drawn as line if drawable.GetMarkerStyle() != 0: self._legend.AddEntry(drawable, title, 'ep') elif drawable.GetFillColor() == 0: self._legend.AddEntry(drawable, title, 'l') else: self._legend.AddEntry(drawable, title, 'f') # Draw the legend self._legend.Draw()
for lep in leps: if lep=='mu': qcdSFs = qcdSF_mu else: qcdSFs = qcdSF_ele for variable in variables: for cut,qcdsf in zip(cuts,qcdSFs): #canvas attributes canx = 900 cany = 1200 c = TCanvas('c','Canvas Named c',canx,cany) c.cd() p1 = TPad('p1','p1',0,0.25,1,1) p1.SetBottomMargin(0.04) p1.Draw() p1.SetLogy(0) p1.SetFrameLineWidth(2) c.cd() p2 = TPad('p2','p2',0,0,1,0.25) p2.SetTopMargin(0.02) p2.SetBottomMargin(0.3) p2.SetFrameLineWidth(2) p2.Draw() c.cd() p1.cd() theFilename = "%sGiuseppe_%s_%s_%s"%(path,cut,variable,lep)
def create_plot_with_ratio(numerator_histograms_or_stack, denominator_histograms_or_stack, canvas_name = 'canvas', canvas_width = 1024.0, canvas_height = 768.0, do_ratio = True, ratio_plot_fraction = 0.35, ratio_plot_title = 'Data / MC', make_legend = True): """This function creates a canvas object with two plots on it, a main plot and a ratio plot. The canvas generated by this function will contain two sub-pads, one with all histograms plotted and a plot below it with the ratio of the numerator histograms to the denominator histograms. The numerator and denominator histograms will not be converted to stacks, so if you pass a list of histograms, they will simply be plotted on top of each other. It is up to you to create a THStack if you want them stacked. Also, aside from the ratio plot, no styling is applied to any of the provided histograms. Args: numerator_histograms_or_stack: A single histogram, an iterable of histograms, or a THStack object which represents the data to use in the numerator of the ratio division. denominator_histograms_or_stack: A single histogram, an iterable of histograms, or a THStack object which represents the data to use in the denominator of the ratio division. Returns: A canvas object containing the two subpads. """ #DR if ratio_plot_fraction is small, switch off the ratio plot if ratio_plot_fraction < 1E-3: do_ratio=False if not do_ratio: denominator_histograms_or_stack=None # Create our ratio histogram if necessary if do_ratio: # Calculate the histograms that we are going to use for division ratio_histo = _get_combined_histogram(numerator_histograms_or_stack) denominator_histo = _get_combined_histogram( denominator_histograms_or_stack ) # Calculate the ratio if ratio_histo.GetSumw2N() == 0: ratio_histo.Sumw2() ratio_histo.Divide(denominator_histo) ratio_histo.SetStats(0) ratio_histo.SetMarkerStyle(21) # Create our canvas canvas = TCanvas(canvas_name, canvas_name, int(canvas_width), int(canvas_height)) if do_ratio: canvas.SetBottomMargin(0.0) # Create the plot pad plot_pad = TPad(canvas_name + '_plot', canvas_name + '_plot', 0.0, ratio_plot_fraction + 0.0075 if do_ratio else 0.0, 1.0, 1.0) if do_ratio: plot_pad.SetTopMargin(0.0) plot_pad.SetBottomMargin(0.0) plot_pad.Draw() plot_pad.cd() # Compute maximum value for axes all_histos = chain(_get_histogram_iterable(numerator_histograms_or_stack), _get_histogram_iterable(denominator_histograms_or_stack)) max_value = max([h.GetMaximum() for h in all_histos]) # Create a legend if requested legend = None if make_legend: legend_height = 200.0 # Pixels, maybe make this configurable as an # argument legend_bottom_margin = 50.0 pad_1_height = canvas_height * (plot_pad.GetY2() - plot_pad.GetY1()) max_value *= (pad_1_height + legend_height + legend_bottom_margin) \ / pad_1_height max_value *= 1.1 # Add a bit of an extra margin legend = TLegend(0.5, (canvas_height - legend_height)/canvas_height, 1.0, 0.98 if do_ratio else 0.93) legend.SetTextSize(0.03) legend.SetBorderSize(0) # No border legend.SetFillStyle(0) # Transparent # Do our plotting. As part of this, draw all stacks first, since the rest # of the histograms will be drawn as points. all_histos = list( chain(_get_histogram_iterable(numerator_histograms_or_stack), _get_histogram_iterable(denominator_histograms_or_stack)) ) def cmp(h1, h2): h1_stack = isinstance(h1, THStack) h2_stack = isinstance(h2, THStack) if h1_stack == h2_stack: return 0 elif h1_stack and not h2_stack: return -1 return 1 all_histos.sort(cmp) first = True for histo in all_histos: histo.SetMaximum(max_value) draw_options = 'ep' if not isinstance(histo, THStack) else '' if first: # Draw the histogram (this has to be done before using # GetHistogram()) histo.Draw(draw_options) # Disable the axis if doing a ratio plot if do_ratio: if isinstance(histo, THStack): histo.GetHistogram().GetXaxis().SetTickLength(0) histo.GetHistogram().GetXaxis().SetLabelOffset(999) else: histo.GetXaxis().SetTickLength(0) histo.GetXaxis().SetLabelOffset(999) else: if isinstance(histo, THStack): histo.GetHistogram().GetXaxis().SetTitleSize(0.08) histo.GetHistogram().GetXaxis().SetTitleOffset(0.90) #histo.GetHistogram().GetXaxis().SetLabelSize(0.08) #print "DRDR xt0",histo.GetHistogram().GetXaxis().GetTitle() else: histo.GetXaxis().SetTitleSize(0.08) histo.GetXaxis().SetTitleOffset(0.90) #histo.GetXaxis().SetLabelSize(0.08) #print "DRDR xt1",histo.GetXaxis().GetTitle() # Style up the y axis if isinstance(histo, THStack): y_title = histo.GetHists()[0].GetYaxis().GetTitle() histo.GetHistogram().GetYaxis().SetTitle(y_title) histo.GetHistogram().GetYaxis().SetTitleSize(0.05) histo.GetHistogram().GetYaxis().SetTitleOffset(0.8) else: histo.GetYaxis().SetTitleSize(0.05) histo.GetYaxis().SetTitleOffset(0.8) first = False histo.Draw(draw_options+"same") else: histo.Draw(draw_options + 'same') # Fill in and draw the legend. We have to grab all histograms again, this # time unpacking any THStack objects, that way each histogram will have its # own entry on the plot. if make_legend: all_histos = chain( _get_histogram_iterable(numerator_histograms_or_stack, True), _get_histogram_iterable(denominator_histograms_or_stack, True) ) # FIXME order should be reversed. And data should be "fp" for histo in all_histos: legend.AddEntry(histo, histo.GetTitle(), 'f') legend.Draw() # Create the ratio pad if necessary if do_ratio: # Create the ratio pad canvas.cd() ratio_pad = TPad(canvas_name + '_ratio', canvas_name + '_ratio', 0.0, 0.0, 1.0, ratio_plot_fraction - 0.0075) ratio_pad.SetTopMargin(0.0) ratio_pad.SetGridy(True) ratio_pad.Draw() ratio_pad.cd() # Set up the ratio pad labels ratio_histo.GetXaxis().SetTitleSize(0.08) ratio_histo.GetXaxis().SetTitleOffset(0.90) ratio_histo.GetXaxis().SetLabelSize(0.08) ratio_histo.GetYaxis().SetTitle(ratio_plot_title) ratio_histo.GetYaxis().SetTitleOffset(0.43) ratio_histo.GetYaxis().SetTitleSize(0.08) ratio_histo.GetYaxis().SetLabelSize(0.08) # Draw the ratio histogram ratio_histo.Draw('ep') # Draw a line at 1 line_min = ratio_histo.GetBinLowEdge(1) max_bin = ratio_histo.GetNbinsX() line_max = ratio_histo.GetBinLowEdge(max_bin) \ + ratio_histo.GetBinWidth(max_bin) unit_line = TLine(line_min, 1.0, line_max, 1.0) unit_line.SetLineColor(2) # Red unit_line.SetLineWidth(2) unit_line.Draw('same') # Now redraw the ratio histogram again, so that the points lie on top of # the red line, but draw same so that the axes/ticks don't cover the red # line ratio_histo.Draw('epsame') # Update the canvas canvas.cd() canvas.Update() # HACK: Work around ROOT/PyROOT's terrible memory management SetOwnership(canvas, False) SetOwnership(plot_pad, False) if legend: SetOwnership(legend, False) if do_ratio: SetOwnership(ratio_histo, False) # DR inclue in do_ratio test SetOwnership(ratio_pad, False) SetOwnership(unit_line, False) return canvas
def sobWeightedPlot(fileName, datasetName, channel, cat, log, mass, tanb): c = TCanvas(fileName, '', 600, 600) c.cd() if log: c.SetLogy(1) f = TFile('Plot_'+fileName+'.root') gROOT.cd() samples = ['ggH', 'Ztt', 'signal', 'data_obs', 'ttbar', 'EWK', 'Fakes', 'ggH_hww'] if fileName.find('emu') != -1 and isSM: samples.append('ggH_hww') histDict = {} for sample in samples: histDict[sample] = tfileGet(f, sample) if not histDict[sample]: print 'Missing histogram', sample, 'in file', 'Plot_'+fileName+'.root' xminInset = 60 # 0 xmaxInset = 180 # 340 (for full range) if tanb > 0: xminInset = mass - 100 xmaxInset = mass + 100 ztt = histDict['Ztt'] ggH = histDict['ggH'] data = histDict['data_obs'] signal = histDict['signal'] ggH_hww = histDict['ggH_hww'] tt = histDict['ttbar'] ewk = histDict['EWK'] fakes = histDict['Fakes'] ztt.GetYaxis().SetRangeUser(0., 1.3*findMaxY(data, 0)) if log: ztt.GetYaxis().SetRangeUser(0.001, 50.*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.) ztt.SetTitleOffset(1.3, 'Y') ztt.SetTitleOffset(1., 'X') 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 ggH_hww: errorBand = ggH_hww.Clone("errorBand") else: errorBand = ztt.Clone("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 ggH_hww: legend.AddEntry(ggH_hww, "H(125 GeV)#rightarrowWW", "F") legend.AddEntry(ztt, "Z#rightarrow#tau#tau","F") legend.AddEntry(tt, "t#bar{t}","F") legend.AddEntry(ewk, "electroweak","F") legend.AddEntry(fakes, "QCD","F") legend.SetX1NDC(0.63) legend.SetX2NDC(1.05) legend.SetY1NDC(0.27) legend.SetY2NDC(0.48) 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 ggH_hww: dataDiff = diffPlot(data, ggH_hww, 1) errBand=getErrorBand(ggH_hww) else: dataDiff = diffPlot(data, ztt, 1) errBand=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*findMinY(dataDiff,0,xminInset,xmaxInset),2.0*findMaxY(dataDiff,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.95) errBandFrame.GetXaxis().SetLabelSize(0.06) 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(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") legendDiff.Draw() pad.RedrawAxis() c.cd() ztt.Draw("hist") ggH.Draw("histsame") if ggH_hww: ggH_hww.Draw("hist same") ztt.Draw("hist same") errorBand.Draw("e2 same") tt.Draw("hist same") ewk.Draw("hist same") fakes.Draw("hist same") data.Draw("pe same") legend.Draw() c.RedrawAxis() padBack.Draw() # clear the background axe pad.Draw() CMSPrelim(datasetName, channel, cat) c.Print('Plot_'+fileName+".eps") c.Print('Plot_'+fileName+".png") c.Print('Plot_'+fileName+".pdf")
## ## \macro_image ## \macro_output ## \macro_code ## ## \author Wim Lavrijsen from ROOT import TCanvas, TPad, TFormula, TF1, TPaveLabel, TH1F, TFile from ROOT import gROOT, gBenchmark c1 = TCanvas( 'c1', 'The FillRandom example', 200, 10, 700, 900 ) c1.SetFillColor( 18 ) pad1 = TPad( 'pad1', 'The pad with the function', 0.05, 0.50, 0.95, 0.95, 21 ) pad2 = TPad( 'pad2', 'The pad with the histogram', 0.05, 0.05, 0.95, 0.45, 21 ) pad1.Draw() pad2.Draw() pad1.cd() gBenchmark.Start( 'fillrandom' ) # # A function (any dimension) or a formula may reference # an already defined formula # form1 = TFormula( 'form1', 'abs(sin(x)/x)' ) sqroot = TF1( 'sqroot', 'x*gaus(0) + [3]*form1', 0, 10 ) sqroot.SetParameters( 10, 4, 1, 20 ) pad1.SetGridx() pad1.SetGridy()
print(len(temp_another_dict)) list1 = [] list2 = [] for i in temp_another_dict: list1.append(float(temp_another_dict[i][0])) list2.append(float(temp_another_dict[i][1])) x = array("d",list1) y = array("d",list2) corr = correlation(x,y) c = TCanvas('canvas','can1',600,600) c.Draw() c.cd() tp1 = TPad('MYDATA','MYDATA',0.0,0.0,1,1) tp1.SetGrid() tp1.Draw() tp1.cd() maximum = 1 bins =500 bin_to_value = (bins/2)/maximum gr_2 = TH1F('h1','myhist',bins, -maximum, maximum) for i in range(len(p_corr_list)): gr_2.Fill(p_corr_list[i],1.0/trials) gr_2.Draw() fitsignal = TF1("FSignal","gaus", -maximum, maximum) # this gaussian can then be integrated to get the two tailed p-values. Input these values into correlation_gaussian.np code to integrate. gr_2.Fit(fitsignal,'R') norm_gaus = fitsignal.Integral(-1,1)
import matplotlib as mpl import matplotlib.pyplot as plt import numpy from ROOT import gROOT, TGaxis, TCanvas, TF1, gPad, TGraph, TGaxis, TLine, TGraphErrors, gApplication, TMultiGraph, TColor, TLegend, TPad,THStack, TAxis,TRandom3, TH1F, gStyle, TH1D,TMath, TSpectrum from array import array from random import random from decimal import * from random import gauss from scipy.fftpack import fft, rfft, fftfreq import pylab as plt import time getcontext().prec = 12 cave = TCanvas('cave', 'ave',600,1800) cave.Draw() cave.cd() p1ave = TPad('p1ave1','p',0.0,0.5,1,1) p1ave.SetGrid() p1ave.Draw() p2ave = TPad('p2ave2','p',0.0,0.0,1,0.5) p2ave.SetGrid() p2ave.Draw() p1ave.cd() juliandate , c117 , zeros, c133, er133, net, ernet, exp , realcount, livetime, fwhm, excesscounts = numpy.loadtxt('/Users/spenceraxani/Documents/Nuclear_Decay/Data/real_data.txt', unpack=True) ave_out_file = 'ave_detector_counts.txt' first_day = 56506.8942593 last_day = 56673.0953472 juliandate , counts, error = numpy.loadtxt('/Users/spenceraxani/Documents/Nuclear_Decay/Data/ave_detector_counts.txt', unpack=True) plot_ave = TGraph() plot_ave.SetLineColor(2) for k in range(len(juliandate)):
def draw_canvas_with_pull(mplot, mplot_pull, in_directory, in_file_name, in_model_name="", logy=0): # mplot + pull mplot.GetXaxis().SetTitleOffset(1.1) mplot.GetYaxis().SetTitleOffset(1.3) mplot.GetXaxis().SetTitleSize(0.05) mplot.GetYaxis().SetTitleSize(0.05) mplot.GetXaxis().SetLabelSize(0.045) mplot.GetYaxis().SetLabelSize(0.045) mplot_pull.GetXaxis().SetLabelSize(0.15) mplot_pull.GetYaxis().SetLabelSize(0.15) mplot_pull.GetYaxis().SetTitleSize(0.15) mplot_pull.GetYaxis().SetNdivisions(205) cMassFit = TCanvas("cMassFit", "cMassFit", 600, 600) pad1 = TPad("pad1", "pad1", 0.0, 0.0, 0.99, 0.24) pad2 = TPad("pad2", "pad2", 0.0, 0.24, 0.99, 1.0) pad1.Draw() pad2.Draw() pad2.cd() mplot.Draw() banner = banner4Plot(1) banner.Draw() pad1.cd() mplot_pull.Draw() ## create the directory where store the plots Directory = TString(in_directory) if not Directory.EndsWith("/"): Directory = Directory.Append("/") if not os.path.isdir(Directory.Data()): os.system("mkdir -p " + Directory.Data()) rlt_file = TString() rlt_file.Form("%s_%s" % (Directory, in_file_name)) if rlt_file.EndsWith(".root"): TString(in_model_name).ReplaceAll(".root", "") rlt_file.ReplaceAll(".root", "_" + in_model_name + "_with_pull.png") else: TString(in_model_name).ReplaceAll(".root", "") rlt_file.ReplaceAll(".root", "") rlt_file = rlt_file.Append("_" + in_model_name + "_with_pull.png") cMassFit.SaveAs(rlt_file.Data()) rlt_file.ReplaceAll(".png", ".pdf") cMassFit.SaveAs(rlt_file.Data()) rlt_file.ReplaceAll(".pdf", ".root") cMassFit.SaveAs(rlt_file.Data()) string_file_name = TString(in_file_name) if string_file_name.EndsWith(".root"): string_file_name.ReplaceAll(".root", "_" + in_model_name) else: string_file_name.ReplaceAll(".root", "") string_file_name.Append("_" + in_model_name) if logy: pad2.SetLogy() pad2.Update() cMassFit.Update() rlt_file.ReplaceAll(".root", "_log.root") cMassFit.SaveAs(rlt_file.Data()) rlt_file.ReplaceAll(".root", ".pdf") cMassFit.SaveAs(rlt_file.Data()) rlt_file.ReplaceAll(".pdf", ".png") cMassFit.SaveAs(rlt_file.Data()) draw_canvas(mplot, in_directory, string_file_name.Data(), 0, logy)