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')
# Fill TH2s by interpolating the TGraph2Ds, then extract contours for c in types: print 'Filling histo for %s' % c hists[c] = h_proto.Clone(c) plot.fillTH2(hists[c], graphs[c]) contours[c] = plot.contourFromTH2(hists[c], CL, 5, frameValue=1) if debug is not None: debug.WriteTObject(hists[c], 'hist_%s' % c) for i, cont in enumerate(contours[c]): debug.WriteTObject(cont, 'cont_%s_%i' % (c, i)) # Setup the canvas: we'll use a two pad split, with a small top pad to contain # the CMS logo and the legend canv = ROOT.TCanvas(args.output, args.output) pads = plot.TwoPadSplit(0.8, 0, 0) pads[1].cd() h_axis.GetXaxis().SetTitle(args.x_title) h_axis.GetYaxis().SetTitle(args.y_title) h_axis.Draw() if args.hist is not None: colzhist = h_proto.Clone(c) plot.fillTH2(colzhist, file.Get(args.hist)) colzhist.SetContour(255) colzhist.Draw('COLZSAME') colzhist.GetZaxis().SetLabelSize(0.03) if args.z_range is not None: colzhist.SetMinimum(float(args.z_range.split(',')[0])) colzhist.SetMaximum(float(args.z_range.split(',')[1])) if args.z_title is not None:
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
axis_hists[i].Draw('AXIS') axis_hists[i].Draw('AXIGSAME') if def_pad is not None: def_pad.cd() ## Boilerplate ROOT.PyConfig.IgnoreCommandLineOptions = True ROOT.gROOT.SetBatch(ROOT.kTRUE) plot.ModTDRStyle() ROOT.gStyle.SetNdivisions(510, 'XYZ') # probably looks better canv = ROOT.TCanvas(args.output, args.output) if args.ratio_to is not None: pads = plot.TwoPadSplit(0.30, 0.01, 0.01) else: pads = plot.OnePad() # Set the style options of the pads for padx in pads: # Use tick marks on oppsite axis edges plot.Set(padx, Tickx=1, Ticky=1, Logx=args.logx) if args.pad_style is not None: settings = { x.split('=')[0]: eval(x.split('=')[1]) for x in args.pad_style.split(',') } print 'Applying style options to the TPad(s):' print settings plot.Set(padx, **settings)
args.output = folder else: if args.output[-1] == '/' and not os.path.exists(args.output): os.makedirs(args.output) for target in target_list: if len(target_list) == 1: output = args.output if args.output != '' else target.split('/')[-1] else: output = args.output + target.split('/')[-1] if args.logy: output += '_logy' # Canvas and pads canv = ROOT.TCanvas(output, output) pads = plot.TwoPadSplit(0.27, 0.01, 0.01) # Get the data and create axis hist h_data = Getter(file, '%s/data_obs' % target, True) if isinstance(h_data, ROOT.TH2): print 'TH2: aborting!' continue h_axes = [h_data.Clone() for x in pads] for h in h_axes: # h.GetXaxis().SetLimits(2.1,200) h.Reset() build_h_tot = True h_tot = Getter(file, '%s/TotalProcs' % target, True) if h_tot is not None:
#intree_DYMC.Draw("pt_2>>LOMC_Z_pt","(trg_1||trg_2)*(wt_pu)") #intree_DYMC.Draw("pt_ll>>LOMC_Z_pt","((trg_1||trg_2)&&dr_ll>0.5)*(wt_pu)") intree_DYMC.Draw( "pt_ll>>LOMC_Z_pt", "((trg_1||trg_2)&&dr_ll>0.5)*(wt_pu*wt_1*wt_2*wt_trg*gen_wt)") LOMC_Z_pt.Scale(6225.42 * 41519.180032466 / LOMC_counter.GetBinContent(2)) LOMC_Z_pt.SetFillStyle(1001) LOMC_Z_pt.SetFillColor(ROOT.TColor.GetColor(100, 192, 232)) LOMC_Z_pt.SetLineColor(ROOT.kBlack) LOMC_Z_pt_unc = LOMC_Z_pt.Clone("LOMC_Z_pt_unc") LOMC_Z_pt_unc.SetFillColor(plot.CreateTransparentColor(12, 0.4)) LOMC_Z_pt_unc.SetLineColor(0) LOMC_Z_pt_unc.SetMarkerSize(0) canvas = ROOT.TCanvas("c1", "c1") pads = plot.TwoPadSplit(0.29, 0.01, 0.01) axish = createAxisHists(2, LOMC_Z_mass, LOMC_Z_mass.GetXaxis().GetXmin(), LOMC_Z_mass.GetXaxis().GetXmax() - 0.01) pads[0].SetLogy() axish[0].GetYaxis().SetRangeUser(1, 12 * LOMC_Z_mass.GetMaximum()) axish[0].GetXaxis().SetTitleSize(0) axish[0].GetXaxis().SetLabelSize(0) axish[1].GetYaxis().SetRangeUser(0.8, 1.2) axish[1].GetXaxis().SetTitle("m_{ee} [GeV]") axish[0].GetYaxis().SetTitle("Events") axish[1].GetYaxis().SetTitle("Obs/Exp") ratio_mchist = plot.MakeRatioHist(LOMC_Z_mass_unc, LOMC_Z_mass_unc, True, False) ratio_datahist = plot.MakeRatioHist(data_Z_mass, LOMC_Z_mass, True, False)
def main(args): fitvars = 'm_sv_vs_pt_tt' fitvars = 'm_sv' if len(args.file_dir.split("_")) >= 4: era = args.file_dir.split("_")[3] else: era = 'all' if era == "2016": lumi = "36.3 fb^{-1} (13 TeV)" elif era == "2017": lumi = "41.5 fb^{-1} (13 TeV)" elif era == "2018": lumi = "59.7 fb^{-1} (13 TeV)" elif era == "all": lumi = "138 fb^{-1} (13 TeV)" plot.ModTDRStyle(width=1800, height=700, r=0.4, l=0.16, t=0.12, b=0.15) ROOT.TGaxis.SetExponentOffset(-0.06, 0.01, "y") # Channel & Category label if args.channel == '': args.channel = args.file_dir.split("_")[1] if args.channel == "tt": channel_label = "#tau_{h}#tau_{h}" if args.channel == "lt": channel_label = "#mu_{}#tau_{h}+e_{}#tau_{h}" if args.channel == "mt": channel_label = "#mu_{}#tau_{h}" if args.channel == "et": channel_label = "e_{}#tau_{h}" if args.channel == "em": channel_label = "e_{}#mu_{}" bin_number = args.file_dir.split("_")[2] #if args.ratio_range=="": # args.ratio_range = "0.7,1.3" if bin_number in ["2", "35", "36", "37"]: if args.channel == 'tt': bin_label = "b tag" if args.channel in ['mt', 'et', 'lt']: bin_label = "b tag" if bin_number == "35": bin_label = "b tag, Tight-m_{T}" if bin_number == "36": bin_label = "b tag, Loose-m_{T}" if args.channel in ['em']: bin_label = "b tag" if bin_number == "2": bin_label = "t#bar{t} CR" if bin_number == "35": bin_label = "b tag, High D_{#zeta}" if bin_number == "36": bin_label = "b tag, Medium D_{#zeta}" if bin_number == "37": bin_label = "b tag, Low D_{#zeta}" plot.ModTDRStyle(r=0.04, l=0.18) if args.ratio_range == "": args.ratio_range = "0.85,1.15" bin_label = "b tag" # no sub labels when combing all sub-categories if bin_number in ["32", "33", "34"]: if args.ratio_range == "": args.ratio_range = "0.4,1.6" if args.channel == 'tt': bin_label = "No b tag" if args.channel in ['mt', 'et', 'lt']: bin_label = "No b tag" if bin_number == "32": bin_label = "No b tag, Tight-m_{T}" if bin_number == "33": bin_label = "No b tag, Loose-m_{T}" if args.channel in ['em']: bin_label = "No b tag" if bin_number == "32": bin_label = "No b tag, High D_{#zeta}" if bin_number == "33": bin_label = "No b tag, Medium D_{#zeta}" if bin_number == "34": bin_label = "No b tag, Low D_{#zeta}" bin_label = "b tag" # no sub labels when combing all sub-categories if bin_number in [ "132", "232", "332", "432", "133", "233", "333", "433", "33", "34" ]: if args.ratio_range == "": args.ratio_range = "0.7,1.3" if args.channel == 'tt': bin_label = "No b tag" if args.channel in ['mt', 'et', 'lt']: bin_label = "No b tag" if bin_number[1:] == "32": bin_label = "No b tag, Tight-m_{T}" if bin_number[1:] == "33": bin_label = "No b tag, Loose-m_{T}" if args.channel in ['em']: bin_label = "No b tag" if bin_number[1:] == "32": bin_label = "No b tag, High D_{#zeta}" if bin_number[1:] == "33": bin_label = "No b tag, Medium D_{#zeta}" if bin_number[1:] == "34": bin_label = "No b tag, Low D_{#zeta}" bin_label = "No b tag" # no sub labels when combing all sub-categories if bin_number[0] == '1': bin_label += ', p_{T}^{#tau#tau}<50 GeV' if bin_number[0] == '2': bin_label += ', 50< p_{T}^{#tau#tau}<100 GeV' if bin_number[0] == '3': bin_label += ', 100< p_{T}^{#tau#tau}<200 GeV' if bin_number[0] == '4': bin_label += ', p_{T}^{#tau#tau}> 200 GeV' plot.ModTDRStyle(r=0.04, l=0.18) ## Add bin labels bin_labels = {} with open("scripts/bin_labels.json") as jsonfile: full_bin_labels = json.load(jsonfile) if bin_number in ["32", "33", "34"]: bin_labels = full_bin_labels[fitvars]['nobtag'] else: bin_labels = full_bin_labels[fitvars]['btag'] is2D = False print fitvars, bin_number if fitvars == 'm_sv' or bin_number in [ "2", "35", "36", "37", "132", "232", "332", "432", "133", "233", "333", "433" ]: x_title = "m_{#tau#tau} (GeV)" #x_bins = re.split("\[|\]",bin_labels)[1].split(",") #Nxbins = len(x_bins) - 1 else: is2D = True x_title = "Bin number" x_bins = re.split("\[|\]", bin_labels)[3].split(",") Nxbins = len(x_bins) - 1 if is2D: y_bin_var = re.split(",|\[|\]", bin_labels)[0] y_bin_labels = re.split("\[|\]", bin_labels)[1].split(",") else: y_bin_var = "" y_bin_labels = "" is2D = False # we now split 2D histograms into 1D file_dir = args.file_dir mode = args.mode manual_blind = args.manual_blind x_blind_min = args.x_blind_min x_blind_max = args.x_blind_max cms_label = args.cms_label empty_bin_error = args.empty_bin_error extra_pad = float(args.extra_pad) custom_x_range = args.custom_x_range custom_y_range = args.custom_y_range x_axis_min = float(args.x_axis_min) x_axis_max = float(args.x_axis_max) y_axis_min = float(args.y_axis_min) y_axis_max = float(args.y_axis_max) log_y = args.log_y log_x = args.log_x if (args.outname != ''): outname = args.outname + '_' else: outname = '' if args.file_dir == "htt_tt_232": extra_pad = 0.45 if args.file_dir == "htt_tt_35": extra_pad = 0.57 if args.file_dir == "htt_tt_132": extra_pad = 0.65 if args.file_dir == "htt_tt_232": extra_pad = 0.62 if args.file_dir == "htt_em_35": extra_pad = 0.7 if args.file_dir == "htt_lt_35": extra_pad = 0.45 if args.file_dir == "htt_lt_232": extra_pad = 0.45 if args.file_dir == "htt_em_232": extra_pad = 0.45 if '_35' in args.file_dir or '_132' in args.file_dir or '_232' in args.file_dir or args.bOnly: cms_label = 'Supplementary' if args.file: print "Providing shape file: ", args.file, ", with specified subdir name: ", file_dir shape_file = args.file shape_file_name = args.file histo_file = ROOT.TFile(shape_file) #Store plotting information for different backgrounds background_schemes = { 'mt': [ backgroundComp("Others", ["ZL", "VVL", "qqH125", "bbH125", "ggH125"], ROOT.TColor.GetColor("#B0C4DE")), #backgroundComp("H(125 GeV)#rightarrow#tau#tau",["qqH125","bbH125","ggH125"],ROOT.TColor.GetColor(51,51,230)), #backgroundComp("Diboson",["VVL"],ROOT.TColor.GetColor("#6F2D35")), backgroundComp("t#bar{t}", ["TTL"], ROOT.TColor.GetColor("#9999cc")), #backgroundComp("Z#rightarrowll",["ZL"],ROOT.TColor.GetColor("#4496c8")), backgroundComp("Jet#rightarrow#tau_{h}", ["jetFakes"], ROOT.TColor.GetColor(192, 232, 100)), backgroundComp("#tau#tau Bkg.", ["EMB"], ROOT.TColor.GetColor("#ffcc66")), ], 'et': [ backgroundComp("Others", ["ZL", "VVL", "qqH125", "bbH125", "ggH125"], ROOT.TColor.GetColor("#B0C4DE")), #backgroundComp("H(125 GeV)#rightarrow#tau#tau",["qqH125","bbH125","ggH125"],ROOT.TColor.GetColor(51,51,230)), #backgroundComp("Diboson",["VVL"],ROOT.TColor.GetColor("#6F2D35")), backgroundComp("t#bar{t}", ["TTL"], ROOT.TColor.GetColor("#9999cc")), #backgroundComp("Z#rightarrowll",["ZL"],ROOT.TColor.GetColor("#4496c8")), backgroundComp("Jet#rightarrow#tau_{h}", ["jetFakes"], ROOT.TColor.GetColor(192, 232, 100)), backgroundComp("#tau#tau Bkg.", ["EMB"], ROOT.TColor.GetColor("#ffcc66")), ], 'lt': [ backgroundComp("Others", ["ZL", "VVL", "qqH125", "bbH125", "ggH125"], ROOT.TColor.GetColor("#B0C4DE")), #backgroundComp("H(125 GeV)#rightarrow#tau#tau",["qqH125","bbH125","ggH125"],ROOT.TColor.GetColor(51,51,230)), #backgroundComp("Diboson",["VVL"],ROOT.TColor.GetColor("#6F2D35")), backgroundComp("t#bar{t}", ["TTL"], ROOT.TColor.GetColor("#9999cc")), #backgroundComp("Z#rightarrowll",["ZL"],ROOT.TColor.GetColor("#4496c8")), backgroundComp("Jet#rightarrow#tau_{h}", ["jetFakes"], ROOT.TColor.GetColor(192, 232, 100)), backgroundComp("#tau#tau Bkg.", ["EMB"], ROOT.TColor.GetColor("#ffcc66")), ], 'tt': [ backgroundComp("Others", ["ZL", "VVL", "qqH125", "bbH125", "ggH125"], ROOT.TColor.GetColor("#B0C4DE")), #backgroundComp("H(125 GeV)#rightarrow#tau#tau",["qqH125","bbH125","ggH125"],ROOT.TColor.GetColor(51,51,230)), #backgroundComp("Diboson",["VVL"],ROOT.TColor.GetColor("#6F2D35")), backgroundComp("t#bar{t}", ["TTL"], ROOT.TColor.GetColor("#9999cc")), #backgroundComp("Z#rightarrowll",["ZL"],ROOT.TColor.GetColor("#4496c8")), backgroundComp("Jet#rightarrow#tau_{h}", ["jetFakes", "wFakes"], ROOT.TColor.GetColor(192, 232, 100)), backgroundComp("#tau#tau Bkg.", ["EMB"], ROOT.TColor.GetColor("#ffcc66")), ], 'em': [ backgroundComp("Others", [ "ZL", "qqH125", "bbH125", "ggH125", 'WHWW125', 'ZHWW125', 'ggHWW125', 'qqHWW125', "W", "VVL" ], ROOT.TColor.GetColor("#B0C4DE")), #backgroundComp("H(125 GeV)",["qqH125","bbH125","ggH125",'WHWW125','ZHWW125','ggHWW125','qqHWW125'],ROOT.TColor.GetColor(51,51,230)), backgroundComp("QCD", ["QCD"], ROOT.TColor.GetColor("#ffccff")), #backgroundComp("Electroweak",["W","VVL"],ROOT.TColor.GetColor(222, 90, 106)), backgroundComp("t#bar{t}", ["TTL"], ROOT.TColor.GetColor("#9999cc")), #backgroundComp("Z#rightarrowll",["ZL"],ROOT.TColor.GetColor("#4496c8")), backgroundComp("#tau#tau Bkg.", ["EMB"], ROOT.TColor.GetColor("#ffcc66")), ], } #Extract relevent histograms from shape file sighists = [] #signal_names = 'TotalSig' signal_names = ['ggh_t', 'ggh_i', 'ggh_b'] if args.no_signal: signal_names = [] file_dir_list = [] file_dir_list = [file_dir] if not args.no_signal: [sighist, binname] = getHistogram(histo_file, signal_names, file_dir_list, mode, args.no_signal, log_x) sighists.append(sighist) bkghist = getHistogram(histo_file, 'TotalBkg', file_dir, mode, logx=log_x)[0] sbhist = bkghist.Clone() # can use this one for showing ggX as well as qqX sbhist_alt = bkghist.Clone() if not args.use_asimov: total_datahist = getHistogram(histo_file, "data_obs", file_dir, mode, logx=log_x)[0] else: total_datahist = getHistogram(histo_file, "TotalProcs", file_dir, mode, logx=log_x)[0].Clone() for bin_ in range(1, total_datahist.GetNbinsX() + 1): content = total_datahist.GetBinContent(bin_) total_datahist.SetBinError(bin_, np.sqrt(content)) blind_datahist = total_datahist.Clone() total_datahist.SetMarkerStyle(20) blind_datahist.SetMarkerStyle(20) blind_datahist.SetLineColor(1) total_bkg = getHistogram(histo_file, "TotalBkg", file_dir, mode, logx=log_x)[0].Clone() azimov_datahist = blind_datahist.Clone() for i in range(0, azimov_datahist.GetNbinsX() + 1): azimov_datahist.SetBinContent(i, -0.1) azimov_datahist.SetBinError(i, 0) azimov_datahist.SetLineColor(ROOT.kRed) azimov_datahist.SetMarkerColor(ROOT.kRed) #Blinding by hand using requested range, set to 70-110 by default # for 0jet category if not is2D and manual_blind: for i in range(0, total_datahist.GetNbinsX()): low_edge = total_datahist.GetBinLowEdge(i + 1) high_edge = low_edge + total_datahist.GetBinWidth(i + 1) if ((low_edge > float(x_blind_min) and low_edge < float(x_blind_max)) or (high_edge > float(x_blind_min) and high_edge < float(x_blind_max))): blind_datahist.SetBinContent(i + 1, -0.1) blind_datahist.SetBinError(i + 1, 0) c = total_bkg.GetBinContent(i + 1) azimov_datahist.SetBinContent(i + 1, c) azimov_datahist.SetBinError(i + 1, c**.5) # for boosted category: if is2D and manual_blind: x_blind_ind = [ ind for ind, x in enumerate(x_bins) if 120 >= int(x) >= 70 ] x_blind_ind1 = [] dummy_list = [ int(x) for x in np.linspace(Nxbins, Nxbins * Nxbins, Nxbins) ] for i in range(0, total_datahist.GetNbinsX()): if i in dummy_list: x_blind_ind1 = [x + i for x in x_blind_ind] if i in x_blind_ind or i in x_blind_ind1: blind_datahist.SetBinContent(i + 1, -0.1) blind_datahist.SetBinError(i + 1, 0) c = total_bkg.GetBinContent(i + 1) azimov_datahist.SetBinContent(i + 1, c) azimov_datahist.SetBinError(i + 1, c**.5) #Set bin errors for empty bins if required: if empty_bin_error: for i in range(1, blind_datahist.GetNbinsX() + 1): if blind_datahist.GetBinContent(i) == 0: blind_datahist.SetBinError(i, 1.8) #Set uniform bin errors properly for Content < 10 bins if args.proper_errors_uniform: proper_errs_dict = { 0: 1.29, 1: 2.38, 2: 3.51, 3: 4.20, 4: 4.44, 5: 5.06, 6: 5.46, 7: 6.05, 8: 6.02, 9: 6.46 } for i in range(1, blind_datahist.GetNbinsX() + 1): if blind_datahist.GetBinContent( i) < 9.5 and blind_datahist.GetBinContent(i) >= 0: new_err = proper_errs_dict[round( blind_datahist.GetBinContent(i))] blind_datahist.SetBinError(i, new_err) #Normalise by bin width scale = 1.0 if is2D: scale = 1. / 10. # if we have an unrolled plot then we need to account for the bins being in 10 GeV units bkghist.Scale(scale, "width") sbhist.Scale(scale, "width") for shist in sighists: if mode == 'prefit': shist.Scale(6.0 * scale, "width") # can scale up signals here if desired else: shist.Scale(scale, "width") # can scale up signals here if desired for shist in sighists: sbhist.Add(shist) #sbhist.Scale(scale,"width") #sbhist_alt.Scale(scale,"width") blind_datahist.Scale(scale, "width") azimov_datahist.Scale(scale, "width") blind_datagraph = ROOT.TGraphAsymmErrors(blind_datahist) azimov_datagraph = ROOT.TGraphAsymmErrors(azimov_datahist) channel = args.channel #Create stacked plot for the backgrounds bkg_histos = [] for i, t in enumerate(background_schemes[channel]): plots = t['plot_list'] isHist = False h = ROOT.TH1F() for j, k in enumerate(plots): if h.GetEntries() == 0 and getHistogram( histo_file, k, file_dir, mode, False, logx=log_x) is not None: isHist = True h = getHistogram(histo_file, k, file_dir, mode, logx=log_x)[0] h.SetName(k) else: if getHistogram(histo_file, k, file_dir, mode, False, logx=log_x) is not None: isHist = True h.Add( getHistogram(histo_file, k, file_dir, mode, logx=log_x)[0]) h.SetFillColor(t['colour']) h.SetLineColor(ROOT.kBlack) h.SetMarkerSize(0) h.Scale(scale, "width") if isHist: bkg_histos.append(h) stack = ROOT.THStack("hs", "") for hists in bkg_histos: stack.Add(hists) #Setup style related things c2 = ROOT.TCanvas() c2.cd() if args.ratio: pads = plot.TwoPadSplit(0.35, 0.01, 0.01) else: pads = plot.OnePad() for p in pads: p.SetFrameLineWidth(1) pads[0].cd() if (log_y): pads[0].SetLogy(1) if (log_x): pads[0].SetLogx(1) if custom_x_range: if x_axis_max > bkghist.GetXaxis().GetXmax(): x_axis_max = bkghist.GetXaxis().GetXmax() if args.ratio: if (log_x): pads[1].SetLogx(1) axish = createAxisHists(2, bkghist, bkghist.GetXaxis().GetXmin(), bkghist.GetXaxis().GetXmax() - 0.01) axish[1].GetXaxis().SetTitle(x_title) if is2D: axish[1].GetXaxis().SetLabelSize(0.03) axish[1].GetYaxis().SetNdivisions(4) axish[1].GetYaxis().SetLabelSize(0.033) axish[1].GetXaxis().SetLabelSize(0.033) if is2D: axish[1].GetXaxis().SetNdivisions(bkghist.GetNbinsX() / Nxbins, Nxbins, 0, False) axish[0].GetYaxis().SetTitleSize(0.048) axish[0].GetYaxis().SetLabelSize(0.033) axish[0].GetYaxis().SetTitleOffset(0.5) axish[0].GetXaxis().SetTitleSize(0) axish[0].GetXaxis().SetLabelSize(0) if is2D: axish[0].GetXaxis().SetNdivisions(bkghist.GetNbinsX() / Nxbins, Nxbins, 0, False) axish[0].GetYaxis().SetTitleSize(axish[1].GetXaxis().GetTitleSize()) axish[0].GetXaxis().SetRangeUser(x_axis_min, bkghist.GetXaxis().GetXmax() - 0.01) axish[1].GetXaxis().SetRangeUser(x_axis_min, bkghist.GetXaxis().GetXmax() - 0.01) axish[0].GetXaxis().SetMoreLogLabels() axish[0].GetXaxis().SetNoExponent() axish[1].GetXaxis().SetMoreLogLabels() axish[1].GetXaxis().SetNoExponent() axish[1].GetXaxis().SetTitleOffset(0.85) if not is2D: axish[0].GetXaxis().SetRangeUser( 0., bkghist.GetXaxis().GetXmax() - 0.01) axish[1].GetXaxis().SetRangeUser( 0., bkghist.GetXaxis().GetXmax() - 0.01) if custom_x_range: axish[0].GetXaxis().SetRangeUser(x_axis_min, x_axis_max - 0.01) axish[1].GetXaxis().SetRangeUser(x_axis_min, x_axis_max - 0.01) if custom_y_range: axish[0].GetYaxis().SetRangeUser(y_axis_min, y_axis_max) axish[1].GetYaxis().SetRangeUser(y_axis_min, y_axis_max) else: axish = createAxisHists(1, bkghist, bkghist.GetXaxis().GetXmin(), bkghist.GetXaxis().GetXmax() - 0.01) if custom_x_range: axish[0].GetXaxis().SetRangeUser(x_axis_min, x_axis_max - 0.01) if custom_y_range: axish[0].GetYaxis().SetRangeUser(y_axis_min, y_axis_max) axish[0].GetYaxis().SetTitleOffset(0.5) axish[1].GetYaxis().SetTitleOffset(0.5) axish[0].GetYaxis().SetTitle("dN/dm_{#tau#tau} (1/GeV)") if not is2D: axish[0].GetYaxis().SetTitle("dN/dm_{#tau#tau} (1/GeV)") #axish[0].GetYaxis().SetTitle("< Events / GeV >") axish[0].GetYaxis().SetTitleOffset(1.5) axish[1].GetYaxis().SetTitleOffset(1.5) axish[0].GetXaxis().SetTitle(x_title) if not custom_y_range: axish[0].SetMaximum(extra_pad * bkghist.GetMaximum()) if not custom_y_range: if (log_y): ymin = 0.1 axish[0].SetMinimum(ymin) else: axish[0].SetMinimum(0) hist_indices = [0] for i in hist_indices: pads[i].cd() axish[i].Draw("AXIS") bkghist.SetMarkerSize(0) bkghist.SetFillColor(2001) bkghist.SetLineColor(1) bkghist.SetLineWidth(1) bkghist.SetFillColor(plot.CreateTransparentColor(12, 0.4)) bkghist.SetLineColor(0) #stack.Draw("histsame") #bkghist.Draw("e2same") #Add signal, either model dependent or independent if not args.no_signal: sighist.SetLineColor(ROOT.kRed) sighist.SetLineWidth(2) if not is2D: sighist.SetLineWidth(3) for shist in sighists: for j in range(1, shist.GetNbinsX() + 1): entry = shist.GetBinContent(j) if entry < axish[0].GetMinimum(): shist.SetBinContent(j, axish[0].GetMinimum() * 1.00001) shist_stack = shist.Clone() shist_stack.SetLineColor(ROOT.kBlack) shist_stack.SetLineWidth(1) #shist_stack.SetFillStyle(1) shist_stack.SetFillColor(ROOT.kRed) #stack.Add(shist_stack) # uncomment to add to the stack # shist.Draw("histsame][") # removing vertical lines at the borders of the pad; possible with the trick above stack.Draw("histsame") shist.Draw("histsame ][") bkghist.Draw("e2same") blind_datagraph_extra = blind_datagraph.Clone() blind_datagraph_extra.Draw("P Z 0 same") blind_datagraph.SetMarkerSize(0.) blind_datagraph.Draw("P Z 0 same") azimov_datagraph_extra = azimov_datagraph.Clone() azimov_datagraph_extra.Draw("P Z 0 same") azimov_datagraph.SetMarkerSize(0.) azimov_datagraph.Draw("P Z 0 same") axish[i].Draw("axissame") pads[0].cd() pads[0].SetTicks(1) pads[1].SetTicks(1) #Setup legend if not is2D: legend = plot.PositionedLegend(0.42, 0.33, 3, 0.02, 0.02) #def PositionedLegend(width, height, pos, offset, horizontaloffset=None): legend.SetTextSize(0.028) else: legend = PositionedLegendUnrolled(0.13, 0.5, 7, 0.02) legend.SetTextSize(0.035) legend.SetTextFont(42) legend.SetFillStyle(0) legend.AddEntry(total_datahist, "Observed", "PEl") #Drawn on legend in reverse order looks better bkg_histos.reverse() background_schemes[channel].reverse() leg_hists = [None] * len(bkg_histos) for legi, hists in enumerate(bkg_histos): legend.AddEntry(hists, background_schemes[channel][legi]['leg_text'], "f") #legend.AddEntry(bkghist,"Background uncertainty","f") bkghist.SetLineWidth(0) legend.AddEntry(bkghist, "Bkg. unc.", "f") if is2D: if not mode == 'prefit': if not args.no_signal: legend.AddEntry(sighist, "gg#phi @ 5.8 pb (m_{#phi}= 100 GeV)" % vars(), "l") else: if not args.no_signal: legend.AddEntry(sighist, "gg#phi @ 5.8 pb (m_{#phi}= 100 GeV)" % vars(), "l") else: #if not args.no_signal: legend.AddEntry(shist_stack,"gg#phi(100 GeV) @ 5.8 pb"%vars(),"f") # uncomment if showing in the stack if not args.no_signal: legend.AddEntry(sighist, "gg#phi @ 5.8 pb (m_{#phi}= 100 GeV)" % vars(), "l") legend.Draw("same") latex2 = ROOT.TLatex() latex2.SetNDC() latex2.SetTextAngle(0) latex2.SetTextColor(ROOT.kBlack) latex2.SetTextFont(42) if not is2D: #latex2.SetTextSize(0.032) #latex2.DrawLatex(0.21,0.89,"{}, {}".format(bin_label.split(',')[0], channel_label)) #latex3 = ROOT.TLatex() #latex3.SetNDC() #latex3.SetTextSize(0.032) #latex3.SetTextAngle(0) #latex3.SetTextColor(ROOT.kBlack) #latex3.SetTextFont(42) #if len(bin_label.split(','))>1: latex3.DrawLatex(0.21,0.84,"{}".format(bin_label.split(',')[1])) textsize = 0.033 #0.027 begin_left = None ypos = 0.960 if "_{" in bin_label else 0.955 latex2 = ROOT.TLatex() latex2.SetNDC() latex2.SetTextAngle(0) latex2.SetTextColor(ROOT.kBlack) latex2.SetTextSize(textsize) if begin_left == None: #begin_left = 0.145 begin_left = 0.180 latex2.SetTextFont(42) latex2.DrawLatex(begin_left, 0.960, channel_label + ', ' + bin_label) else: latex2.SetTextAlign(23) latex2.SetTextSize(0.05) latex2.DrawLatex(0.46, 0.955, "{}, {}".format(bin_label, channel_label)) if args.bOnly: #pads[0].cd() latex2.DrawLatex(0.54, 0.55, "Bkg. only fit") #CMS and lumi labels plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), extra_pad if extra_pad > 0 else 0.3) extra = cms_label #extra='Preliminary' if not is2D: #DrawCMSLogo(pads[0], 'CMS', extra, 0, 0.07, -0.0, 2.0, '', 0.85, relExtraDX=0.05) cms_scale = 1.0 DrawCMSLogo(pads[0], 'CMS', extra, 11, 0.045, 0.05, 1.0, '', cms_scale) plot.DrawTitle(pads[0], lumi, 3, textSize=0.6) else: DrawCMSLogo(pads[0], 'CMS', extra, 0, 0.07, -0.0, 2.0, '', 0.6, relExtraDX=0.005) DrawTitleUnrolled(pads[0], lumi, 3, scale=0.6) #Add ratio plot if required axish[1].GetYaxis().SetTitle("Obs./Exp.") if args.ratio: ratio_bkghist = plot.MakeRatioHist(bkghist, bkghist, True, False) sbhist.SetLineColor(ROOT.kRed) sbhist_alt.SetLineColor(ROOT.kBlue) sbhist.SetLineWidth(2) sbhist_alt.SetLineWidth(2) if not is2D: sbhist.SetLineWidth(3) sbhist_alt.SetLineWidth(3) bkghist_errors = bkghist.Clone() #for i in range(1,bkghist_errors.GetNbinsX()+1): bkghist_errors.SetBinContent(i,bkghist.GetBinError(i)) for i in range(1, bkghist_errors.GetNbinsX() + 1): bkghist_errors.SetBinContent(i, 1.) ratio_sighist = plot.MakeRatioHist(sbhist, bkghist, True, False) ratio_datahist_ = plot.MakeRatioHist(blind_datahist, bkghist, True, False) azimov_ratio_datahist_ = plot.MakeRatioHist(azimov_datahist, bkghist, True, False) ratio_datahist = ROOT.TGraphAsymmErrors(ratio_datahist_) azimov_ratio_datahist = ROOT.TGraphAsymmErrors(azimov_ratio_datahist_) pads[1].cd() #pads[1].SetGrid(0,1) axish[1].Draw("axis") axish[1].SetMinimum(float(args.ratio_range.split(',')[0])) axish[1].SetMaximum(float(args.ratio_range.split(',')[1])) ratio_bkghist.SetMarkerSize(0) ratio_bkghist.Draw("e2same") ratio_datahist.Draw("P Z 0 same") ratio_sighist.Draw('histsame') if args.f_bOnly: bonly_histo_file = ROOT.TFile(args.f_bOnly) bonlyhist = getHistogram(bonly_histo_file, 'TotalBkg', file_dir, mode, logx=log_x)[0] bonlyhist.Scale(1, "width") bonlyhist.SetLineColor(ROOT.kBlue) bonlyhist.SetLineWidth(2) bonlyhist.SetLineStyle(2) ratio_bonlyhist = plot.MakeRatioHist(bonlyhist, bkghist, True, False) ratio_bonlyhist.Draw("histsame") pads[0].cd() legend.AddEntry(bonlyhist, 'Bkg. only fit', 'l') legend.Draw() #bonlyhist.Draw('histsame') bonlyhist.SetMarkerSize(0) bonlyhist.Draw('lsame') stack.Draw("histsame") shist.Draw("histsame ][") bkghist.Draw("e2same") blind_datagraph.SetMarkerSize(1) blind_datagraph.Draw("P Z 0 same") pads[1].cd() if args.manual_blind: azimov_ratio_datahist.Draw("P Z 0 same") pads[1].RedrawAxis("G") if is2D: rlegend = ROOT.TLegend(0.85, 0.27, 0.98, 0.16, '', 'NBNDC') rlegend.SetTextFont(42) rlegend.SetTextSize(0.035) rlegend.SetFillStyle(0) rlegend.AddEntry(ratio_datahist, "Obs./Exp.", "PE") rlegend.AddEntry("", " ", "") #rlegend.AddEntry(ratio_sighist,"(Sig.+Bkg.)/Bkg.","L") #rlegend.Draw("same") # Draw extra axis for explanation (use "N" for no optimisation) if is2D: extra_axis = ROOT.TGaxis(0, -0.03, 30., -0.03, 0., 300., 403, "NS") extra_axis.SetLabelSize(0.03) extra_axis.SetLabelFont(42) extra_axis.SetMaxDigits(3) extra_axis.SetTitle("m_{#tau#tau} (GeV)") extra_axis.SetTitleFont(42) extra_axis.SetTitleSize(0.035) extra_axis.SetTitleOffset(1.1) extra_axis.SetTickSize(0.08) extra_axis.Draw() pads[0].cd() pads[0].GetFrame().Draw() pads[0].RedrawAxis() ## Add lines after every Nxbins #line = ROOT.TLine() #line.SetLineWidth(2) #line.SetLineStyle(3) #line.SetLineColor(1) #x = bkghist.GetNbinsX()/Nxbins #x_min=bkghist.GetXaxis().GetBinLowEdge(1) #x_max=bkghist.GetXaxis().GetBinLowEdge(bkghist.GetNbinsX()+1) #x_range=x_max-x_min ## for now we have to hard code x=4 otherwise we have issues when the auto rebinning has been used #x=4 #if is2D: # for l in range(1,x): # pads[0].cd() # ymax = axish[0].GetMaximum() # ymin = axish[0].GetMinimum() # line.DrawLine(l*x_range/x,ymin,l*x_range/x,ymax) # if args.ratio: # pads[1].cd() # ymax = axish[1].GetMaximum() # ymin = axish[1].GetMinimum() # line.DrawLine(l*x_range/x,ymin,l*x_range/x,ymax) ## Add bin labels between lines pads[0].cd() latex_bin = ROOT.TLatex() latex_bin.SetNDC() latex_bin.SetTextAngle(0) latex_bin.SetTextColor(ROOT.kBlack) latex_bin.SetTextFont(42) latex_bin.SetTextSize(0.035) if len(y_bin_labels) > 6 or ('_2_' in file_dir and len(y_bin_labels) > 5): latex_bin.SetTextSize(0.027) for i in range(0, len(y_bin_labels)): if i < len(y_bin_labels) - 1: y_bin_label = "{} #leq {} < {} {}".format(y_bin_labels[i], y_bin_var, y_bin_labels[i + 1], "GeV") l = ROOT.gPad.GetLeftMargin() r = ROOT.gPad.GetRightMargin() #xshift = ((1-r-l)/(axish[0].GetNbinsX()/Nxbins))*i + l # have to hard code 4 here other wise we have problems when the autorebinning has been used xshift = ((1 - r - l) / (4)) * i + l latex_bin.DrawLatex(xshift + 0.02, 0.82, y_bin_label) else: #xshift = ((1-r-l)/(axish[0].GetNbinsX()/Nxbins))*i + l # have to hard code 4 here other wise we have problems when the autorebinning has been used xshift = ((1 - r - l) / (4)) * i + l y_bin_label = "{} > {} {}".format(y_bin_var, y_bin_labels[i], "GeV") latex_bin.DrawLatex(xshift + 0.02, 0.82, y_bin_label) #Save as png and pdf with some semi sensible filename shape_file_name = shape_file_name.replace(".root", "_%(mode)s" % vars()) shape_file_name = shape_file_name.replace("_shapes", "") outname += shape_file_name + "_" + file_dir.strip("htt").strip("_") if (log_x): outname += "_logx" c2.SaveAs("plots/%(outname)s.pdf" % vars()) del c2 histo_file.Close()
h.Add(getHistogram(histo_file, k, mode)[0]) h.SetFillColor(t['colour']) h.SetLineColor(ROOT.kBlack) h.SetMarkerSize(0) bkg_histos.append(h) stack = ROOT.THStack("hs", "") for hists in bkg_histos: stack.Add(hists) #Setup style related things plot.ModTDRStyle(r=0.06, l=0.12) c2 = ROOT.TCanvas() c2.cd() if args.ratio: pads = plot.TwoPadSplit(0.29, 0.005, 0.005) else: pads = plot.OnePad() pads[0].cd() if (log_y): pads[0].SetLogy(1) if (log_x): pads[0].SetLogx(1) if args.ratio: if (log_x): pads[1].SetLogx(1) axish = createAxisHists(2, bkghist, bkghist.GetXaxis().GetXmin(), bkghist.GetXaxis().GetXmax()) axish[1].GetXaxis().SetTitle("Visible mass (GeV)") axish[1].GetYaxis().SetNdivisions(4) axish[1].GetYaxis().SetTitle("Obs/Exp") axish[0].GetXaxis().SetTitleSize(0) axish[0].GetXaxis().SetLabelSize(0)
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')
tmp = ROOT.TFile(filesin[0], "r") h = tmp.Get("mm_1jet_zpt_loose").Get("VV") nbins = h.GetXaxis().GetNbins() for ibin in range(0, nbins + 1): h.SetBinContent(ibin, 0) h.SetBinError(ibin, 0) ncat = 4 nch = 2 nfiles = 9 width = [0.3, 0.2] pos = [3, 4] c2 = ROOT.TCanvas() c2.cd() plot.ModTDRStyle(r=0.06, l=0.12) pads = plot.TwoPadSplit(0.29, 0.010, 0.035) for f in range(0, nfiles): file = ROOT.TFile("../outputs_mt_EB/" + files[f], "r") for i in range(0, ncat): Data = file.Get(categories[i]).Get("data_obs") if (file.Get(categories[i]).GetListOfKeys().Contains("W")): W = file.Get(categories[i]).Get("W") else: W = h.Clone() if (file.Get(categories[i]).GetListOfKeys().Contains("QCD")): QCD = file.Get(categories[i]).Get("QCD") else: QCD = h.Clone() VV = file.Get(categories[i]).Get("VV")
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')
k1_res = json.load(jsonfile)[args.kappa_results.split(':')[1]] masses = args.masses.split(',') mass_dict = {} for m in masses: particle = m.split(':')[0] mass = float(m.split(':')[1]) mass_dict[particle] = mass kappa_graph = ROOT.TGraphAsymmErrors(len(k1_res.keys())) kappa_graph_fix = ROOT.TGraphAsymmErrors(1) split = args.ratio canv = ROOT.TCanvas(args.output, args.output) pads = pads = plot.TwoPadSplit(0.30, 0.006, 0.006) if split else plot.OnePad() haxis = plot.CreateAxisHist(c68, True) haxis.GetXaxis().SetTitle('Particle mass [GeV]') haxis.GetYaxis().SetTitle('#kappa_{F}#frac{m_{F}}{v} or #sqrt{#kappa_{V}}#frac{m_{V}}{v}') haxis.GetYaxis().SetTitleOffset(haxis.GetYaxis().GetTitleOffset()* 0.9) haxis.SetMinimum(7E-5) pads[0].SetLogx(True) pads[0].SetLogy(True) pads[0].cd() pads[0].SetTickx(True) pads[0].SetTicky(True) if args.x_range is not None: haxis.GetXaxis().SetLimits(float(args.x_range.split(',')[0]),float(args.x_range.split(',')[1])) if args.y_range is not None: haxis.SetMinimum(float(args.y_range.split(',')[0]))
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 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))