def Compare(w, output, fn1, fn2, bins, var, other_vars= {}, line_pos=None): label_vars = [] for key, val in other_vars.iteritems(): w.var(key).setVal(val) label_vars.append('%s=%g' % (key, val)) h1 = w.function(fn1).createHistogram(fn1, w.var(var), ROOT.RooFit.Binning(*bins), ROOT.RooFit.Scaling(False) ) h2 = w.function(fn2).createHistogram(fn2, w.var(var), ROOT.RooFit.Binning(*bins), ROOT.RooFit.Scaling(False) ) canv = ROOT.TCanvas(output, output) pads = plot.TwoPadSplit(0.30, 0.01, 0.01) pads[0].cd() pads[0].SetGrid(1, 1) plot.Set(h1, LineColor=ROOT.kBlack, LineWidth=2) plot.Set(h1.GetYaxis(), Title='Efficiency') plot.Set(h2, LineColor=ROOT.kRed, LineWidth=2) for i in xrange(1, h1.GetNbinsX()+1): h1.SetBinError(i, 0.) for i in xrange(1, h2.GetNbinsX()+1): h2.SetBinError(i, 0.) h1.Draw('L') h2.Draw('LSAME') ratio = h1.Clone() ratio.Divide(h2) legend = ROOT.TLegend(0.18, 0.82, 0.6, 0.93, '', 'NBNDC') legend.AddEntry(h1, fn1, 'L') legend.AddEntry(h2, fn2, 'L') legend.Draw() print plot.GetPadYMax(pads[0]) plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.25) plot.DrawTitle(pads[0], ','.join(label_vars), 1) line = ROOT.TLine() plot.Set(line, LineColor=12, LineStyle=4, LineWidth=2) if line_pos is not None: plot.DrawVerticalLine(pads[0], line, line_pos) pads[1].cd() pads[1].SetGrid(1, 1) ratio.Draw('L') plot.SetupTwoPadSplitAsRatio( pads, plot.GetAxisHist( pads[0]), plot.GetAxisHist(pads[1]), 'Ratio', True, 0.91, 1.09) if line_pos is not None: plot.DrawVerticalLine(pads[1], line, line_pos) canv.Print('.pdf') canv.Print('.png')
plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.40) delta_acc = Rate(res[1]) / Rate(res[0]) legend.SetHeader('Rel. Acc.: %.3f #pm %.3f' % (delta_acc.n, delta_acc.s)) legend.Draw() axis = plot.GetAxisHist(pads[0]) plot.Set(axis.GetXaxis(), Title=args.x_title) plot.Set(axis.GetYaxis(), Title='a.u.') rmin = float(args.ratio_range.split(',')[0]) rmax = float(args.ratio_range.split(',')[1]) pads[1].cd() pads[1].SetGrid(0, 1) ratio_hist = res[1].Clone() ratio_hist.Divide(res[0]) ratio_hist.Draw('HISTESAME') plot.SetupTwoPadSplitAsRatio( pads, plot.GetAxisHist( pads[0]), plot.GetAxisHist(pads[1]), 'Ratio', True, rmin, rmax) plot.DrawTitle(pads[0], args.title_left, 1) plot.DrawTitle(pads[0], args.title_right, 3) res[0].Print() canv.Print('.pdf') canv.Print('.png')
plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.35) legend.Draw() # plot.FixBoxPadding(pads[0], legend, 0.05) # Do the ratio plot pads[1].cd() pads[1].SetGrid(0, 1) h_axes[1].Draw() r_data = plot.MakeRatioHist(h_data, h_tot, True, False) r_tot = plot.MakeRatioHist(h_tot, h_tot, True, False) r_tot.Draw('E2SAME') r_data.Draw('SAME') plot.SetupTwoPadSplitAsRatio( pads, plot.GetAxisHist( pads[0]), plot.GetAxisHist(pads[1]), 'Obs/Exp', True, 0.61, 1.39) # Go back and tidy up the axes and frame pads[0].cd() pads[0].GetFrame().Draw() pads[0].RedrawAxis() # CMS logo plot.DrawCMSLogo(pads[0], 'CMS', 'Internal', 11, 0.045, 0.05, 1.0, '', 1.0) plot.DrawTitle(pads[0], '12.9 fb^{-1} (13 TeV)', 3) latex = ROOT.TLatex() plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03) latex.DrawLatex(0.20, 0.75, args.title) # plot.DrawTitle(pads[0], args.title, 1)
pads[1].SetGrid(0, 1) h_axes[1].Draw() # r_data = plot.MakeRatioHist(h_data, h_tot, True, False) # r_nominal = plot.MakeRatioHist(h_nominal, h_nominal, True, False) r_NLO_inc = plot.MakeRatioHist(h_NLO_inc, h_LO_inc, True, True) # r_LO_130 = plot.MakeRatioHist(h_LO_130, h_LO_inc, True, True) # r_LO_inc_cut_130 = plot.MakeRatioHist(h_LO_130, h_LO_inc, True, True) # r_LO_500 = plot.MakeRatioHist(h_LO_inc_cut_130, h_LO_inc, True, True) r_NLO_inc.Draw('SAMEE') # r_LO_130.Draw('SAMEE') # r_LO_inc_cut_130.Draw('SAMEE') # r_LO_500.Draw('SAMEE') # r_data.Draw('SAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'C_{3W} = X / Nominal', True, 0.8, 1.8) # Go back and tidy up the axes and frame pads[0].cd() pads[0].GetFrame().Draw() pads[0].RedrawAxis() # CMS logo # plot.DrawCMSLogo(pads[0], 'CMS', 'Internal', 11, 0.045, 0.05, 1.0, '', 1.0) # plot.DrawTitle(pads[0], '0.1 fb^{-1} (13 TeV)', 3) # latex = ROOT.TLatex() # plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03) # # latex.DrawLatex(0.20, 0.75, args.title) # plot.DrawTitle(pads[0], '#sqrt{s} = 13 TeV', 3)
for i, h in enumerate(h_axes): print i hr = r_h_axes[i] h.Reset() hr.Reset() pads[i].cd() pads[i].SetLogy(True) h.Draw() ratio_pads[i].cd() hr.Draw() pads[i].cd() plot.SetupTwoPadSplitAsRatio([pads[i], ratio_pads[i]], h, hr, '(Obs-Exp)/Exp', True, settings[args.selection]['ratio_min'], settings[args.selection]['ratio_max']) h.SetMinimum(settings[args.selection]['y_axis_min']) h.SetMaximum(settings[args.selection]['y_axis_max']) h.GetXaxis().SetNdivisions(510) hr.GetXaxis().SetNdivisions(510) hr.GetXaxis().ChangeLabel(-1, -1., -1., -1, -1, -1, ' ') h.GetYaxis().SetTickLength(h.GetYaxis().GetTickLength() * 0.5) hr.GetYaxis().SetTickLength(hr.GetYaxis().GetTickLength() * 0.5) if i == 0: h.GetYaxis().SetTitle(settings[args.selection]['y_axis_title']) if i > 0: h.GetYaxis().SetLabelSize(0) hr.GetYaxis().SetLabelSize(0)
1.2, cmsTextSize=0.9) plot.DrawTitle(pads[0], args.title_right, 3) if args.ratio_to is not None: pads[1].cd() pads[1].SetLogx(True) ratios = [] for slice in slices: ratios.append(slice.Clone()) ratios[-1].Divide(slices[args.ratio_to]) ratios[-1].Print("range") ratios[0].Draw('AXIS') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Data/MC', True, float(args.ratio_y_range.split(',')[0]), float(args.ratio_y_range.split(',')[1])) for j, ratio in enumerate(ratios): if j == args.ratio_to: continue ratio.Draw('SAME') pads[1].SetGrid(1, 1) pads[1].RedrawAxis('g') outname = '%s.%s.%g_%g' % (args.output, hist.GetYaxis().GetTitle(), hist.GetYaxis().GetBinLowEdge(i), hist.GetYaxis().GetBinUpEdge(i)) outname = outname.replace('(', '_') outname = outname.replace(')', '_')
def MakePlot(name, outdir, hists, cfg, layouts): copyhists = {} for hname, h in hists.iteritems(): if len(cfg['rebinvar']): copyhists[hname] = VariableRebin(h, cfg['rebinvar']) else: copyhists[hname] = h.Clone() if cfg['divwidth']: copyhists[hname].Scale(1., 'width') hists = copyhists # Canvas and pads canv = ROOT.TCanvas(name, name) if cfg['ratio'] or cfg['fraction']: pads = plot.TwoPadSplit(0.27, 0.01, 0.01) else: pads = plot.OnePad() # Get the data and create axis hist h_data = hists[cfg['data_name']] # h_data = Getter(file, '%s/data_obs' % target, True) if isinstance(h_data, ROOT.TH2): print 'TH2: aborting!' return h_axes = [h_data.Clone() for x in pads] for h in h_axes: if len(cfg['x_range']): h.GetXaxis().SetRangeUser(*cfg['x_range']) h.Reset() build_h_tot = True h_tot = None if 'TotalProcs' in hists: h_tot = hists['TotalProcs'] build_h_tot = False x_title = cfg['x_title'][0] units = cfg['x_title'][1] if x_title == '' and h_data.GetXaxis().GetTitle() != '': x_title = h_data.GetXaxis().GetTitle() if ':' in x_title: units = x_title.split(':')[1] x_title = x_title.split(':')[0] if cfg['logy']: pads[0].SetLogy() h_axes[0].SetMinimum(0.001) if cfg['ratio'] or cfg['fraction']: plot.StandardAxes(h_axes[1].GetXaxis(), h_axes[0].GetYaxis(), x_title, units) else: plot.StandardAxes(h_axes[0].GetXaxis(), h_axes[0].GetYaxis(), x_title, units) h_axes[0].Draw() # A dict to keep track of the hists h_store = {} layout = layouts[cfg['layout']] stack = ROOT.THStack() legend = ROOT.TLegend(*(cfg['legend_pos'] + ['', 'NBNDC'])) for info in layout: hist = hists[info['entries'][0]] col = info['color'] if isinstance(col, list): col = ROOT.TColor.GetColor(*col) plot.Set(hist, FillColor=col, Title=info['legend']) if len(info['entries']) > 1: for other in info['entries'][1:]: hist.Add(hists[other]) h_store[info['name']] = hist if build_h_tot: if h_tot is None: h_tot = hist.Clone() else: h_tot.Add(hist) stack.Add(hist) h_tot.SetFillColor(plot.CreateTransparentColor(12, 0.3)) h_tot.SetMarkerSize(0) legend.AddEntry(h_data, 'Observed', 'PL') for ele in reversed(layout): legend.AddEntry(h_store[ele['name']], '', 'F') bkg_uncert_label = 'Stat. Uncertainty' if not build_h_tot: bkg_uncert_label = 'Uncertainty' legend.AddEntry(h_tot, bkg_uncert_label, 'F') stack.Draw('HISTSAME') h_tot.Draw("E2SAME") if not cfg['hide_data']: h_data.Draw('E0SAME') plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.35) legend.Draw() if cfg['legend_padding'] > 0.: print h_axes[0].GetMinimum(), h_axes[0].GetMaximum() if not h_axes[0].GetMaximum() == 0.: plot.FixBoxPadding(pads[0], legend, cfg['legend_padding']) # Do the ratio plot if cfg['ratio'] or cfg['fraction']: pads[1].cd() pads[1].SetGrid(0, 1) h_axes[1].Draw() if cfg['ratio']: r_data = plot.MakeRatioHist(h_data, h_tot, True, False) r_tot = plot.MakeRatioHist(h_tot, h_tot, True, False) r_tot.Draw('E2SAME') if not cfg['hide_data']: r_data.Draw('SAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Obs/Exp', True, 0.61, 1.69) if cfg['fraction']: r_frac = plot.MakeRatioHist(h_tot, h_data, True, True) r_frac.Draw('SAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Exp/Obs', True, 0.0, 0.5) # Go back and tidy up the axes and frame pads[0].cd() pads[0].GetFrame().Draw() pads[0].RedrawAxis() # CMS logo plot.DrawCMSLogo(pads[0], cfg['main_logo'], cfg['sub_logo'], 11, 0.045, 0.05, 1.0, '', 1.0) plot.DrawTitle(pads[0], cfg['top_title_left'], 1) if cfg['auto_top_title_right']: title_right = h_data.GetTitle() if title_right.startswith('lumi:'): plot.DrawTitle(pads[0], title_right.replace('lumi:', ''), 3) else: plot.DrawTitle(pads[0], cfg['top_title_right'], 3) latex = ROOT.TLatex() plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03) latex.DrawLatex(0.20, 0.75, args.title) # plot.DrawTitle(pads[0], args.title, 1) # ... and we're done canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.png') canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.pdf')
def Compare(w, output, SFname, fn1, fn2, bins, var, other_vars= {}, line_pos=None, ylims=None): label_vars = [] for key, val in other_vars.iteritems(): w.var(key).setVal(val) name = key particle = "" if name=="e_eta": name="#eta(e)" particle = "(e)" if name=="m_eta": name="#eta(#mu)" particle = "(#mu)" label_vars.append('%s=%g' % (name, val)) h1 = w.function(fn1).createHistogram(fn1, w.var(var), ROOT.RooFit.Binning(*bins), ROOT.RooFit.Scaling(False) ) h2 = w.function(fn2).createHistogram(fn2, w.var(var), ROOT.RooFit.Binning(*bins), ROOT.RooFit.Scaling(False) ) herr = h1.Clone() canv = ROOT.TCanvas(output, output) pads = plot.TwoPadSplit(0.30, 0.01, 0.01) pads[0].cd() pads[0].SetGrid(1, 1) plot.Set(h1, LineColor=ROOT.kBlack, LineWidth=2) plot.Set(herr, FillColor=18, MarkerSize=0) plot.Set(herr.GetYaxis(), Title='Scale Factor') plot.Set(herr.GetXaxis(), Title='p_{T}%s' % (particle)) plot.Set(h2, LineColor=ROOT.kRed, LineWidth=2) for i in xrange(1, h1.GetNbinsX()+1): h1.SetBinError(i, 0.) herr.SetBinError(i, herr.GetBinContent(i)*0.02) for i in xrange(1, h2.GetNbinsX()+1): h2.SetBinError(i, 0.) herr.Draw('E3') h1.Draw('LSAME') h2.Draw('LSAME') ratio = h2.Clone() ratio.Divide(h1) ratioerr = herr.Clone() ratioerr.Divide(h1) #legend = ROOT.TLegend(0.18, 0.82, 0.6, 0.93, '', 'NBNDC') #legend.AddEntry(h1, 'KIT + 2% error band', 'L') #legend.AddEntry(h2, 'DESY', 'L') #legend.Draw() print plot.GetPadYMax(pads[0]) #plot.FixTopRange(pads[0], 1.5, 0) #plot.GetPadYMax(pads[0]), 0.25) #plot.FixBothRanges(pads[0], 0.0, 0, 1.5, 0) if ylims==None: upperlim=plot.GetPadYMax(pads[0]) if upperlim>1.2: upperlim=1.2 plot.FixTopRange(pads[0], upperlim, 0.25) else: plot.FixBothRanges(pads[0], ylims[0], 0, ylims[1], 0) plot.DrawTitle(pads[0], SFname, 1) plot.DrawTitle(pads[0], ','.join(label_vars), 3) canv.Update() box = ROOT.TBox() box.SetFillColor(1) box.SetFillStyle(3004) box.DrawBox(bins[1], pads[0].GetUymin(), line_pos, pads[0].GetUymax()) line = ROOT.TLine() plot.Set(line, LineColor=12, LineStyle=4, LineWidth=2) if line_pos is not None: #plot.DrawVerticalLine(pads[0], line, line_pos) line.DrawLine(line_pos, pads[0].GetUymin(), line_pos, pads[0].GetUymax()) legend = ROOT.TLegend(0.18, 0.82, 0.6, 0.93, '', 'NBNDC') legend.AddEntry(h1, 'KIT + 2% error band', 'L') legend.AddEntry(h2, 'DESY', 'L') legend.Draw() pads[1].cd() pads[1].SetGrid(1, 1) ratioerr.Draw('E3') ratio.Draw('LSAME') plot.SetupTwoPadSplitAsRatio( pads, plot.GetAxisHist( pads[0]), plot.GetAxisHist(pads[1]), 'KIT/DESY', True, 0.91, 1.09) canv.Update() box.DrawBox(bins[1], pads[1].GetUymin(), line_pos, pads[1].GetUymax()) if line_pos is not None: #plot.DrawVerticalLine(pads[1], line, line_pos) line.DrawLine(line_pos, pads[1].GetUymin(), line_pos, pads[1].GetUymax()) canv.Print('.pdf') canv.Print('.png')
def SummaryPlots(cfg): h_ref = cfg['h_ref'].Clone() main_label = cfg['main_label'] ref_axis = h_ref.GetYaxis() if cfg['proj'] == 'X' else h_ref.GetXaxis() for ix in xrange(1, ref_axis.GetNbins() + 1): bin_label = '%s #in [%g, %g]' % (cfg['y_label'], ref_axis.GetBinLowEdge(ix), ref_axis.GetBinUpEdge(ix)) canv = ROOT.TCanvas('%s_%s_%i' % (main_label, cfg['proj'], ix), '%s_%s_%i' % (main_label, cfg['proj'], ix)) pads = plot.TwoPadSplit(cfg.get('ratio_split', 0.4), 0.01, 0.01) pads[0].cd() text = ROOT.TPaveText(0.17, 0.84, 0.6, 0.93, 'NDC') legend = ROOT.TLegend(0.6, 0.75, 0.94, 0.93, '', 'NDC') data_hists = MakeProjections(cfg['data'], '%s_data' % main_label, ix, color=cfg.get('data_colour', 4), marker=21, along=cfg['proj']) mc_hists = MakeProjections(cfg['mc'], '%s_mc' % main_label, ix, color=cfg.get('mc_colour', 2), marker=20, along=cfg['proj']) ratio_hists = MakeProjections(cfg['ratio'], '%s_ratio' % main_label, ix, color=cfg.get('ratio_colour', 1), marker=21, along=cfg['proj']) if 'total' in data_hists: data_hists['total'].Draw('E2SAME') if 'syst' in data_hists: data_hists['syst'].Draw('E0X0SAME') if 'stat' in data_hists: data_hists['stat'].Draw('E1X0SAME') if 'stat' in mc_hists: mc_hists['stat'].Draw('E1X0PSAME') if 'syst' in data_hists: legend.AddEntry(data_hists['stat'], 'Data', 'P') legend.AddEntry(data_hists['stat'], ' Statistical', 'E') legend.AddEntry(data_hists['syst'], ' Systematic', 'E') legend.AddEntry(data_hists['total'], ' Total', 'F') legend.AddEntry(mc_hists['stat'], 'Simulation', 'P') legend.AddEntry(mc_hists['stat'], ' Statistical', 'E') else: legend.AddEntry(data_hists['stat'], 'Data', 'PE') legend.AddEntry(mc_hists['stat'], 'Simulation', 'PE') axis = plot.GetAxisHist(pads[0]) plot.Set(axis, Minimum=cfg['y_range'][0], Maximum=cfg['y_range'][1]) plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.40) axis.GetYaxis().SetTitle('Efficiency') pads[1].cd() if 'total' in ratio_hists: ratio_hists['total'].Draw('E2SAME') if 'syst' in ratio_hists: ratio_hists['syst'].Draw('E0X0SAME') if 'stat' in ratio_hists: ratio_hists['stat'].Draw('E1X0SAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Data/Sim', True, cfg['ratio_range'][0], cfg['ratio_range'][1]) r_axis = plot.GetAxisHist(pads[1]) if cfg['logx']: pads[1].SetLogx(True) r_axis.GetXaxis().SetMoreLogLabels(True) r_axis.GetXaxis().SetNoExponent(True) r_axis.GetXaxis().SetTitle(cfg['x_axis_title']) r_axis.GetXaxis().SetTitleOffset(ROOT.gStyle.GetTitleXOffset()) pads[1].SetGrid(1, 1) pads[1].RedrawAxis('g') pads[0].cd() legend.Draw() text.AddText(cfg['main_text']) text.AddText(bin_label) text.SetTextAlign(13) text.SetBorderSize(0) text.Draw() pads[0].SetGrid(1, 1) if cfg['logx']: pads[0].SetLogx(True) canv.Print('.png') canv.Print('.pdf')
legend.Draw() axis = plot.GetAxisHist(pads[0]) plot.Set(axis.GetXaxis(), Title=args.x_title) plot.Set(axis.GetYaxis(), Title='Events') rmin = float(args.ratio_range.split(',')[0]) rmax = float(args.ratio_range.split(',')[1]) pads[1].cd() pads[1].SetGrid(0, 1) if args.type == 0: ratio_hist = res_stitched[0].Clone() ratio_hist.Divide(res_inc[0]) ratio_hist.Draw('SAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Stitched/Inc', True, rmin, rmax) elif args.type == 1: ratios = [] for i, f in enumerate(files): if i == 0: continue ratios.append(res[i].Clone()) ratios[-1].Divide(res[0]) ratios[-1].Draw('SAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Ratio/Inc', True, rmin, rmax) plot.DrawTitle(pads[0], args.title_left, 1) plot.DrawTitle(pads[0], args.title_right, 3)
latex.DrawLatex(0.2, 0.85, args.text) axis = plot.GetAxisHist(pads[0]) plot.Set(axis.GetXaxis(), Title='m_{T} (GeV)') plot.Set(axis.GetYaxis(), Title='a.u.') pads[1].cd() pads[1].SetGrid(0, 1) ratio_hists = [x.Clone() for x in mt_hists] # ratio_hists[0].Draw('') for i, h in enumerate(ratio_hists): h.Divide(mt_hists[0]) h.Draw('SAMEHIST') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Ratio', True, 0.91, 1.09) plot.DrawTitle(pads[0], args.title_left, 1) plot.DrawTitle(pads[0], args.title_right, 3) canv.Print('.pdf') canv.Print('.png') for i, h in enumerate(mt_hists): outfile.WriteTObject(h) outfile.WriteTObject(hratio) outfile.Close()
pads[1].SetGrid(0, 1) h_axes[1].Draw() # r_data = plot.MakeRatioHist(h_data, h_tot, True, False) # r_nominal = plot.MakeRatioHist(h_nominal, h_nominal, True, False) r_0p1 = plot.MakeRatioHist(h_0p1, h_nominal, True, False) r_0p2 = plot.MakeRatioHist(h_0p2, h_nominal, True, False) r_0p4 = plot.MakeRatioHist(h_0p4, h_nominal, True, False) r_1p0 = plot.MakeRatioHist(h_1p0, h_nominal, True, False) r_0p1.Draw('HISTSAME') r_0p2.Draw('HISTSAME') r_0p4.Draw('HISTSAME') r_1p0.Draw('HISTSAME') # r_data.Draw('SAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'C_{3W} = X / Nominal', True, 0.54, args.ratio_max) # Go back and tidy up the axes and frame pads[0].cd() pads[0].GetFrame().Draw() pads[0].RedrawAxis() # CMS logo # plot.DrawCMSLogo(pads[0], 'CMS', 'Internal', 11, 0.045, 0.05, 1.0, '', 1.0) # plot.DrawTitle(pads[0], '0.1 fb^{-1} (13 TeV)', 3) latex = ROOT.TLatex() plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03) # latex.DrawLatex(0.20, 0.75, args.title) plot.DrawTitle(pads[0], '#sqrt{s} = 13 TeV', 3)
if args.y_range is not None: haxis.SetMinimum(float(args.y_range.split(',')[0])) haxis.SetMaximum(float(args.y_range.split(',')[1])) haxis.Draw() c95.Draw('SAME3') c68.Draw('SAME3') best_line.Draw('LXSAME') sm.Draw('LSAME') if split: haxis_lower = haxis.Clone() pads[1].cd() pads[1].SetLogx(True) haxis_lower.Draw() plot.SetupTwoPadSplitAsRatio(pads, haxis, haxis_lower, "Ratio to SM", True, 0.0, 1.5) sm_lower = sm.Clone() best_line_lower = best_line.Clone() for i in xrange(sm.GetN()): sm_lower.GetY()[i] = sm.GetY()[i] / sm.Eval(sm.GetX()[i]) for i in xrange(best_line.GetN()): best_line_lower.GetY()[i] = best_line.GetY()[i] / sm.Eval(best_line.GetX()[i]) c68_lower = c68.Clone() for i in xrange(c68.GetN()): c68_lower.GetY()[i] = c68.GetY()[i] / sm.Eval(c68.GetX()[i]) c68_lower.GetEYhigh()[i] = c68.GetEYhigh()[i] / sm.Eval(c68.GetX()[i]) c68_lower.GetEYlow()[i] = c68.GetEYlow()[i] / sm.Eval(c68.GetX()[i]) c95_lower = c95.Clone() for i in xrange(c95.GetN()): c95_lower.GetY()[i] = c95.GetY()[i] / sm.Eval(c95.GetX()[i]) c95_lower.GetEYhigh()[i] = c95.GetEYhigh()[i] / sm.Eval(c95.GetX()[i])
pads[1].cd() pads[1].SetGrid(0, 1) h_axes[1].Draw() # r_MC = plot.MakeRatioHist(h_MC, h_matrix, True, False) r_pdf_nnlo_fill = plot.MakeRatioHist(h_pdf_nnlo_fill, h_pdf_nnlo_fill, True, False) r_pdf_nlo_fill = plot.MakeRatioHist(h_pdf_nlo_fill, h_pdf_nnlo_fill, True, False) r_pdf_nlo = plot.MakeRatioHist(h_pdf_nlo, h_pdf_nnlo_fill, True, False) r_pdf_nnlo_fill.Draw('E2SAME') r_pdf_nlo_fill.Draw('E2SAME') # r_matrix_fill.Draw('E2SAME') r_pdf_nlo.Draw('HISTSAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'ratio to NNLO', True, 0.92, 1.08) # # # Go back and tidy up the axes and frame pads[0].cd() pads[0].GetFrame().Draw() pads[0].RedrawAxis() canv.Print('.png') canv.Print('.pdf') fout = ROOT.TFile('output_pdf_uncertainty.root', 'RECREATE') NodeToTDir(fout, hists) fout.Close()
if args.logy: axis[0].SetMinimum(0.1) # we'll fix this later pads[0].SetLogy(True) # axis[0].GetYaxis().SetMoreLogLabels() # axis[0].SetNdivisions(50005, "X") y_min, y_max = (plot.GetPadYMin(pads[0]), plot.GetPadYMax(pads[0])) plot.FixBothRanges(pads[0], y_min if args.logy else 0, 0.05 if args.logy else 0, y_max, 0.25) ratio_graph_sets = [] ratio_graphs = [] if args.ratio_to is not None: pads[1].cd() plot.SetupTwoPadSplitAsRatio(pads, axis[0], axis[1], 'Ratio_{}', True, 0.1, 2.4) axis[1].SetNdivisions(506, 'Y') splitsrc = args.ratio_to.split(':') ref = plot.LimitTGraphFromJSONFile(splitsrc[0], splitsrc[1]) for gr_set in graph_sets: ratio_set = {} for key in gr_set: ratio_set[key] = plot.GraphDivide(gr_set[key], ref) ratio_graph_sets.append(ratio_set) plot.DrawLimitBand(pads[1], ratio_graph_sets[-1]) pads[1].RedrawAxis() pads[1].RedrawAxis('g') pads[1].GetFrame().Draw() for gr in graphs: ratio_graphs.append(plot.GraphDivide(gr, ref)) ratio_graphs[-1].Draw('LP')
stack.Add(h_bkg, "hist") stack.Add(h_sig, "hist") stack2 = ROOT.THStack("stack2", "stack2") stack2.Add(h_bkg, "hist") stack2.Add(h_sig_mu1, "hist") if do_ratio: pads = plot.TwoPadSplit(0.35, 0.005, 0.005) else: pads = plot.OnePad() pads[0].SetLogy(True) if do_ratio: plot.SetupTwoPadSplitAsRatio(pads, axes[0], axes[1], "Obs. / Bkg.", True, 0.8, 2.9) axes[1].GetXaxis().SetTitle("log_{10}(S/B)") axes[0].GetYaxis().SetTitle("Events") else: axes[0].GetXaxis().SetTitle("log_{10}(S/B)") axes[0].GetYaxis().SetTitle("Events") axes[0].Draw("axis") axes[0].SetMinimum(1.0) stack.Draw("samenoclear") stack2.Draw("samenoclear") h_err.Draw('e2same') h_dat.Draw("esamex0")
def MakeMultiHistPlot(name, outdir, hists, cfg, layout, ratios=None): js_workaround = False copyhists = {} for hname, h in hists.iteritems(): if len(cfg['rebinvar']): copyhists[hname] = VariableRebin(h, cfg['rebinvar']) else: copyhists[hname] = h.Clone() if cfg['norm_to'] > 0.: copyhists[hname].Scale(cfg['norm_to'] / copyhists[hname].Integral()) if cfg['divwidth']: copyhists[hname].Scale(1., 'width') hists = copyhists # Canvas and pads if cfg['pads'] is not None: pads = cfg['pads'] elif cfg['ratio'] or cfg['fraction']: canv = ROOT.TCanvas(name, name) if cfg['purity']: pads = plot.MultiRatioSplit([0.27, 0.13], [0.005, 0.005], [0.005, 0.005]) else: # if js_workaround: # upper = ROOT.TPad('upper', 'upper', 0., cfg['ratio_pad_frac'], 1., 1.) # upper.SetBottomMargin(0.01) # # upper.SetFillStyle(4000) # upper.Draw() # lower = ROOT.TPad('lower', 'lower', 0., 0., 1., cfg['ratio_pad_frac']) # lower.SetTopMargin(0.01) # # lower.SetFillStyle(4000) # lower.Draw() # upper.cd() # pads = [upper, lower] # else: # pads = plot.TwoPadSplit(cfg['ratio_pad_frac'], 0.01, 0.01) pads = plot.TwoPadSplit(cfg['ratio_pad_frac'], 0.01, 0.01) else: canv = ROOT.TCanvas(name, name) pads = plot.OnePad() # Allow the user to skip specifying a list of entries for a given plot element. # If it's not been specified then we will add it manually for info in layout: if 'entries' not in info: info['entries'] = [info['name']] for opt in cfg['global_hist_opts']: if opt not in info: info[opt] = cfg['global_hist_opts'][opt] h_data = None if cfg['type'] == 'datamc': # Get the data and create axis hist h_data = hists[cfg['data_name']] else: h_data = hists[layout[0]['entries'][0]] if isinstance(h_data, ROOT.TH2): print 'TH2: aborting!' return h_axes = [h_data.Clone() for x in pads] for h in h_axes: h.SetTitle("") if len(cfg['x_range']): h.GetXaxis().SetRangeUser(*cfg['x_range']) h.Reset() build_h_tot = True h_tot = None if 'TotalProcs' in hists: h_tot = hists['TotalProcs'] build_h_tot = False if cfg['type'] != 'datamc': build_h_tot = False if isinstance(cfg['x_title'], list) or isinstance(cfg['x_title'], tuple): x_title = cfg['x_title'][0] units = cfg['x_title'][1] else: x_title = cfg['x_title'] units = '' if x_title == '' and h_data.GetXaxis().GetTitle() != '': x_title = h_data.GetXaxis().GetTitle() if ':' in x_title: units = x_title.split(':')[1] x_title = x_title.split(':')[0] if cfg['logy']: pads[0].SetLogy() h_axes[0].SetMinimum(cfg['logy_min']) rpad_idx = len(pads) - 1 if cfg['ratio'] or cfg['fraction']: plot.StandardAxes(h_axes[rpad_idx].GetXaxis(), h_axes[0].GetYaxis(), x_title, units) else: plot.StandardAxes(h_axes[0].GetXaxis(), h_axes[0].GetYaxis(), x_title, units) h_axes[0].Draw() # A dict to keep track of the hists h_store = {} p_store = {} legend = ROOT.TLegend(*(cfg['legend_pos'] + ['', 'NBNDC'])) stack = ROOT.THStack() purity_stack = ROOT.THStack() curr_auto_colour = 0 for info in layout: hist = hists[info['entries'][0]] if 'color' in info: col = info['color'] else: col = AUTO_COLOURS[curr_auto_colour] if curr_auto_colour == (len(AUTO_COLOURS) - 1): curr_auto_colour = 0 else: curr_auto_colour += 1 # col = info['color'] if isinstance(col, list): col = ROOT.TColor.GetColor(*col) # print info['line_width'] if cfg['type'] == 'multihist': plot.Set(hist, FillColor=col, MarkerColor=col, LineColor=col, Title=info['legend'], MarkerSize=info['marker_size'], LineWidth=info['line_width']) else: plot.Set(hist, FillColor=col, MarkerColor=col, Title=info['legend'], MarkerSize=info['marker_size'], LineWidth=info['line_width']) if len(info['entries']) > 1: for other in info['entries'][1:]: hist.Add(hists[other]) h_store[info['name']] = hist p_store[info['name']] = hist.Clone() if build_h_tot: if h_tot is None: h_tot = hist.Clone() else: h_tot.Add(hist) if cfg['type'] == 'datamc': stack.Add(hist) else: hist.Draw('SAME%s' % info['draw_opts']) # h_tot_purity = h_tot.Clone() for info in layout: p_store[info['name']].Divide(h_tot) purity_stack.Add(p_store[info['name']]) if cfg['type'] == 'datamc': h_tot.SetFillColor(plot.CreateTransparentColor(12, 0.3)) h_tot.SetMarkerSize(0) legend.AddEntry(h_data, 'Observed', 'PL') # Build overlays for info in cfg['overlays']: hist = None input_list = [] if isinstance(info['entries'], str): input_list = list(all_input_hists) else: input_list = list(info['entries']) updated_list = [] for xh in input_list: if xh + info['hist_postfix'] in hists: updated_list.append(xh + info['hist_postfix']) else: updated_list.append(xh) print updated_list hist = HistSum(hists, updated_list) col = info['color'] if isinstance(col, list): col = ROOT.TColor.GetColor(*col) plot.Set(hist, LineColor=col, LineWidth=1, MarkerSize=0, Title=info['legend']) for ib in xrange(1, hist.GetNbinsX() + 1): hist.SetBinError(ib, 1E-7) h_store[info['name']] = hist if cfg['type'] == 'datamc': for ele in reversed(layout): legend.AddEntry(h_store[ele['name']], ele['legend'], ele['legend_opts']) else: for ele in layout: leg_extra = '' if cfg['legend_show_yields']: leg_extra = ' (%.1f)' % h_store[ele['name']].Integral( 'width' if cfg['divwidth'] else '') legend.AddEntry(h_store[ele['name']], ele['legend'] + leg_extra, ele['legend_opts']) if cfg['type'] == 'datamc': bkg_uncert_label = 'Stat. Uncertainty' if not build_h_tot: bkg_uncert_label = 'Uncertainty' legend.AddEntry(h_tot, bkg_uncert_label, 'F') stack.Draw('HISTSAME') h_tot.Draw("E2SAME") for info in cfg['overlays']: h_store[info['name']].Draw('HISTSAME') if not cfg['hide_data']: h_data.Draw('E0SAME') for info in cfg['overlays']: legend.AddEntry(h_store[info['name']], info['legend'], 'L') plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.35) legend.Draw() # if cfg['legend_padding'] > 0.: # plot.FixBoxPadding(pads[0], legend, cfg['legend_padding']) # Do the ratio plot r_store = {} r_data = None r_tot = None if cfg['ratio'] or cfg['fraction']: pads[rpad_idx].cd() pads[rpad_idx].SetGrid(0, 1) h_axes[rpad_idx].Draw() if cfg['type'] == 'datamc' and cfg['ratio']: r_data = plot.MakeRatioHist(h_data, h_tot, True, False) r_tot = plot.MakeRatioHist(h_tot, h_tot, True, False) r_tot.Draw('E2SAME') for info in cfg['overlays']: r_store[info['name']] = plot.MakeRatioHist( h_store[info['name']], h_tot, False, False) r_store[info['name']].Draw('SAME') if not cfg['hide_data']: r_data.Draw('SAME') if cfg['type'] == 'datamc' and cfg['fraction']: r_frac = plot.MakeRatioHist(h_tot, h_data, True, True) r_frac.Draw('SAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[rpad_idx]), 'Exp/Obs', True, 0.0, 0.5) if ratios is not None: for info in ratios: if 'type' in info and info['type'] == 'binomial': rhist = h_store[info['num']].Clone() rhist.Divide(h_store[info['num']], h_store[info['den']], 1., 1., "B") elif 'type' in info and info['type'] == 'noerror': rhist = plot.MakeRatioHist(h_store[info['num']], h_store[info['den']], True, False) else: rhist = plot.MakeRatioHist(h_store[info['num']], h_store[info['den']], True, True) r_store['%s_%s' % (info['num'], info['den'])] = rhist rhist.Draw('SAMEE0') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[rpad_idx]), cfg['ratio_y_title'], True, *(cfg['ratio_y_range'])) if js_workaround: # This makes the ticks way too large plot.GetAxisHist(pads[rpad_idx]).GetYaxis().SetTickLength( ROOT.gStyle.GetTickLength()) if cfg['purity']: pads[1].cd() h_axes[1].Draw() plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'f', True, 0, 1) plot.Set(h_axes[1].GetXaxis(), TitleSize=0, LabelSize=0) plot.Set(h_axes[1].GetYaxis(), Ndivisions=(502, False)) purity_stack.Draw('HISTSAME') # purity_stack.Print() h_axes[1].SetMinimum(0) h_axes[1].SetMaximum(1) pads[1].RedrawAxis() # Go back and tidy up the axes and frame pads[0].cd() if not js_workaround: pads[0].GetFrame().Draw() pads[0].RedrawAxis() # CMS logo plot.DrawCMSLogo(pads[0], cfg['main_logo'], cfg['sub_logo'], 11, 0.045, 0.05, 1.0, '', 1.0) plot.DrawTitle(pads[0], cfg['top_title_left'], 1) if cfg['auto_top_title_right']: title_right = h_data.GetTitle() if title_right.startswith('lumi:'): plot.DrawTitle(pads[0], title_right.replace('lumi:', ''), 3) latex = ROOT.TLatex() plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03) # latex.DrawLatex(0.20, 0.75, args.title) # plot.DrawTitle(pads[0], args.title, 1) # ... and we're done if cfg['pads'] is None: canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.png') canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.pdf') # canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.root') # canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.svg') # canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.json') outobjs = {} outobjs['axes'] = h_axes outobjs['hists'] = hists outobjs['stack'] = stack outobjs['purity_stack'] = purity_stack outobjs['h_tot'] = h_tot outobjs['legend'] = legend outobjs['r_store'] = r_store outobjs['p_store'] = p_store outobjs['r_data'] = r_data outobjs['r_tot'] = r_tot return outobjs
def main(files, label, output, draw_options, title, y_range, ratio_y_range, binned_in, x_title, ratio_to, plot_dir, label_pos): ROOT.PyConfig.IgnoreCommandLineOptions = True ROOT.gROOT.SetBatch(ROOT.kTRUE) ROOT.TH1.AddDirectory(0) plot.ModTDRStyle() # parser = argparse.ArgumentParser() # parser.add_argument( # 'input', nargs='+', help="""Input files""") # parser.add_argument( # '--output', '-o', default='efficiency', help="""Name of the output # plot without file extension""") # parser.add_argument('--title', default='Muon ID Efficiency') # parser.add_argument('--y-range', default='0,1') # parser.add_argument('--ratio-y-range', default='0.5,1.5') # parser.add_argument('--binned-in', default='#eta') # parser.add_argument('--x-title', default='p_{T} (GeV)') # parser.add_argument('--ratio-to', default=None, type=int) # parser.add_argument('--plot-dir', '-p', default='./') # parser.add_argument('--label-pos', default=1) # args = parser.parse_args() if plot_dir != '': os.system('mkdir -p %s' % plot_dir) hists = [] # file = ROOT.TFile('%s.root' % target) # Process each input argument for src in files: #splitsrc = src.split(':') file = ROOT.TFile(src) if src.find("gen") >= 0: hists.append(file.Get(label + "_tot").Clone()) else: hists.append(file.Get(label).Clone()) file.Close() print hists hist = hists[0] latex = ROOT.TLatex() latex.SetNDC() for i in xrange(1, hist.GetNbinsY() + 1): bin_label = '%s: [%g,%g]' % (binned_in, hist.GetYaxis().GetBinLowEdge(i), hist.GetYaxis().GetBinUpEdge(i)) canv = ROOT.TCanvas('%s_%i' % (output, i), output) if ratio_to is not None: pads = plot.TwoPadSplit(0.50, 0.01, 0.01) else: pads = plot.OnePad() slices = [] if label_pos == 1: text = ROOT.TPaveText(0.55, 0.37, 0.9, 0.50, 'NDC') legend = ROOT.TLegend(0.18, 0.37, 0.5, 0.50, '', 'NDC') elif label_pos == 2: text = ROOT.TPaveText(0.55, 0.67, 0.9, 0.80, 'NDC') legend = ROOT.TLegend(0.18, 0.67, 0.5, 0.80, '', 'NDC') else: text = ROOT.TPaveText(0.55, 0.54, 0.9, 0.67, 'NDC') legend = ROOT.TLegend(0.55, 0.67, 0.9, 0.80, '', 'NDC') text = ROOT.TPaveText(0.55, 0.54, 0.9, 0.67, 'NDC') legend = ROOT.TLegend(0.6, 0.54, 0.95, 0.74, '', 'NDC') #~ if 'ID' in splitsrc[1]: #~ legend = ROOT.TLegend(0.18, 0.67, 0.5, 0.85, '', 'NDC') for j, src in enumerate(files): #splitsrc = src.split(':') htgr = hists[j].ProjectionX( '%s_projx_%i' % (hists[j].GetName(), j), i, i) #if len(splitsrc) >= 3: # settings = {x.split('=')[0]: eval(x.split('=')[1]) for x in splitsrc[2].split(',')} if draw_options[j] != None: settings = draw_options[j] plot.Set(htgr, **settings) htgr.Draw('HIST LP SAME') #htgr.Draw('SAME') legend.AddEntry(htgr) slices.append(htgr) latex.SetTextSize(0.06) #~ text.AddText(args.title) #~ text.AddText(bin_label) #~ text.SetTextAlign(13) #~ text.SetBorderSize(0) #~ text.Draw() legend.Draw() axis = plot.GetAxisHist(pads[0]) axis.GetYaxis().SetTitle('Efficiency') axis.GetXaxis().SetTitle(x_title) #~ axis.GetXaxis().SetRange(10,1000) axis.SetMinimum(float(y_range[0])) axis.SetMaximum(float(y_range[1])) pads[0].SetGrid(0, 1) pads[0].SetLogx(True) pads[0].RedrawAxis('g') #~ plot.DrawCMSLogo(pads[0], args.title, bin_label, 0, 0.16, 0.035, 1.2, cmsTextSize=0.5) plot.DrawTitle(pads[0], title + ' - ' + bin_label, 1) #plot.DrawTitle(pads[0], '18.99 fb^{-1} (13 TeV)', 3) plot.DrawTitle(pads[0], '41.29 fb^{-1} (13 TeV)', 3) if ratio_to is not None: pads[1].cd() pads[1].SetLogx(True) ratios = [] for slice in slices: ratios.append(slice.Clone()) ratios[-1].Divide(slices[ratio_to]) ratios[0].Draw('AXIS') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Ratio to data', True, float(ratio_y_range[0]), float(ratio_y_range[1])) for j, ratio in enumerate(ratios): if j == ratio_to: continue ratio.Draw('HIST LP SAME') #('SAME E0') pads[1].SetGrid(0, 1) pads[1].RedrawAxis('g') outname = '%s.%s.%g_%g' % (output, hist.GetYaxis().GetTitle(), hist.GetYaxis().GetBinLowEdge(i), hist.GetYaxis().GetBinUpEdge(i)) outname = outname.replace('(', '_') outname = outname.replace(')', '_') outname = outname.replace('.', '_') canv.Print('%s/%s.png' % (plot_dir, outname)) canv.Print('%s/%s.pdf' % (plot_dir, outname))