def drawRatio(histRatio,stack,Region,BLINDEDLIST,nbins,xmin,xmax): #histRatio = datastack.sum.Clone() #histRatio.merge_bins([(0, 1), (-2, -1)]) tempDataStack = histRatio.Clone() ratioMinimum=0 ratioMaximum=2 histRatio.SetMinimum(ratioMinimum) histRatio.SetMaximum(ratioMaximum) histRatio.yaxis.divisions = 5 histRatio.Divide(stack.sum) if Region not in BLINDEDLIST: histRatio.Draw("PE") line = Line(float(xmin)+1e-2*float(xmax),1.,float(xmax)-1e-2*float(xmax),1.); line.SetLineWidth(4); line.SetLineColor("red"); line.Draw(); if Region not in BLINDEDLIST: histRatio.Draw("SAME EP") MCerrorband = stack.sum.Clone() MCerrorband.SetLineWidth(10) MCerrorband.SetFillStyle(3244) MCerrorband.SetFillColor(922) for i in range(1,int(nbins)+1): if stack.sum.GetBinContent(i) != 0: if tempDataStack.GetBinContent(i)/stack.sum.GetBinContent(i) >= 2: xcoord = stack.sum.GetBinCenter(i) arrow = Arrow(xcoord,1.67,xcoord,1.87,0.015,"|>") arrow.SetAngle(50) arrow.SetLineWidth(6) arrow.SetLineColor(2) arrow.SetFillColor(2) arrow.Draw() if tempDataStack.GetBinContent(i)/stack.sum.GetBinContent(i) <= -2: xcoord = stack.sum.GetBinCenter(i) arrow = Arrow(xcoord,0.33,xcoord,0.13,0.015,"|>") arrow.SetAngle(50) arrow.SetLineWidth(6) arrow.SetLineColor(2) arrow.SetFillColor(2) arrow.Draw(); mcerror = 0.0 content = stack.sum.GetBinContent(i) error = stack.sum.GetBinError(i) if content != 0 : mcerror = (content+error)/content - 1.0 MCerrorband.SetBinContent(i,1) MCerrorband.SetBinError(i,mcerror) MCerrorband.Draw("E2PSAME")
def draw_curve_8(_func, name, title, ylow, yhigh, num_errs=1): """ Draw 8TeV trigger efficiency curves """ graphs = [] for (trigger, color) in triggers: tool = ROOT.TrigTauEfficiency() tool.loadInputFile(os.path.join(base, 'triggerSF_{0}.root'.format(trigger))) func = getattr(tool, _func) eff = np.array(map(lambda x: func(x, eta, 0, period, prong, wpflag, eveto), pt)) errs_low = [] errs_high = [] for ierr in xrange(num_errs): eff_low = np.array(map(lambda x: func(x, eta, -1, period, prong, wpflag, eveto), pt)) eff_high = np.array(map(lambda x: func(x, eta, 1, period, prong, wpflag, eveto), pt)) errs_low.append(eff_low) errs_high.append(eff_high) # quadrature sum of error eff_low = np.sqrt(np.sum([np.power(err, 2) for err in errs_low], axis=0)) eff_high = np.sqrt(np.sum([np.power(err, 2) for err in errs_high], axis=0)) graph = Graph(len(pt), name=trigger) for i, (p, e, e_low, e_high) in enumerate(zip(pt, eff, eff_low, eff_high)): graph.SetPoint(i, p / 1000, e) graph.SetPointError(i, 0.4, 0.4, e_low, e_high) graph.linecolor = color graph.linewidth = 2 graph.fillstyle = '/' graph.fillcolor = color graphs.append(graph) c = Canvas() leg = Legend(len(graphs), pad=c, topmargin=0.6, leftmargin=0.3, textsize=25, margin=0.2) for i, g in enumerate(graphs): if i == 0: g.Draw('3AL') g.xaxis.title = '#font[52]{p}_{T} [GeV]' g.xaxis.SetLimits(20, 100) g.yaxis.SetLimits(ylow, yhigh) g.yaxis.SetRangeUser(ylow, yhigh) g.yaxis.title = title else: g.Draw('3L SAME') leg.AddEntry(g, g.name, 'L') leg.Draw() lines = [] for thresh in (25, 35): line = Line(thresh, ylow, thresh, yhigh) line.linestyle = 'dashed' line.linewidth = 2 line.Draw() lines.append(line) c.SaveAs('trigger_{0}.png'.format(name)) c.SaveAs('trigger_{0}.eps'.format(name))
def draw_curve_7(_func, name, title, ylow, yhigh): """ Draw 7TeV trigger efficiency curves """ graphs = [] for (trigger, color) in triggers: tool = ROOT.TauTriggerCorrections( os.path.join(base, 'triggerSF_%s.root' % trigger)) func = getattr(tool, _func) eff = map(lambda x: func(x, 0), pt) eff_low = map(lambda x: func(x, -1), pt) eff_high = map(lambda x: func(x, 1), pt) graph = Graph(len(pt), name=trigger) for i, (p, e, e_low, e_high) in enumerate(zip(pt, eff, eff_low, eff_high)): graph.SetPoint(i, p / 1000, e) graph.SetPointError(i, 0.4, 0.4, e - e_low, e_high - e) graph.linecolor = color graph.linewidth = 2 graph.fillstyle = '/' graph.fillcolor = color graphs.append(graph) c = Canvas() leg = Legend(len(graphs), pad=c, topmargin=0.4, leftmargin=0.3, textsize=25, margin=0.2) for i, g in enumerate(graphs): if i == 0: g.Draw('3AC') g.xaxis.title = '#font[52]{p}_{T} [GeV]' g.xaxis.SetLimits(20, 100) g.yaxis.SetLimits(ylow, yhigh) g.yaxis.SetRangeUser(ylow, yhigh) g.yaxis.title = title else: g.Draw('3C SAME') leg.AddEntry(g, g.name, 'L') leg.Draw() lines = [] for thresh in (25, 35): line = Line(thresh, ylow, thresh, yhigh) line.linestyle = 'dashed' line.linewidth = 2 line.Draw() lines.append(line) c.SaveAs('trigger_{0}.png'.format(name)) c.SaveAs('trigger_{0}.eps'.format(name))
def draw_curve_7(_func, name, title, ylow, yhigh): """ Draw 7TeV trigger efficiency curves """ graphs = [] for (trigger, color) in triggers: tool = ROOT.TauTriggerCorrections(os.path.join(base, 'triggerSF_%s.root' % trigger)) func = getattr(tool, _func) eff = map(lambda x: func(x, 0), pt) eff_low = map(lambda x: func(x, -1), pt) eff_high = map(lambda x: func(x, 1), pt) graph = Graph(len(pt), name=trigger) for i, (p, e, e_low, e_high) in enumerate(zip(pt, eff, eff_low, eff_high)): graph.SetPoint(i, p / 1000, e) graph.SetPointError(i, 0.4, 0.4, e - e_low, e_high - e) graph.linecolor = color graph.linewidth = 2 graph.fillstyle = '/' graph.fillcolor = color graphs.append(graph) c = Canvas() leg = Legend(len(graphs), pad=c, topmargin=0.4, leftmargin=0.3, textsize=25, margin=0.2) for i, g in enumerate(graphs): if i == 0: g.Draw('3AC') g.xaxis.title = '#font[52]{p}_{T} [GeV]' g.xaxis.SetLimits(20, 100) g.yaxis.SetLimits(ylow, yhigh) g.yaxis.SetRangeUser(ylow, yhigh) g.yaxis.title = title else: g.Draw('3C SAME') leg.AddEntry(g, g.name, 'L') leg.Draw() lines = [] for thresh in (25, 35): line = Line(thresh, ylow, thresh, yhigh) line.linestyle = 'dashed' line.linewidth = 2 line.Draw() lines.append(line) c.SaveAs('trigger_{0}.png'.format(name)) c.SaveAs('trigger_{0}.eps'.format(name))
print('[4mu VR] dphiIsoinit - correlation factor: ', h.get_correlation_factor()) h.Draw('colz') h.GetListOfFunctions().FindObject("palette").SetX2NDC(0.92) title = TitleAsLatex('[4#mu VR] ' + h.title) title.Draw() canvas.SaveAs('{}/ch4mu_vr_dphiisopre.pdf'.format(outdir)) canvas.Clear() h.Draw('colz') h.GetListOfFunctions().FindObject("palette").SetX2NDC(0.92) title.Draw() dphi_bounds = [0.7 * math.pi, 0.8 * math.pi, 0.9 * math.pi] vlines = [] for i, b in enumerate(dphi_bounds): vline = Line(b, h.yaxis.GetXmin(), b, h.yaxis.GetXmax()) vline.color = COLORS[i] vline.linewidth = 2 vlines.append(vline) for l in vlines: l.Draw() canvas.SaveAs('{}/ch4mu_vr_dphiisopre_vline.pdf'.format(outdir)) canvas.Clear() h.Draw('colz') h.GetListOfFunctions().FindObject("palette").SetX2NDC(0.92) title.Draw() iso_bounds = [0.2, 0.3, 0.4] hlines = [] for i, b in enumerate(iso_bounds): hline = Line(h.xaxis.GetXmin(), b, h.xaxis.GetXmax(), b)
if htitle and 'phi' in htitle: decorate_axis_pi(axes[0]) if args.logx: axes[0].SetMoreLogLabels() mainPad.SetGrid() # ROOT.gPad.Update() # ROOT.gPad.RedrawAxis('G') legend.Draw() title = TitleAsLatex('[{}] {}'.format(chan.replace('mu', '#mu'), htitle.split(';')[0])) title.Draw() draw_labels('59.74 fb^{-1} (13 TeV)', cms_position='left', extra_text='work-in-progress') if args.vline is not None: vline = Line(args.vline, mainPad.GetUymin(), args.vline, axes[1].GetXmax()) vline.color = 'black' vline.linewidth = 2 vline.linestyle = 'dashed' vline.Draw() if args.dataset == 'all': # draw ratio on subpad subPad.cd() _ratio = hData.clone() _ratio.Divide(sumHistStack(hstack)) _ratio.SetMarkerSize(0.8) _ratio.yaxis.SetTitle('Data/MC') _ratio.yaxis.SetTitleOffset(0.35) _ratio.yaxis.CenterTitle()
def __init__(self, width=None, height=None, offset=0, ratio_height=None, ratio_margin=26, ratio_limits=(0, 2), ratio_divisions=4, prune_ratio_ticks=False, ratio_line_values=(1,), ratio_line_width=2, ratio_line_style='dashed', xtitle=None, ytitle=None, ratio_title=None, tick_length=15, logy=False): # first init as normal canvas super(RatioPlot, self).__init__(width=width, height=height) # get margins in pixels left, right, bottom, top = self.margin_pixels default_height = self.height default_frame_height = default_height - bottom - top if ratio_height is None: ratio_height = default_height / 4. self.height += int(ratio_height) + ratio_margin + offset self.margin = (0, 0, 0, 0) main_height = default_frame_height + top + ratio_margin / 2. + offset ratio_height += ratio_margin / 2. + bottom # top pad for histograms with self: main = Pad(0., ratio_height / self.height, 1., 1.) if logy: main.SetLogy() main.margin_pixels = (left, right, ratio_margin / 2., top) main.Draw() # bottom pad for ratio plot with self: ratio = Pad(0, 0, 1, ratio_height / self.height) ratio.margin_pixels = (left, right, bottom, ratio_margin / 2.) ratio.Draw() # draw main axes with main: main_hist = Hist(1, 0, 1) main_hist.Draw('AXIS') # hide x-axis labels and title on main pad xaxis, yaxis = main_hist.xaxis, main_hist.yaxis xaxis.SetLabelOffset(1000) xaxis.SetTitleOffset(1000) # adjust y-axis title spacing yaxis.SetTitleOffset( yaxis.GetTitleOffset() * self.height / default_height) # draw ratio axes with ratio: ratio_hist = Hist(1, 0, 1) ratio_hist.Draw('AXIS') # adjust x-axis label and title spacing xaxis, yaxis = ratio_hist.xaxis, ratio_hist.yaxis xaxis.SetLabelOffset( xaxis.GetLabelOffset() * self.height / ratio_height) xaxis.SetTitleOffset( xaxis.GetTitleOffset() * self.height / ratio_height) # adjust y-axis title spacing yaxis.SetTitleOffset( yaxis.GetTitleOffset() * self.height / default_height) if ratio_limits is not None: low, high = ratio_limits if prune_ratio_ticks: delta = 0.01 * (high - low) / float(ratio_divisions % 100) low += delta high -= delta yaxis.SetLimits(low, high) yaxis.SetRangeUser(low, high) yaxis.SetNdivisions(ratio_divisions) if xtitle is not None: ratio_hist.xaxis.title = xtitle if ytitle is not None: main_hist.yaxis.title = ytitle if ratio_title is not None: ratio_hist.yaxis.title = ratio_title # set the tick lengths tick_length_pixels(main, main_hist.xaxis, main_hist.yaxis, tick_length) tick_length_pixels(ratio, ratio_hist.xaxis, ratio_hist.yaxis, tick_length) # draw ratio lines lines = [] if ratio_line_values: with ratio: for value in ratio_line_values: line = Line(0, value, 1, value) line.linestyle = ratio_line_style line.linewidth = ratio_line_width line.Draw() lines.append(line) self.lines = lines self.main = main self.main_hist = main_hist self.ratio = ratio self.ratio_hist = ratio_hist self.ratio_limits = ratio_limits self.logy = logy
def __init__(self, width=None, height=None, offset=0, ratio_height=None, ratio_margin=26, ratio_limits=(0, 2), ratio_divisions=4, prune_ratio_ticks=False, ratio_line_values=(1, ), ratio_line_width=2, ratio_line_style='dashed', xtitle=None, ytitle=None, ratio_title=None, tick_length=15, logy=False): # first init as normal canvas super(RatioPlot, self).__init__(width=width, height=height) # get margins in pixels left, right, bottom, top = self.margin_pixels default_height = self.height default_frame_height = default_height - bottom - top if ratio_height is None: ratio_height = default_height / 4. self.height += int(ratio_height) + ratio_margin + offset self.margin = (0, 0, 0, 0) main_height = default_frame_height + top + ratio_margin / 2. + offset ratio_height += ratio_margin / 2. + bottom # top pad for histograms with self: main = Pad(0., ratio_height / self.height, 1., 1.) if logy: main.SetLogy() main.margin_pixels = (left, right, ratio_margin / 2., top) main.Draw() # bottom pad for ratio plot with self: ratio = Pad(0, 0, 1, ratio_height / self.height) ratio.margin_pixels = (left, right, bottom, ratio_margin / 2.) ratio.Draw() # draw main axes with main: main_hist = Hist(1, 0, 1) main_hist.Draw('AXIS') # hide x-axis labels and title on main pad xaxis, yaxis = main_hist.xaxis, main_hist.yaxis xaxis.SetLabelOffset(1000) xaxis.SetTitleOffset(1000) # adjust y-axis title spacing yaxis.SetTitleOffset(yaxis.GetTitleOffset() * self.height / default_height) # draw ratio axes with ratio: ratio_hist = Hist(1, 0, 1) ratio_hist.Draw('AXIS') # adjust x-axis label and title spacing xaxis, yaxis = ratio_hist.xaxis, ratio_hist.yaxis xaxis.SetLabelOffset(xaxis.GetLabelOffset() * self.height / ratio_height) xaxis.SetTitleOffset(xaxis.GetTitleOffset() * self.height / ratio_height) # adjust y-axis title spacing yaxis.SetTitleOffset(yaxis.GetTitleOffset() * self.height / default_height) if ratio_limits is not None: low, high = ratio_limits if prune_ratio_ticks: delta = 0.01 * (high - low) / float(ratio_divisions % 100) low += delta high -= delta yaxis.SetLimits(low, high) yaxis.SetRangeUser(low, high) yaxis.SetNdivisions(ratio_divisions) if xtitle is not None: ratio_hist.xaxis.title = xtitle if ytitle is not None: main_hist.yaxis.title = ytitle if ratio_title is not None: ratio_hist.yaxis.title = ratio_title # set the tick lengths tick_length_pixels(main, main_hist.xaxis, main_hist.yaxis, tick_length) tick_length_pixels(ratio, ratio_hist.xaxis, ratio_hist.yaxis, tick_length) # draw ratio lines lines = [] if ratio_line_values: with ratio: for value in ratio_line_values: line = Line(0, value, 1, value) line.linestyle = ratio_line_style line.linewidth = ratio_line_width line.Draw() lines.append(line) self.lines = lines self.main = main self.main_hist = main_hist self.ratio = ratio self.ratio_hist = ratio_hist self.ratio_limits = ratio_limits self.logy = logy
def plotratio(datastack, stack): histRatio = datastack.sum.Clone() #histRatio.merge_bins([(0, 1), (-2, -1)]) ratioMinimum = 0 ratioMaximum = 2 histRatio.SetMinimum(ratioMinimum) histRatio.SetMaximum(ratioMaximum) histRatio.xaxis.SetTitle(xtitle) histRatio.yaxis.SetTitle("Data/SM") histRatio.yaxis.CenterTitle() histRatio.yaxis.divisions = 5 histRatio.Divide(stack.sum) histRatio.xaxis.SetTitleOffset(3.4) histRatio.yaxis.SetTitleOffset(2) histRatio.xaxis.set_label_size(int(canvasheight * labelscale * 1.5)) histRatio.yaxis.set_label_size(int(canvasheight * labelscale * 1.5)) if plotData: histRatio.Draw("PE") line = Line( float(xmin) + 1e-2 * float(xmax), 1., float(xmax) - 1e-2 * float(xmax), 1.) line.SetLineWidth(4) line.SetLineColor("red") if plotData: line.Draw("Same") else: line.Draw() if plotData: histRatio.Draw("SAME EP") MCerrorband = stack.sum.Clone() MCerrorband.SetLineWidth(10) MCerrorband.SetFillStyle(3244) MCerrorband.SetFillColor(922) for i in range(1, int(nbins) + 1): if stack.sum.GetBinContent(i) != 0: if datastack.sum.GetBinContent(i) / stack.sum.GetBinContent( i) >= 2: xcoord = stack.sum.GetBinCenter(i) arrow = Arrow(xcoord, 1.67, xcoord, 1.87, 0.015, "|>") arrow.SetAngle(50) arrow.SetLineWidth(6) arrow.SetLineColor(2) arrow.SetFillColor(2) arrow.Draw() if datastack.sum.GetBinContent(i) / stack.sum.GetBinContent( i) <= -2: xcoord = stack.sum.GetBinCenter(i) arrow = Arrow(xcoord, 0.33, xcoord, 0.13, 0.015, "|>") arrow.SetAngle(50) arrow.SetLineWidth(6) arrow.SetLineColor(2) arrow.SetFillColor(2) arrow.Draw() mcerror = 0.0 content = stack.sum.GetBinContent(i) error = stack.sum.GetBinError(i) if content != 0: mcerror = (content + error) / content - 1.0 MCerrorband.SetBinContent(i, 1) MCerrorband.SetBinError(i, mcerror) MCerrorband.Draw("E2PSAME")
entrysep=0.01, entryheight=0.02, textsize=15) leg.AddEntry(mkh, label=label) leg.Draw() canvas.SaveAs('{}/ch4mu_{}.pdf'.format(outdir, sigtag)) canvas.Clear() sigc = sigh.clone() sigc.Draw('colz') sigc.GetListOfFunctions().FindObject("palette").SetX2NDC(0.92) title = TitleAsLatex('[4#mu SR {}] '.format(sigtag) + '|#Delta#phi| vs. maxIso') title.Draw() decorate_axis_pi(sigc.xaxis) hline = Line(sigc.xaxis.GetXmin(), yedge, sigc.xaxis.GetXmax(), yedge) vline = Line(xedge, sigc.yaxis.GetXmin(), xedge, sigc.yaxis.GetXmax()) for l in [hline, vline]: l.linewidth = 2 l.color = 'red' l.Draw() canvas.SaveAs('{}/ch4mu_isodphi_{}.pdf'.format(outdir, sigtag)) canvas.Clear() bkgf.close() ######################################### bkgfn = os.path.join( os.getenv('CMSSW_BASE'), 'src/FireROOT/Analysis/python/outputs/rootfiles/proxy/proxy_2mu2e.root' )
def pvalue_plot(poi, pvalues, pad=None, xtitle='X', ytitle='P_{0}', linestyle=None, linecolor=None, yrange=None, verbose=False): """ Draw a pvalue plot Parameters ---------- poi : list List of POI values tested pvalues : list List of p-values or list of lists of p-values to overlay multiple p-value curves pad : Canvas or Pad, optional (default=None) Pad to draw onto. Create new pad if None. xtitle : str, optional (default='X') The x-axis label (POI name) ytitle : str, optional (default='P_{0}') The y-axis label linestyle : str or list, optional (default=None) Line style for the p-value graph or a list of linestyles for multiple p-value graphs. linecolor : str or list, optional (default=None) Line color for the p-value graph or a list of linestyles for multiple p-value graphs. Returns ------- pad : Canvas The pad. graphs : list of Graph The p-value graphs """ if not pvalues: raise ValueError("pvalues is empty") if not poi: raise ValueError("poi is empty") # determine if pvalues is list or list of lists if not isinstance(pvalues[0], (list, tuple)): pvalues = [pvalues] if linecolor is not None: if not isinstance(linecolor, list): linecolor = [linecolor] linecolor = cycle(linecolor) if linestyle is not None: if not isinstance(linestyle, list): linestyle = [linestyle] linestyle = cycle(linestyle) with preserve_current_canvas(): if pad is None: pad = Canvas() pad.cd() pad.SetLogy() # create the axis min_poi, max_poi = min(poi), max(poi) haxis = Hist(1000, min_poi, max_poi) xaxis = haxis.xaxis yaxis = haxis.yaxis xaxis.SetRangeUser(min_poi, max_poi) haxis.Draw('AXIS') min_pvalue = float('inf') graphs = [] for ipv, pv in enumerate(pvalues): graph = Graph(len(poi), linestyle='dashed', drawstyle='L', linewidth=2) for idx, (point, pvalue) in enumerate(zip(poi, pv)): graph.SetPoint(idx, point, pvalue) if linestyle is not None: graph.linestyle = linestyle.next() if linecolor is not None: graph.linecolor = linecolor.next() graphs.append(graph) curr_min_pvalue = min(pv) if curr_min_pvalue < min_pvalue: min_pvalue = curr_min_pvalue if verbose: for graph in graphs: log.info(['{0:1.1f}'.format(xval) for xval in list(graph.x())]) log.info(['{0:0.3f}'.format(yval) for yval in list(graph.y())]) # automatically handles axis limits axes, bounds = draw(graphs, pad=pad, same=True, logy=True, xtitle=xtitle, ytitle=ytitle, xaxis=xaxis, yaxis=yaxis, ypadding=(0.2, 0.1), logy_crop_value=1E-300) if yrange is not None: xaxis, yaxis = axes yaxis.SetLimits(*yrange) yaxis.SetRangeUser(*yrange) min_pvalue = yrange[0] # draw sigma levels up to minimum of pvalues line = Line() line.SetLineStyle(2) line.SetLineColor(2) latex = ROOT.TLatex() latex.SetNDC(False) latex.SetTextSize(20) latex.SetTextColor(2) sigma = 0 while True: pvalue = gaussian_cdf_c(sigma) if pvalue < min_pvalue: break keepalive( pad, latex.DrawLatex(max_poi, pvalue, " {0}#sigma".format(sigma))) keepalive(pad, line.DrawLine(min_poi, pvalue, max_poi, pvalue)) sigma += 1 pad.RedrawAxis() pad.Update() return pad, graphs
def routine(chandir, bkgh, optm_region, outdir): canvas = Canvas() ROOT.gPad.SetGrid() for massKey in chandir.keys(): mboundstate = int(massKey.name.split('_')[0].replace('mXX-', '')) NORM_FACTOR_SIGNAL = 30./genxsec[mboundstate] # norm to 30/fb massDir = getattr(chandir, massKey.name) _outdir = os.path.join(outdir, massKey.name) if not os.path.isdir(_outdir): os.makedirs(_outdir) boundary_edges = {} for lifetimeKey in massDir.keys(): lifetimeDir = getattr(massDir, lifetimeKey.name) sigh = lifetimeDir.dphiIso2D_nominal sigh.scale( NORM_FACTOR_SIGNAL ) ###### ZA map ###### zah = create_za_map(sigh, bkgh, optm_region=optm_region) zah.Draw('colz') zah.GetListOfFunctions().FindObject("palette").SetX2NDC(0.92) mkh, xedge, yedge, maxval = mark_maximum_bin(zah) boundary_edges[lifetimeKey.name] = (xedge, yedge, maxval) # bookkeeping for overlap plot label = '(|#Delta#phi|, iso): {:.2f}, {:.2f} '.format(xedge, yedge)+'Z_{A}: '+'{:.3f}'.format(maxval) mkh.Draw('p same') if outdir.endswith('ch4mu'): title = TitleAsLatex('[4#mu {}] '.format(massKey.name)+'proxy significance Z_{A}') if outdir.endswith('ch2mu2e'): title = TitleAsLatex('[2#mu2e {}] '.format(massKey.name)+'proxy significance Z_{A}') title.Draw() leg = Legend(1, margin=0.25, leftmargin=0.05, rightmargin=0.5, topmargin=0.05, entrysep=0.01, entryheight=0.02, textsize=15, header=lifetimeKey.name) leg.AddEntry(mkh, label=label) leg.Draw() canvas.SaveAs('{}/ZA__{}.png'.format(_outdir, lifetimeKey.name)) canvas.SaveAs('{}/ZA__{}.pdf'.format(_outdir, lifetimeKey.name)) canvas.Clear() ###### signal distribution ###### sigc = sigh.clone() sigc.Draw('colz') if sigc.integral(): sigc.GetListOfFunctions().FindObject("palette").SetX2NDC(0.92) if outdir.endswith('ch4mu'): title = TitleAsLatex('[4#mu SR {}] '.format(massKey.name)+'|#Delta#phi| vs. maxIso') if outdir.endswith('ch2mu2e'): title = TitleAsLatex('[2#mu2e SR {}] '.format(massKey.name)+'|#Delta#phi| vs. Iso') sigc.yaxis.title='egm lepton-jet iso' title.Draw() decorate_axis_pi(sigc.xaxis) hline = Line(sigc.xaxis.GetXmin(), yedge, sigc.xaxis.GetXmax(), yedge) vline = Line(xedge, sigc.yaxis.GetXmin(), xedge, sigc.yaxis.GetXmax()) for l in [hline, vline]: l.linewidth=2 l.color='red' l.Draw() canvas.SaveAs('{}/IsoDphi_{}.png'.format(_outdir, lifetimeKey.name)) canvas.SaveAs('{}/IsoDphi_{}.pdf'.format(_outdir, lifetimeKey.name)) canvas.Clear() ###### optimal boundaries ###### boundsh = sigh.clone() boundsh.Reset() boundsh.Draw('col') decorate_axis_pi(boundsh.xaxis) leg = Legend(len(boundary_edges), margin=0.25, leftmargin=0.05, rightmargin=0.5, topmargin=0.05, entrysep=0.01, entryheight=0.02, textsize=12) get_lxy = lambda t : float(t.split('_')[0].split('-')[-1].replace('p', '.')) for i, k in enumerate(sorted(boundary_edges, key=get_lxy)): bx, by, za = boundary_edges[k] hline = Line(boundsh.xaxis.GetXmin(), by, boundsh.xaxis.GetXmax(), by) vline = Line(bx, boundsh.yaxis.GetXmin(), bx, boundsh.yaxis.GetXmax()) label = '{:20}'.format(k) label+='({:.2f}, {:.2f})'.format(bx, by) label+=' Z_{A}: %.3f'%za leg.AddEntry(hline, label=label, style='L') for l in (hline, vline): l.linewidth=2 l.color=sigCOLORS[i] if i%2==0: l.linestyle='dashed' l.Draw() leg.Draw() if outdir.endswith('ch4mu'): title = TitleAsLatex('[4#mu {}] '.format(massKey.name)+'optimial boundaries') if outdir.endswith('ch2mu2e'): title = TitleAsLatex('[2#mu2e SR {}] '.format(massKey.name)+'optimal boundaries') title.Draw() canvas.SaveAs('{}/boundaries.png'.format(_outdir)) canvas.SaveAs('{}/boundaries.pdf'.format(_outdir)) canvas.Clear()
def draw_curve_8(_func, name, title, ylow, yhigh, num_errs=1): """ Draw 8TeV trigger efficiency curves """ graphs = [] for (trigger, color) in triggers: tool = ROOT.TrigTauEfficiency() tool.loadInputFile( os.path.join(base, 'triggerSF_{0}.root'.format(trigger))) func = getattr(tool, _func) eff = np.array( map(lambda x: func(x, eta, 0, period, prong, wpflag, eveto), pt)) errs_low = [] errs_high = [] for ierr in xrange(num_errs): eff_low = np.array( map(lambda x: func(x, eta, -1, period, prong, wpflag, eveto), pt)) eff_high = np.array( map(lambda x: func(x, eta, 1, period, prong, wpflag, eveto), pt)) errs_low.append(eff_low) errs_high.append(eff_high) # quadrature sum of error eff_low = np.sqrt( np.sum([np.power(err, 2) for err in errs_low], axis=0)) eff_high = np.sqrt( np.sum([np.power(err, 2) for err in errs_high], axis=0)) graph = Graph(len(pt), name=trigger) for i, (p, e, e_low, e_high) in enumerate(zip(pt, eff, eff_low, eff_high)): graph.SetPoint(i, p / 1000, e) graph.SetPointError(i, 0.4, 0.4, e_low, e_high) graph.linecolor = color graph.linewidth = 2 graph.fillstyle = '/' graph.fillcolor = color graphs.append(graph) c = Canvas() leg = Legend(len(graphs), pad=c, topmargin=0.6, leftmargin=0.3, textsize=25, margin=0.2) for i, g in enumerate(graphs): if i == 0: g.Draw('3AL') g.xaxis.title = '#font[52]{p}_{T} [GeV]' g.xaxis.SetLimits(20, 100) g.yaxis.SetLimits(ylow, yhigh) g.yaxis.SetRangeUser(ylow, yhigh) g.yaxis.title = title else: g.Draw('3L SAME') leg.AddEntry(g, g.name, 'L') leg.Draw() lines = [] for thresh in (25, 35): line = Line(thresh, ylow, thresh, yhigh) line.linestyle = 'dashed' line.linewidth = 2 line.Draw() lines.append(line) c.SaveAs('trigger_{0}.png'.format(name)) c.SaveAs('trigger_{0}.eps'.format(name))
leg = Legend( 3, pad=canvas, topmargin=0.05, margin=0.2, entryheight=0.02, entrysep=0.01, textsize=12, ) leg.AddEntry(d0inc, label='inclusive') leg.AddEntry(d0wbj, label='N_{bjet}#geq1') leg.AddEntry(d0wbj_c, label='N_{bjet}#geq1 (scaled)') leg.Draw() title = TitleAsLatex( '[4#mu VR] muon-type lepton-jet min |d_{0}| shape comparison') title.Draw() frame = canvas.FindObject('TFrame') lo, hi = frame.GetY1(), frame.GetY2() vline = Line(100, lo, 100, hi) vline.color = 'black' vline.linewidth = 2 vline.linestyle = 'dashed' vline.Draw() canvas.SaveAs('{}/ch4mu_muljd0Shape.pdf'.format(outdir)) canvas.clear() pf.close()
def __init__(self, width=None, height=None, ratio_height=0.2, ratio_margin=0.05, ratio_range=(0, 2), ratio_divisions=4, ratio_line_values=(1,), ratio_line_width=2, ratio_line_style='dashed', xtitle=None, ytitle=None, ratio_title=None, tick_length=20): style = ROOT.gStyle # plot dimensions in pixels if height is not None: figheight = baseheight = height else: figheight = baseheight = style.GetCanvasDefH() if width is not None: figwidth = basewidth = width else: figwidth = basewidth = style.GetCanvasDefW() # margins left_margin = style.GetPadLeftMargin() bottom_margin = style.GetPadBottomMargin() top_margin = style.GetPadTopMargin() right_margin = style.GetPadRightMargin() figheight += (ratio_height + ratio_margin) * figheight ratio_height += bottom_margin + ratio_margin / 2. super(RatioPlot, self).__init__( width=int(figwidth), height=int(figheight)) self.SetMargin(0, 0, 0, 0) # top pad for histograms with self: main = Pad(0., ratio_height, 1., 1.) main.SetBottomMargin(ratio_margin / 2.) main.SetTopMargin(top_margin) main.SetLeftMargin(left_margin) main.SetRightMargin(right_margin) main.Draw() # bottom pad for ratio plot with self: ratio = Pad(0, 0, 1, ratio_height) ratio.SetBottomMargin(bottom_margin / ratio_height) ratio.SetTopMargin(ratio_margin / (2. * ratio_height)) ratio.SetLeftMargin(left_margin) ratio.SetRightMargin(right_margin) ratio.Draw() # draw main axes with main: main_hist = Hist(1, 0, 1) main_hist.Draw('AXIS') # hide x-axis labels and title on main pad xaxis, yaxis = main_hist.xaxis, main_hist.yaxis xaxis.SetLabelOffset(1000) xaxis.SetTitleOffset(1000) # adjust y-axis title spacing yaxis.SetTitleOffset( yaxis.GetTitleOffset() * figheight / baseheight) # draw ratio axes with ratio: ratio_hist = Hist(1, 0, 1) ratio_hist.Draw('AXIS') # adjust x-axis label and title spacing xaxis, yaxis = ratio_hist.xaxis, ratio_hist.yaxis xaxis.SetLabelOffset( xaxis.GetLabelOffset() / ratio_height) xaxis.SetTitleOffset( xaxis.GetTitleOffset() / ratio_height) # adjust y-axis title spacing yaxis.SetTitleOffset( yaxis.GetTitleOffset() * figheight / baseheight) if ratio_range is not None: yaxis.SetLimits(*ratio_range) yaxis.SetRangeUser(*ratio_range) yaxis.SetNdivisions(ratio_divisions) if xtitle is not None: ratio_hist.xaxis.title = xtitle if ytitle is not None: main_hist.yaxis.title = ytitle if ratio_title is not None: ratio_hist.yaxis.title = ratio_title # set the tick lengths tick_length_pixels(main, main_hist.xaxis, main_hist.yaxis, tick_length) tick_length_pixels(ratio, ratio_hist.xaxis, ratio_hist.yaxis, tick_length) # draw ratio lines lines = [] if ratio_line_values: with ratio: for value in ratio_line_values: line = Line(0, value, 1, value) line.linestyle = ratio_line_style line.linewidth = ratio_line_width line.Draw() lines.append(line) self.lines = lines self.main = main self.main_hist = main_hist self.ratio = ratio self.ratio_hist = ratio_hist self.ratio_range = ratio_range