plot.Set(gr, LineColor=0, FillColor=ROOT.kWhite, FillStyle=1001) if args.hist is not None: plot.Set(gr, LineColor=ROOT.kGray + 0, LineWidth=2) gr.Draw(fillstyle) if 'exp0' in contours: for i, gr in enumerate(contours['exp0']): if args.hist is not None: plot.Set(gr, LineWidth=2) if 'obs' in contours: plot.Set(gr, LineColor=ROOT.kBlack, LineStyle=2) gr.Draw('LSAME') else: plot.Set(gr, LineStyle=2, FillStyle=1001, FillColor=plot.CreateTransparentColor( ROOT.kSpring + 6, 0.5)) gr.Draw(fillstyle) gr.Draw('LSAME') if 'obs' in contours: for i, gr in enumerate(contours['obs']): plot.Set(gr, FillStyle=1001, FillColor=plot.CreateTransparentColor(ROOT.kAzure + 6, 0.5)) if args.hist is not None: plot.Set(gr, LineWidth=2) gr.Draw(fillstyle) gr.Draw('LSAME') # We just want the top pad to look like a box, so set all the text and tick # sizes to zero pads[0].cd()
plot.Set(h_impacts.GetXaxis(), LabelSize=0.03, TitleSize=0.04, Ndivisions=505, Title= # '#Delta#hat{%s}' % (Translate(POIs[selectedPOI], translate))) '#Delta#hat{%s}' % (Translate("m_{ t}", translate))) plot.Set(h_impacts.GetYaxis(), LabelSize=0, TickLength=0.0) h_impacts.Draw() # Back to the first pad to draw the pulls graph pads[0].cd() plot.Set(g_pulls, MarkerSize=0.8, LineWidth=2) #plot.Set(g_pulls, MarkerSize=1.5, LineWidth=1) g_pulls.Draw('PSAME') # And back to the second pad to draw the impacts graphs pads[1].cd() alpha = 0.7 if args.transparent else 1.0 g_impacts_hi.SetFillColor(plot.CreateTransparentColor(46, alpha)) g_impacts_hi.Draw('2SAME') g_impacts_lo.SetFillColor(plot.CreateTransparentColor(38, alpha)) g_impacts_lo.Draw('2SAME') g_impacts_hi_overdrawn.SetFillColor(plot.CreateTransparentColor(46, alpha)) g_impacts_hi_overdrawn.Draw("2SAME") pads[1].RedrawAxis() legend = ROOT.TLegend(0.02, 0.02, 0.40, 0.06, '', 'NBNDC') legend.SetNColumns(3) legend.AddEntry(g_pulls, 'Pull', 'LP') legend.AddEntry(g_impacts_hi, '+1#sigma Impact', 'F') legend.AddEntry(g_impacts_lo, '-1#sigma Impact', 'F') legend.Draw() if args.color_groups 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
data_Z_pt.SetMarkerColor(ROOT.kBlack) LOMC_Z_mass = ROOT.TH1F("LOMC_Z_mass", "LOMC_Z_mass", 60, 60, 120) LOMC_Z_mass.SetMarkerSize(0) LOMC_Z_mass.Sumw2() #intree_DYMC.Draw("pt_1>>LOMC_Z_mass","(trg_1||trg_2)*(wt_pu)") #intree_DYMC.Draw("m_ll>>LOMC_Z_mass","((trg_1||trg_2)&&dr_ll>0.5)*(wt_pu)") intree_DYMC.Draw( "m_ll>>LOMC_Z_mass", "((trg_1||trg_2)&&dr_ll>0.5)*(wt_pu*wt_1*wt_2*wt_trg*gen_wt)") LOMC_Z_mass.Scale(6225.42 * 41519.180032466 / LOMC_counter.GetBinContent(2)) LOMC_Z_mass.SetFillStyle(1001) LOMC_Z_mass.SetFillColor(ROOT.TColor.GetColor(100, 192, 232)) LOMC_Z_mass.SetLineColor(ROOT.kBlack) LOMC_Z_mass_unc = LOMC_Z_mass.Clone("LOMC_Z_mass_unc") LOMC_Z_mass_unc.SetFillColor(plot.CreateTransparentColor(12, 0.4)) LOMC_Z_mass_unc.SetLineColor(0) LOMC_Z_mass_unc.SetMarkerSize(0) LOMC_Z_pt = ROOT.TH1F("LOMC_Z_pt", "LOMC_Z_pt", 60, 0, 120) LOMC_Z_pt.SetMarkerSize(0) LOMC_Z_pt.Sumw2() #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)
for ele in layout: info = ele[1] hist = Getter(file, '%s/%s' % (target, info['entries'][0]), True) plot.Set(hist, FillColor=info['color'], Title=info['legend']) if len(info['entries']) > 1: for other in info['entries'][1:]: hist.Add(Getter(file, '%s/%s' % (target, other), True)) h_store[ele[0]] = 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[0]], '', '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") h_data.Draw('E0SAME') if args.logy:
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()
def PlotTestStat(self, result, name, opts, poi_vals): null_vals = [ x * -2. for x in result.GetNullDistribution().GetSamplingDistribution() ] alt_vals = [ x * -2. for x in result.GetAltDistribution().GetSamplingDistribution() ] if len(null_vals) == 0 or len(alt_vals) == 0: print '>> Errror in PlotTestStat for %s, null and/or alt distributions are empty' return plot.ModTDRStyle() canv = ROOT.TCanvas(name, name) pad = plot.OnePad()[0] min_val = min(min(alt_vals), min(null_vals)) max_val = max(max(alt_vals), max(null_vals)) min_plot_range = min_val - 0.05 * (max_val - min_val) if opts['one_sided']: min_plot_range = 0. pad.SetLogy(True) max_plot_range = max_val + 0.05 * (max_val - min_val) hist_null = ROOT.TH1F('null', 'null', 40, min_plot_range, max_plot_range) hist_alt = ROOT.TH1F('alt', 'alt', 40, min_plot_range, max_plot_range) for val in null_vals: hist_null.Fill(val) for val in alt_vals: hist_alt.Fill(val) hist_alt.SetLineColor(ROOT.TColor.GetColor(4, 4, 255)) hist_alt.SetFillColor( plot.CreateTransparentColor(ROOT.TColor.GetColor(4, 4, 255), 0.4)) hist_alt.GetXaxis().SetTitle('-2 #times ln(^{}L_{%s}/^{}L_{%s})' % (opts['alt_label'], opts['null_label'])) hist_alt.GetYaxis().SetTitle('Pseudo-experiments') hist_alt.Draw() hist_null.SetLineColor(ROOT.TColor.GetColor(252, 86, 11)) hist_null.SetFillColor( plot.CreateTransparentColor(ROOT.TColor.GetColor(254, 195, 40), 0.4)) hist_null.Draw('SAME') val_obs = result.GetTestStatisticData() * -2. obs = ROOT.TArrow(val_obs, 0, val_obs, hist_alt.GetMaximum() * 0.3, 0.05, '<-|') obs.SetLineColor(ROOT.kRed) obs.SetLineWidth(3) obs.Draw() plot.FixTopRange(pad, plot.GetPadYMax(pad), 0.25) leg = plot.PositionedLegend(0.22, 0.2, 3, 0.02) leg.AddEntry(hist_alt, opts['alt_label'], 'F') leg.AddEntry(hist_null, opts['null_label'], 'F') leg.AddEntry(obs, 'Observed', 'L') leg.Draw() plot.DrawCMSLogo(pad, 'CMS', opts['cms_subtitle'], 0, 0.15, 0.035, 1.2) pt_l = ROOT.TPaveText(0.23, 0.75, 0.33, 0.9, 'NDCNB') pt_l.AddText('Model:') pt_l.AddText('Toys:') pt_l.AddText('CLs+b:') pt_l.AddText('CLb:') pt_l.AddText('CLs:') plot.Set(pt_l, TextAlign=11, TextFont=62, BorderSize=0) pt_l.Draw() pt_r = ROOT.TPaveText(0.33, 0.75, 0.63, 0.9, 'NDCNB') pt_r.AddText('%s [%s = %.1f, %s = %.1f]' % (opts['model_label'], opts['poi_labels'][0], poi_vals[0], opts['poi_labels'][1], poi_vals[1])) pt_r.AddText( '%i (%s) + %i (%s)' % (result.GetNullDistribution().GetSize(), opts['null_label'], result.GetAltDistribution().GetSize(), opts['alt_label'])) pt_r.AddText('%.3f #pm %.3f' % (result.CLsplusb(), result.CLsplusbError())) pt_r.AddText('%.3f #pm %.3f' % (result.CLb(), result.CLbError())) pt_r.AddText('%.3f #pm %.3f' % (result.CLs(), result.CLsError())) plot.Set(pt_r, TextAlign=11, TextFont=42, BorderSize=0) pt_r.Draw() pad.GetFrame().Draw() pad.RedrawAxis() for fmt in opts['formats']: canv.SaveAs(fmt)
alpha = 0.7 lo_color = { 'default': 38, 'hesse': ROOT.kOrange - 3, 'robust': ROOT.kGreen + 1 } hi_color = { 'default': 46, 'hesse': ROOT.kBlue, 'robust': ROOT.kAzure - 5 } method = 'default' if 'method' in data and data['method'] in lo_color: method = data['method'] g_impacts_hi.SetFillColor(plot.CreateTransparentColor(hi_color[method], alpha)) g_impacts_hi.Draw('2SAME') g_impacts_lo.SetFillColor(plot.CreateTransparentColor(lo_color[method], alpha)) g_impacts_lo.Draw('2SAME') pads[1].RedrawAxis() legend = ROOT.TLegend(0.02, 0.02, 0.40, 0.06, '', 'NBNDC') legend.SetNColumns(3) legend.AddEntry(g_pulls, 'Pull', 'LP') legend.AddEntry(g_impacts_hi, '+1#sigma Impact', 'F') legend.AddEntry(g_impacts_lo, '-1#sigma Impact', 'F') legend.Draw() leg_width = pads[0].GetLeftMargin() - 0.01 if args.color_groups is not None: legend2 = ROOT.TLegend(0.01, 0.94, leg_width, 0.99, '', 'NBNDC')
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) h.GetYaxis().SetTitle('') hr.GetYaxis().SetTitle('') if i == n_bins_phi - 1: hr.GetXaxis().SetTitle('Photon p_{T} (GeV)') plot.Set(ref_hists_1D[i], LineWidth=1, LineColor=2, MarkerSize=0, FillColor=plot.CreateTransparentColor(2, 0.2)) h_store['ref_hists_1D_%i_line' % i] = ZeroErrors(ref_hists_1D[i].Clone()) plot.Set(obs_graphs[i], LineWidth=2, MarkerSize=0.6) ref_hists_1D[i].Draw('E2SAME') print '>>> REF graph %i' % i for ig in xrange(1, ref_hists_1D[i].GetNbinsX() + 1): print '%10g %10g %10.3g %10.3g' % ( ref_hists_1D[i].GetXaxis().GetBinLowEdge(ig), ref_hists_1D[i].GetXaxis().GetBinUpEdge(ig), ref_hists_1D[i].GetBinContent(ig), ref_hists_1D[i].GetBinError(ig)) h_store['ref_hists_1D_%i_line' % i].Draw('LSAME') if i == 0: legend.AddEntry(h_obs, 'Observed', 'PE') legend.AddEntry(ref_hists_1D[i], 'MG5_aMC + PY8 (#leq1j NLO + PS)',
axish = createAxisHists(1, bkghist, bkghist.GetXaxis().GetXmin(), bkghist.GetXaxis().GetXmax()) axish[0].GetYaxis().SetTitleOffset(1.4) if custom_x_range: axish[0].GetXaxis().SetRangeUser(x_axis_min, x_axis_max) if custom_y_range: axish[0].GetYaxis().SetRangeUser(y_axis_min, y_axis_max) axish[0].GetYaxis().SetTitle("Events (1/GeV)") axish[0].GetXaxis().SetTitle("Visible mass (GeV)") axish[0].SetMaximum(extra_pad * bkghist.GetMaximum()) axish[0].SetMinimum(0.0009) axish[0].Draw() #Draw uncertainty band bkghist.SetFillColor(plot.CreateTransparentColor(12, 0.4)) bkghist.SetMarkerSize(0) stack.Draw("histsame") bkghist.Draw("e2same") blind_datahist.DrawCopy("psame") axish[0].Draw("axissame") #Setup legend legend = plot.PositionedLegend(0.30, 0.30, 3, 0.03) legend.SetTextFont(42) legend.SetTextSize(0.025) legend.SetFillColor(0) for legi, hists in enumerate(bkg_histos): legend.AddEntry(hists, background_schemes[channel][legi]['leg_text'], "f") legend.AddEntry(bkghist, "Background uncertainty", "f")
# And back to the second pad to draw the impacts graphs pads[1].cd() alpha = 0.7 lo_color = { 'default': 38, 'hesse': ROOT.kOrange - 3, 'robust': ROOT.kGreen + 1 } hi_color = {'default': 46, 'hesse': ROOT.kBlue, 'robust': ROOT.kAzure - 5} method = 'default' if 'method' in data and data['method'] in lo_color: method = data['method'] g_impacts_hi.SetFillColor( plot.CreateTransparentColor(hi_color[method], alpha)) g_impacts_hi.Draw('2SAME') g_impacts_lo.SetFillColor( plot.CreateTransparentColor(lo_color[method], alpha)) g_impacts_lo.Draw('2SAME') pads[1].RedrawAxis() legend = ROOT.TLegend(0.02, 0.02, 0.40, 0.06, '', 'NBNDC') legend.SetNColumns(3) legend.AddEntry(g_pulls, 'Pull', 'LP') legend.AddEntry(g_impacts_hi, '+1#sigma Impact', 'F') legend.AddEntry(g_impacts_lo, '-1#sigma Impact', 'F') legend.Draw() leg_width = pads[0].GetLeftMargin() - 0.01 if args.color_groups is not None:
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')
canv = ROOT.TCanvas(args.output, args.output) pads = plot.OnePad() # sb_sig.SetBinContent(17, 0.); # sb_bkg.SetBinContent(17, 0.); # sb_obs.SetBinContent(17, 0.); h_bkg.SetFillColor(18) h_sig.SetFillColor(ROOT.kRed) h_sig.SetFillStyle(3004) h_sig.SetLineColor(ROOT.kRed) h_sig_mu1.SetFillColor(ROOT.kOrange-2) h_sig_mu1.SetFillStyle(3004) h_sig_mu1.SetLineColor(ROOT.kOrange-2) new_idx = plot.CreateTransparentColor(12, 0.4) h_err.SetFillColor(new_idx) h_err.SetMarkerSize(0) h_sig_num = h_sig.Clone() h_sig_num.Add(h_bkg) h_sig_r = plot.MakeRatioHist(h_sig_num, h_bkg, False, False) blank_r = h_bkg.Clone() for i in xrange(1, blank_r.GetNbinsX()+1): blank_r.SetBinContent(i, 1.) blank_r.SetFillColor(10) blank_r.SetFillStyle(1001) h_sig_mu1_num = h_sig_mu1.Clone() h_sig_mu1_num.Add(h_bkg)
if 'exp-2' in contours and 'exp+2' in contours: for i, gr in enumerate(contours['exp+2']): plot.Set(gr, LineColor=0, FillColor=ROOT.kWhite, FillStyle=1001) if (args.hist or args.model_hist) is not None: plot.Set(gr, LineColor=ROOT.kGray + 0, LineWidth=2) gr.Draw(fillstyle) if 'exp0' in contours: for i, gr in enumerate(contours['exp0']): if (args.hist or args.model_hist) is not None: plot.Set(gr, LineWidth=2) if 'obs' in contours: plot.Set(gr, LineColor=ROOT.kBlack, LineStyle=2) gr.Draw('LSAME') else: plot.Set(gr, LineStyle=2, FillStyle=1001, FillColor=plot.CreateTransparentColor( ROOT.kSpring + 6, 0.5)) gr.Draw(fillstyle) gr.Draw('LSAME') if 'obs' in contours: for i, gr in enumerate(contours['obs']): plot.Set(gr, FillStyle=1001, FillColor=plot.CreateTransparentColor( ROOT.kAzure + 6, 0.5)) if (args.hist or args.model_hist) is not None: plot.Set(gr, LineWidth=2) gr.Draw(fillstyle) gr.Draw('LSAME') if mh122_contours is not None: for i, gr in enumerate(mh122_contours): plot.Set(gr, LineWidth=2, LineColor=ROOT.kRed,FillStyle=3004,FillColor=ROOT.kRed) gr.Draw(fillstyle)
plot.Set(h_impacts.GetYaxis(), LabelSize=0, TickLength=0.0) h_impacts.Draw() # Back to the first pad to draw the pulls graph pads[0].cd() plot.Set(g_pulls, MarkerSize=0.8, LineWidth=2) g_pulls.Draw('PSAME') plot.Set(g_pulls_e, MarkerSize=0.8, LineWidth=2) g_pulls_e.SetMarkerColor(2) g_pulls_e.SetLineColor(2) g_pulls_e.Draw('PSAME') # And back to the second pad to draw the impacts graphs pads[1].cd() alpha = 0.7 if args.transparent else 1.0 g_impacts_hi.SetFillColor(plot.CreateTransparentColor(46, alpha)) g_impacts_hi.Draw('2SAME') g_impacts_lo.SetFillColor(plot.CreateTransparentColor(38, alpha)) g_impacts_lo.Draw('2SAME') g_impacts_hi_e.SetFillColor(plot.CreateTransparentColor(5, alpha)) g_impacts_hi_e.Draw('2SAME') g_impacts_lo_e.SetFillColor(plot.CreateTransparentColor(8, alpha)) g_impacts_lo_e.Draw('2SAME') pads[1].RedrawAxis() legend = ROOT.TLegend(0.02, 0.01, 0.40, 0.06, '', 'NBNDC') legend.SetNColumns(3) legend.AddEntry(g_pulls, 'Pull exp.', 'LP') legend.AddEntry(g_impacts_hi, '+1#sigma Impact exp.', 'F') legend.AddEntry(g_impacts_lo, '-1#sigma Impact exp.', 'F') legend.AddEntry(g_pulls_e, 'Pull obs.', 'LP')
if not soverb_plot and not fractions: axish[0].GetYaxis().SetTitle(args.y_title) elif soverb_plot: axish[0].GetYaxis().SetTitle("Events") elif fractions: axish[0].GetYaxis().SetTitle("Fraction of total bkg") axish[0].GetXaxis().SetTitle(args.x_title) if not custom_y_range: axish[0].SetMaximum(extra_pad*bkghist.GetMaximum()) if not custom_y_range: if(log_y): axish[0].SetMinimum(0.0009) else: axish[0].SetMinimum(0) hist_indices = [0,2] if split_y_scale else [0] for i in hist_indices: pads[i].cd() axish[i].Draw("AXIS") #Draw uncertainty band bkghist.SetFillColor(plot.CreateTransparentColor(12,0.4)) bkghist.SetLineColor(0) bkghist.SetMarkerSize(0) stack.Draw("histsame") #Don't draw total bkgs/signal if plotting bkg fractions if not fractions and not uniform: bkghist.Draw("e2same") #Add signal, either model dependent or independent if not args.no_signal and ((split_y_scale and i == 2) or (not split_y_scale)): if model_dep is True: sighist.SetLineColor(ROOT.kGreen+3) sighist.SetLineWidth(3) # A trick to remove vertical lines for the signal histogram at the borders while preventing the lines to end in the middle of the plot. for j in range(1,sighist.GetNbinsX()+1): entry = sighist.GetBinContent(j)