def legend4Plot(plot, left = False): if left: theLeg = TLegend(0.2, 0.62, 0.55, 0.92, "", "NDC") else: theLeg = TLegend(0.60, 0.62, 0.92, 0.92, "", "NDC") theLeg.SetName('theLegend') theLeg.SetBorderSize(0) theLeg.SetLineColor(0) theLeg.SetFillColor(0) theLeg.SetFillStyle(0) theLeg.SetLineWidth(0) theLeg.SetLineStyle(0) theLeg.SetTextFont(42) theLeg.SetTextSize(.045) entryCnt = 0 for obj in range(0, int(plot.numItems())): objName = plot.nameOf(obj) if (not plot.getInvisible(objName)): theObj = plot.getObject(obj) objTitle = theObj.GetTitle() if len(objTitle) < 1: objTitle = objName dopts = plot.getDrawOptions(objName).Data() # print 'obj:',theObj,'title:',objTitle,'opts:',dopts,'type:',type(dopts) if theObj.IsA().InheritsFrom('TNamed'): theLeg.AddEntry(theObj, objTitle, dopts) entryCnt += 1 theLeg.SetY1NDC(0.9 - 0.05*entryCnt - 0.005) theLeg.SetY1(theLeg.GetY1NDC()) return theLeg
def makePlot(variable): data_var = np.array(data[variable]) data[ "totalWeight"] = data.evtWeight * data.lep1_frWeight * data.lep2_frWeight * data.lep3_frWeight * data.tau_frWeight data_weights = np.array(data['totalWeight']) data_tight_var = np.array(data_tight[variable]) data_tight[ "totalWeight"] = data_tight.evtWeight * data_tight.lep1_frWeight * data_tight.lep2_frWeight * data_tight.lep3_frWeight data_tight_weights = np.array(data_tight['totalWeight']) c1 = TCanvas() c1.SetFillColor(10) c1.SetBorderSize(2) c1.SetLeftMargin(0.12) c1.SetBottomMargin(0.12) c1.SetRightMargin(0.05) c1.SetLogy() histogram_base = TH1F("histogram_base", "", 100, np.nanmin(data_var), np.nanmax(data_var)) histogram_base.SetTitle("") histogram_base.SetStats(False) histogram_base.SetMinimum(0.001) histogram_base.SetMaximum(10.0) histogram_base.GetXaxis().SetTitle(variable) histogram_base.GetYaxis().SetTitle("Events") histogram_base.Draw("hist") hist_loose = TH1F("hist_loose", "", 100, np.nanmin(data_var), np.nanmax(data_var)) hist_tight = TH1F("hist_tight", "", 100, np.nanmin(data_var), np.nanmax(data_var)) root_numpy.fill_hist(hist_loose, data_var, weights=data_weights) root_numpy.fill_hist(hist_tight, data_tight_var, weights=data_tight_weights) hist_loose.SetLineColor(2) hist_tight.SetLineColor(4) hist_loose.SetFillColor(2) hist_tight.SetFillColor(4) hist_loose.SetFillStyle(3004) hist_tight.SetFillStyle(3005) leg = TLegend(0.2, 0.65, 0.5, 0.9) leg.SetBorderSize(0) leg.SetFillColor(10) leg.SetLineColor(0) leg.SetFillStyle(0) leg.SetTextSize(0.04) leg.SetTextFont(42) leg.AddEntry(hist_loose, "loose", "F") leg.AddEntry(hist_tight, "loose_genTau_matched", "F") hist_loose.DrawNormalized("histsame") hist_tight.DrawNormalized("histsame") leg.Draw() c1.SaveAs("plots/" + variable + "_" + process + "_loose_vs_genTau.png")
def makeNumPro(method): c = Canvas('c') c.cd() c.SetTicks(1,1) c.SetLogy() h_16 = getHist(method,['2016'],'h_num_pro') h_17 = getHist(method,['2017'],'h_num_pro') h_18 = getHist(method,['2018'],'h_num_pro') h_18.SetTitle(''), h_18.GetXaxis().SetTitle('Number Of Reconstructed Protons'), h_18.GetYaxis().SetTitle('Events') h_18.SetMarkerStyle(20), h_17.SetMarkerStyle(20), h_16.SetMarkerStyle(20) h_18.SetMarkerColor(ROOT.darkLime), h_17.SetMarkerColor(ROOT.turquois), h_16.SetMarkerColor(ROOT.orangeSoda) h_18.SetMarkerSize(1.5), h_17.SetMarkerSize(1.5), h_16.SetMarkerSize(1.5) h_18.SetLineColor(ROOT.darkLime), h_17.SetLineColor(ROOT.turquois), h_16.SetLineColor(ROOT.orangeSoda) h_18.SetLineWidth(2), h_17.SetLineWidth(2), h_16.SetLineWidth(2) h_18.SetMinimum(10000.0) h_18.Draw('p') h_17.Draw('p same') h_16.Draw('p same') c.SetGrid(0,1) legend = TLegend(0.6,0.7,0.8,0.78) legend.SetTextSize(0.03) legend.SetLineColor( 0 ) legend.SetFillColor( 0 ) legend.AddEntry(h_18,"2018",'lp') legend.AddEntry(h_17,"2017",'lp') legend.AddEntry(h_16,"2016",'lp') legend.Draw() pLabel = prelimLabel('top',True,h_18.GetMaximum()) pLabel.Draw() c.SaveAs('plots/combined/h_num_pro_%s.png' % (selection))
def produceStackedPlots(processes, selections, variables, colors, intLumi, pdir, delphesVersion, log, stacksig, hfile): print '' print 'Preparing distribution plots ...' myStyle() gROOT.SetBatch(True) intLumiab = intLumi/1e+06 yl = "Events" rt = "RECO: Delphes-{}".format(delphesVersion) lt = "#sqrt{{s}} = 100 TeV, L = {} ab^{{-1}}".format(intLumiab) ff = "png" logstr = '' if log: logstr = 'log' else: logstr = 'lin' stackstr = '' if stacksig: stackstr = 'stack' else: stackstr = 'nostack' hfile.cd() nsel = 0 for s in selections: selstr = 'sel{}'.format(int(nsel)) nsel += 1 for v in variables.keys() : histos = [] i = 0 filename = '{}_{}_{}_{}'.format(v, selstr, stackstr, logstr) leg = TLegend(0.70,0.65,0.95,0.88) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetLineColor(0) cols = [] for p in processes: hname = '{}_{}_{}'.format(p, selstr, v) h = hfile.Get(hname) hh = TH1D.Clone(h) hh.Scale(intLumi) histos.append(hh) cols.append(colors[p]) if i > 0: leg.AddEntry(hh,p,"f") else: leg.AddEntry(hh,p,"l") i+=1 drawStack(filename, yl, leg, lt, rt, ff, pdir, log, stacksig, histos, cols) print 'DONE.'
def produceNormalizedPlots(processes, selections, variables, colors, intLumi, pdir, lt, rt, log, hfile): print '' print 'Preparing normalized plots ...' gROOT.SetBatch(True) intLumiab = intLumi/1e+06 yl = "Normalized Event Rate" ff = "eps" logstr = '' if log: logstr = 'log' else: logstr = 'lin' stackstr = '' hfile.cd() nsel = 0 for s in selections: selstr = 'sel{}'.format(int(nsel)) nsel += 1 for v, dic in variables.iteritems() : histos = [] i = 0 filename = '{}_{}_{}'.format(v, selstr, logstr) leg = TLegend(0.60,0.65,0.90,0.88) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetLineColor(0) leg.SetShadowColor(10) leg.SetTextSize(0.035) leg.SetTextFont(42) cols = [] for p in processes: hname = '{}_{}_{}'.format(p, selstr, v) h = hfile.Get(hname) hh = TH1D.Clone(h) # rebin if needed hh.Rebin(int(hh.GetNbinsX()/dic['bin'])) if hh.Integral(0, hh.GetNbinsX()+1) > 0: hh.Scale(1./hh.Integral(0, hh.GetNbinsX()+1)) histos.append(hh) cols.append(colors[p]) leg.AddEntry(hh,p,"l") i+=1 drawNormalized(filename, yl, leg, lt, rt, ff, pdir, log, histos, cols) print 'DONE.'
def draw_error_hist(histogram, hist_file, text): leg_text = text.replace('_', ' ') leg_text = leg_text.replace('Chi2', '') leg_text = leg_text.replace('Background', '') leg_text = leg_text.replace('Mu', ' #mu channel ') leg_text = leg_text.replace('Ele', ' e channel ') leg_text = leg_text.replace('BT', 'b-t') leg_text = leg_text.replace('WT', 'W-t') leg_text = leg_text.replace('TopT', 't-t') leg_text = leg_text.replace('Anti', '0 ') can = ROOT.gROOT.MakeDefCanvas() root_style() histogram.SetAxisRange(0.0, 1.79, "Y") histogram.GetXaxis().SetTitle("m_{reco} [GeV]") histogram.GetYaxis().SetTitle("SR/CR ratio") leg = TLegend(0.5, 0.7, 0.8, 0.8) leg.SetFillColor(0) leg.SetLineColor(1) leg.SetBorderSize(0) leg.SetTextFont(42) leg.SetTextSize(.05) leg.SetFillStyle(0) leg.AddEntry(histogram, leg_text) histogram.Draw() leg.Draw() can.Print(hist_file)
def plot_data_vs_refold(args, regularisation_settings, tau): ''' Plot the differences between the unfolded and refolded distributions TODO Include also with best tau - redo unfolding with best tau then come here ''' from ROOT import gStyle variable = regularisation_settings.variable channel = regularisation_settings.channel plot_outpath = regularisation_settings.outpath.replace('tables/', 'plots/')+'tauscan/taus/' make_folder_if_not_exists(plot_outpath) # tau as string name for output tau = str(tau).replace('.', 'p') outfile = plot_outpath+'data_vs_refold_'+channel+'_'+variable+'_tau_'+tau+'.pdf' if args.run_measured_as_data: outfile = plot_outpath+'measured_vs_refold_'+channel+'_'+variable+'_tau_'+tau+'.pdf' if args.run_smeared_measured_as_data: outfile = plot_outpath+'smeared_vs_refold_'+channel+'_'+variable+'_tau_'+tau+'.pdf' if args.unfolded_binning: outfile = outfile.replace('.pdf', '_unf_binning.pdf') c = TCanvas('c1','c1',1000,800) gStyle.SetOptStat(0) p1 = TPad("pad1", "p1",0.0,0.2,1.0,1.0,21) p1.SetFillColor(0); p1.Draw() p2 = TPad("pad2", "p2",0.0,0.0,1.0,0.2,22) p2.SetFillColor(0); p2.Draw() p1.cd() regularisation_settings.h_data.SetTitle("Data vs Refolded Data;;NEvents") regularisation_settings.h_data.Draw() regularisation_settings.h_refolded.SetLineColor(2) regularisation_settings.h_refolded.Draw("same") leg1 = TLegend(0.7, 0.8, 0.9, 0.9) leg1.SetLineColor(0) leg1.SetFillColor(0) leg1.AddEntry(regularisation_settings.h_data, "Data") leg1.AddEntry(regularisation_settings.h_refolded, "Refolded Data") leg1.Draw() p2.cd() h_ratio = regularisation_settings.h_data.Clone() h_ratio.Divide(regularisation_settings.h_refolded) h_ratio.SetTitle(";"+variable+";") h_ratio.SetLineColor(1); h_ratio.Draw() c.SaveAs(outfile) c.Delete() print "Written plots to {outfile}".format(outfile = outfile) return
def draw_nice_legend(x=[0.7, 0.92], y=[0.7, 0.92], tit="", columns=1): global nice_legends leg = TLegend(x[0], y[0], x[1], y[1], tit) leg.SetLineColor(0) leg.SetNColumns(columns) nice_legends.append(leg) leg.Draw() return leg
def produceNormalizedPlots(processes, selections, variables, colors, intLumi, pdir, delphesVersion, log, hfile): print '' print 'Preparing normalized plots ...' myStyle() gROOT.SetBatch(True) intLumiab = intLumi / 1e+06 yl = "Normalized Event Rate" rt = "RECO: Delphes-{}".format(delphesVersion) lt = "#sqrt{{s}} = 100 TeV, L = {} ab^{{-1}}".format(intLumiab) ff = "png" logstr = '' if log: logstr = 'log' else: logstr = 'lin' stackstr = '' hfile.cd() nsel = 0 for s in selections: selstr = 'sel{}'.format(int(nsel)) nsel += 1 for v in variables.keys(): histos = [] i = 0 filename = '{}_{}_{}'.format(v, selstr, logstr) leg = TLegend(0.60, 0.65, 0.90, 0.88) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetLineColor(0) cols = [] for p in processes: hname = '{}_{}_{}'.format(p, selstr, v) h = hfile.Get(hname) hh = TH1D.Clone(h) if hh.Integral(0, hh.GetNbinsX() + 1) > 0: hh.Scale(1. / hh.Integral(0, hh.GetNbinsX() + 1)) histos.append(hh) cols.append(colors[p]) leg.AddEntry(hh, p, "l") i += 1 drawNormalized(filename, yl, leg, lt, rt, ff, pdir, log, histos, cols) print 'DONE.'
def drawAppMVAOutputPlots(region, method, isMC): MCstr = "" if isMC: MCstr = "BsMC12" Region = region[:1].upper() + region[ 1:] #capitalize first letter for retrieving file names HistName = "ApplicationOutput" + MCstr + Region + method CvsName = "canvasMVA_" + MCstr + method + region canvas = TCanvas(CvsName, CvsName) stackBDT = THStack(HistName, HistName) histos = [] appFiles = [] canvas.Draw() # note: TMVApp file name structure: "TMVApp"+Region+method+sample+".root" # "BsMC12TMVApp"+Region+method+sample+".root" appFile = TFile(MCstr + "TMVApp" + Region + method + ".root") histo = appFile.Get("MVA_" + method).Clone(HistName) histo.Scale(1 / histo.GetEntries()) stackBDT.Add(histo) for sample in range(3): appFiles.append( TFile(MCstr + "TMVApp" + Region + method + str(sample) + ".root")) histos.append(appFiles[sample].Get("MVA_" + method).Clone("HistName" + str(sample))) histos[sample].SetLineColor(2 * sample) histos[sample].Scale(1 / histos[sample].GetEntries()) stackBDT.Add(histos[sample]) stackBDT.Draw("nostack") if isMC: applicationBDTLegend = TLegend(0.2, 0.7, 0.5, 0.9, "", "brNDC") #applicationBDTLegend.SetHeader("Bs MC "+region.split("BsMC")[1]) applicationBDTLegend.SetHeader("Bs MC " + Region) else: applicationBDTLegend = TLegend(0.55, 0.7, 0.85, 0.9, "", "brNDC") applicationBDTLegend.SetHeader(Region) applicationBDTLegend.AddEntry(histo, "Full sample", "l") applicationBDTLegend.AddEntry(histos[0], "Trained on 0, tested on 1, applied on 2", "l") applicationBDTLegend.AddEntry(histos[1], "Trained on 1, tested on 2, applied on 0", "l") applicationBDTLegend.AddEntry(histos[2], "Trained on 2, tested on 0, applied on 1", "l") applicationBDTLegend.Draw("same") applicationBDTLegend.SetFillColor(0) applicationBDTLegend.SetLineColor(0) canvas.SaveAs(figuresDir + "Application" + method + "Output_" + MCstr + region + ".pdf")
def getLegend(): legend = TLegend(0.55010112, 0.7183362, 0.70202143, 0.919833) legend.SetTextSize(0.032) legend.SetLineColor(0) legend.SetShadowColor(0) legend.SetLineStyle(1) legend.SetLineWidth(1) legend.SetFillColor(0) legend.SetFillStyle(0) legend.SetMargin(0.35) return legend
def getLegend(x1=0.70010112,y1=0.123362,x2=0.90202143,y2=0.279833): legend = TLegend(x1,y1,x2,y2) legend.SetTextSize(0.032) legend.SetLineColor(0) legend.SetShadowColor(0) legend.SetLineStyle(1) legend.SetLineWidth(1) legend.SetFillColor(0) legend.SetFillStyle(0) legend.SetMargin(0.35) return legend
def legend(title=''): lg = TLegend(0.65, 0.55, 0.95, 0.90, title) lg.SetFillColor(0) lg.SetFillStyle(0) lg.SetLineColor(0) lg.SetLineStyle(0) lg.SetBorderSize(0) lg.SetShadowColor(0) lg.SetTextFont(42) lg.SetTextSize(0.06) return lg
def myLegend(coordinate=[0.48, 0.55, 0.97, 0.87], ncol=1): co = coordinate leg = TLegend(co[0], co[1], co[2], co[3]) leg.SetNColumns(ncol) leg.SetBorderSize(0) leg.SetLineColor(1) leg.SetLineStyle(1) leg.SetLineWidth(1) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextFont(42) leg.SetTextSize(0.035) return leg
def SetLegend(coordinate_=[.15, .7, .47, .87], ncol=1): c_ = coordinate_ legend = TLegend(c_[0], c_[1], c_[2], c_[3]) legend.SetBorderSize(0) legend.SetNColumns(ncol) legend.SetLineColor(1) legend.SetLineStyle(1) legend.SetLineWidth(1) legend.SetFillColor(0) legend.SetFillStyle(0) legend.SetTextFont(42) legend.SetTextSize(0.05) return legend
def main(progname, file_name, number): myFile1 = TFile.Open("%s" % (file_name), "READ") hist1 = myFile1.Get("Data_s%s" % (number)) myFile2 = TFile.Open("%s" % (file_name), "READ") hist2 = myFile2.Get("Model_cat1_s%s" % (number)) c1 = TCanvas("c1", "fit", 1000, 4000) hist1.Sumw2() hist1.SetLineColor(ROOT.kOrange + 10) hist1.SetMarkerStyle(20) hist1.SetLineWidth(1) hist1.SetMarkerSize(0.7) hist1.SetMarkerColorAlpha(ROOT.kOrange + 10, 1) # hist1.SetFillColorAlpha(ROOT.kOrange + 10, 0.4) hist1.SetStats(False) hist2.SetLineColor(ROOT.kViolet + 10) hist2.SetLineStyle(1) hist2.Sumw2() hist2.SetMarkerStyle(20) hist2.SetMarkerSize(0.7) hist2.SetLineWidth(1) hist2.SetMarkerColorAlpha(ROOT.kViolet + 10, 1) hist2.SetStats(False) #Create pad1 pad1 = TPad("pad1", "", 0, 0, 1, 1) pad1.SetLeftMargin(0.1) pad1.SetRightMargin(0.1) pad1.SetTopMargin(0.1) pad1.SetBottomMargin(0.1) pad1.Draw() pad1.cd() hist1.Draw("E1") hist2.Draw("E1 same") #Add the legend legend = TLegend(0.65, 0.75, 0.89, 0.89) legend.AddEntry(hist1, "LHCb data", "lpe") legend.AddEntry(hist2, "AmpGen fitter", "lpe") legend.SetTextFont(133) legend.SetTextSize(30) legend.SetLineColor(0) legend.Draw() c1.SaveAs("compare%s.png" % (number))
def makeXiComp(era, sector, log): pf = TFile("output_reconstructionPlotter_2017" + era + ".root") c = Canvas('c') c.cd() c.SetTicks(1, 1) if log: c.SetLogy() #c.SetGrid(1,1) h_near = ROOT.TH1F('h_near', '', 100, 0.0, 0.3) h_far = ROOT.TH1F('h_far', '', 100, 0.0, 0.3) h_multi = ROOT.TH1F('h_multi', '', 100, 0.0, 0.3) # Add hists if sector == '45': h_near.Add(pf.Get('singleRPPlots/rp3/h_xi')) h_far.Add(pf.Get('singleRPPlots/rp23/h_xi')) h_multi.Add(pf.Get('multiRPPlots/arm0/h_xi')) elif sector == '56': h_near.Add(pf.Get('singleRPPlots/rp103/h_xi')) h_far.Add(pf.Get('singleRPPlots/rp123/h_xi')) h_multi.Add(pf.Get('multiRPPlots/arm1/h_xi')) h_far.SetLineColor(210) h_near.SetLineColor(62) h_multi.SetLineColor(207) h_far.GetYaxis().SetTitle('Events') h_far.GetYaxis().SetTitleOffset(1.5) h_far.GetXaxis().SetTitle('#xi - sector' + sector) if log: h_far.SetMaximum(h_far.GetMaximum() * 10) else: h_far.SetMaximum(h_far.GetMaximum() * 1.2) h_far.Draw('HIST') h_near.Draw('HIST same') h_multi.Draw('HIST same') legend = TLegend(0.6, 0.7, 0.8, 0.8) legend.SetTextSize(0.03) legend.SetLineColor(0) legend.SetFillColor(0) legend.AddEntry(h_near, "singleRP near", 'l') legend.AddEntry(h_far, "singleRP far", 'l') legend.AddEntry(h_multi, "multiRP", 'l') legend.Draw() pLabel, lLabel = prelimLabel('top', log, h_far.GetMaximum()), lumiLabel( False, ['2017']) pLabel.Draw(), lLabel.Draw() c.SaveAs('h_xi_comp_' + sector + '_Run2017' + era + '.pdf')
def plot_GOF(hist, obs, critical, p_value, alpha="0.05"): # canvas canv = TCanvas("canv", "canv", 600, 600) canv.SetBottomMargin(0.10) canv.SetLeftMargin(0.15) canv.SetRightMargin(0.12) # histograms hist.SetMarkerColor(0) hist.SetTitle("GOF test - toys {}".format(int(hist.GetEntries()))) hist.GetXaxis().SetTitleFont(43) hist.GetYaxis().SetTitleFont(43) hist.GetXaxis().SetTitleSize(20) hist.GetYaxis().SetTitleSize(20) hist.GetXaxis().SetTitleOffset(0.8) hist.GetYaxis().SetTitleOffset(1.5) hist.GetXaxis().SetTitle("Statistics") hist.GetYaxis().SetTitle("Probability") hist.Draw("hist") up = hist.GetMaximum() hist.GetYaxis().SetRangeUser(0, 1.2 * up) # lines c_line = TLine(critical, 0, critical, 1.2 * up) c_line.SetLineColor(2) c_line.SetLineWidth(4) c_line.SetLineStyle(2) c_line.Draw("L same") obs_line = TLine(obs, 0, obs, 1.2 * up) obs_line.SetLineColor(1) obs_line.SetLineWidth(4) obs_line.Draw("L same") # legend leg = TLegend(0.6, 0.65, .95, .95) leg.SetFillColor(0) leg.SetShadowColor(0) leg.SetLineColor(0) leg.SetTextFont(43) leg.SetTextSize(18) leg.AddEntry(c_line, "alpha = {}".format(alpha), 'L') leg.AddEntry(obs_line, "data (p-value={0:.2f})".format(p_value), 'L') leg.AddEntry(hist, "toys", "L") leg.Draw("same") # save canvas canv.SaveAs("{}.pdf".format(saveout)) canv.SaveAs("{}.png".format(saveout)) canv.SaveAs("{}.root".format(saveout)) return canv
def plot_ROC_curve(ROC_curve, file_name_portion): gStyle.SetOptStat(0) gStyle.SetLabelSize(0.03, "xy") gStyle.SetTitleSize(0.03, "xy") gStyle.SetTitleOffset(1.2, "xy") gStyle.SetPadLeftMargin(0.15) gStyle.SetPadRightMargin(0.1) gStyle.SetPadTopMargin(0.1) gStyle.SetPadBottomMargin(0.15) canvas = TCanvas("c1", "c1", 800, 800) canvas.SetTickx() canvas.SetTicky() ROC_curve.GetYaxis().SetTitle('Background rejection') ROC_curve.GetXaxis().SetTitle('Signal efficiency') ROC_curve.SetLineColor(TColor.kAzure) ROC_curve.SetFillColor(TColor.kAzure - 2) ROC_curve.SetLineWidth(2) ROC_curve.SetFillStyle(0) from array import array x, y = array('d'), array('d') x.append(EFF_SIGNAL_DIRECT_CUT) y.append(1 - EFF_BACKGROUND_DIRECT_CUT) dot = TGraph(1, x, y) dot.SetMarkerColor(8) dot.SetMarkerSize(3) dot.SetMarkerStyle(21) legend = TLegend(0.2, 0.2, 0.4, 0.4) legend.SetTextSize(0.04) legend.SetTextFont(42) legend.SetFillColor(10) legend.SetLineColor(10) legend.SetBorderSize(0) legend.AddEntry(ROC_curve, "BDT 500 trees", "l") legend.AddEntry(dot, "m_{jj} > 500 GeV and |#Delta#eta_{jj}| > 3 cut", "P") ROC_curve.Draw("HIST") legend.Draw("same") dot.Draw("LPsame") canvas.RedrawAxis() canvas.Print(file_name_portion + "_ROC" + ".png")
def makeXiComp(sector,log): sec = 'p' if sector == '45' else 'm' c = Canvas('c') c.cd() c.SetTicks(1,1) if log: c.SetLogy() #c.SetGrid(1,1) h_near = ROOT.TH1F('h_near', '', 100, 0.0, 0.2) h_far = ROOT.TH1F('h_far', '', 100, 0.0, 0.2) h_multi = ROOT.TH1F('h_multi', '', 100, 0.0, 0.2) # Add hists for year in years: for pf in protonFiles: if year == pf[0]: pf_single, pf_multi = pf[1], pf[2] h_near.Add( pf_single.Get('plots/h_pro_xi_'+sector+'n') ) h_far.Add( pf_single.Get('plots/h_pro_xi_'+sector+'f') ) h_multi.Add( pf_multi.Get('plots/h_pro_xi'+sec) ) h_far.SetLineColor(210) #h_far.Rebin(2) h_near.SetLineColor(62) #h_near.Rebin(2) h_multi.SetLineColor(207) #h_multi.Rebin(2) h_far.GetYaxis().SetTitle('Events') h_far.GetYaxis().SetTitleOffset(1.5) h_far.GetXaxis().SetTitle('#xi - sector'+sector) if log: h_far.SetMaximum( h_far.GetMaximum()*10 ) else: h_far.SetMaximum( h_far.GetMaximum()*1.2 ) h_far.Draw('HIST') h_near.Draw('HIST same') h_multi.Draw('HIST same') legend = TLegend(0.6,0.7,0.8,0.8) legend.SetTextSize(0.03) legend.SetLineColor( 0 ) legend.SetFillColor( 0 ) legend.AddEntry(h_near,"singleRP near",'l') legend.AddEntry(h_far,"singleRP far",'l') legend.AddEntry(h_multi,"multiRP",'l') legend.Draw() pLabel, lLabel = prelimLabel('top',log,h_far.GetMaximum()), lumiLabel(False,years) pLabel.Draw(), lLabel.Draw() c.SaveAs('plots/%s/h_xi_comp_%s_%s.pdf' % (s_years,s_years,sector))
def makeProtonSide(log): c = Canvas('c') c.cd() c.SetLeftMargin(0.15) if log: c.SetLogy() c.SetTicks(1,1) h_single = ROOT.TH1F('h_single', '', 4, 0, 4) h_multi = ROOT.TH1F('h_multi', '', 4, 0, 4) for year in years: for pf in protonFiles: if year == pf[0]: pf_single, pf_multi = pf[1], pf[2] h_single.Add( pf_single.Get('plots/h_proton_side') ) h_multi.Add( pf_multi.Get('plots/h_proton_side') ) denom = h_single.GetEntries() h_multi.Scale(1.0/denom) h_multi.GetYaxis().SetTitle('Fraction Of Events') h_multi.GetXaxis().SetBinLabel(1,'No protons'), h_multi.GetXaxis().SetBinLabel(2,'sector45 only'), h_multi.GetXaxis().SetBinLabel(3,'sector56 only'), h_multi.GetXaxis().SetBinLabel(4,'Both') h_multi.Draw('p') h_single.Scale(1.0/denom) h_single.Draw('p same') h_single.SetMarkerColor(62), h_multi.SetMarkerColor(207) h_single.SetLineColor(62), h_multi.SetLineColor(207) h_single.SetLineWidth(2), h_multi.SetLineWidth(2) h_single.SetMarkerStyle(20), h_multi.SetMarkerStyle(20) h_multi.SetMinimum(0.0), h_multi.SetMaximum( h_multi.GetMaximum()*1.5 ) h_single.SetMarkerSize(0.9), h_multi.SetMarkerSize(0.9) c.SetGrid(0,1) legend = TLegend(0.6,0.7,0.8,0.78) legend.SetTextSize(0.03) legend.SetLineColor( 0 ) legend.SetFillColor( 0 ) legend.AddEntry(h_single,"singleRP",'lp') legend.AddEntry(h_multi,"multiRP",'lp') legend.Draw() pLabel, lLabel = prelimLabel('top',log,h_single.GetMaximum()), lumiLabel(False,years) pLabel.SetMargin(0.49) pLabel.Draw(), lLabel.Draw() c.SaveAs('plots/%s/h_proton_side_%s_%s.pdf' % (s_years,selection,s_years))
for ilayer, layer in enumerate(layers): for iplot, plot in enumerate(plots): print "\nPLOT %i / %i" % ( iplot + ilayer * len(plots) + 1 , len(layers) * len(plots)) # Do TH2 histos plotname = 'h_%s_%s' % (plot, layer) if 'TH2' in plots[plot]['class']: c2.cd() legend = TLegend(0.25, 0.72, 0.80, 0.93, "") legend.SetNColumns(2) legend.SetFillColor(ROOT.kWhite) legend.SetLineColor(ROOT.kWhite) legend.SetShadowColor(ROOT.kWhite) for irun, run in enumerate(runs): for ilumisection, lumisection in enumerate(lumisections): for ibx, bx in enumerate(bxs): # for ibx, bx in enumerate(bx_list): for k in keyList: if plots[plot]['histname'] not in k: continue if layer not in k or str(run) not in k: continue # if 'LS_%i-%i_%s' % (lumisection[0], lumisection[1], layer) not in k: if '_%i-%i_%s' % (lumisection[0], lumisection[1], layer) not in k: continue if bx not in k: continue
zll_color = ROOT.TColor.GetColor(0.537, 0.494, 0.580) wjets_color = ROOT.TColor.GetColor(0.717, 0.815, 0.749) zvv_color = (kAzure + 3) syst_color = ROOT.TColor.GetColor(0.960, 0.925, 0.6) color = [ qcd_color, vh_color, diboson_color, singletop_color, ttbar_color, zll_color, wjets_color, zvv_color ] print color legend = TLegend(0.65, 0.7, 0.92, 0.89) legend.SetTextSize(0.046) legend.SetBorderSize(0) legend.SetLineColor(1) legend.SetLineStyle(1) legend.SetLineWidth(1) legend.SetFillColor(0) legend.SetFillStyle(0) legend.SetTextFont(42) legend.SetNColumns(2) i = 0 for iprocess in processes: hist_met_ = fin.Get('h_summary_' + iprocess) hist_met_.Sumw2() hist_met_.SetDirectory(0) TH1.AddDirectory(0) # gStyle.SetPalette(53) hist_met_.SetFillColor(color[i]) #hist_met_.SetLineColor(color[i])
hnames = datasamples[datasamples.keys()[mode]]["hname"][i].split("_") string0 = "%s \n" % hnames fNevt.write(string0) #print string0 printHistName = "NJet" ##if hnames[1] == printHistName : #print hnames[1], " ", hnames[2], " ", hnames[3] hs = THStack() #l = TLegend(0.30, 0.99 - 0.8 * N_bkgsamples / 20., 0.89, 0.85) l = TLegend(0.15, 0.71, 0.89, 0.87) l.SetNColumns(4) l.SetTextSize(0.05) l.SetLineColor(0) l.SetFillColor(0) h_data = datasamples[datasamples.keys()[mode]]["file"].Get( datasamples[datasamples.keys()[mode]]["hname"][i]) h_data.Add(datasamples[datasamples.keys()[mode + 1]]["file"].Get( datasamples[datasamples.keys()[mode + 1]]["hname"][j])) nbins = h_data.GetNbinsX() h_data.AddBinContent(nbins, h_data.GetBinContent(nbins + 1)) #overflow h_sub = h_data.Clone("h_sub") if QCDestimate: h_sub.SetName(hnames[0] + "_" + hnames[1] + "_" + hnames[2] + "_" + hnames[3] + "_qcd") ntotalbkg = 0
def makeLimitPlot(output, obs, exp, chan, printStats=False, obs2="", ratioLabel=""): #fileForHEPData = TFile("plots/"+output+"_forHEPData.root","RECREATE") fileObs = open(obs, 'r') fileExp = open(exp, 'r') observedx = [] observedy = [] obsLimits = {} for entry in fileObs: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in obsLimits: obsLimits[massPoint] = [] obsLimits[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits) for massPoint in sorted(obsLimits): observedx.append(massPoint) observedy.append(numpy.mean(obsLimits[massPoint])) if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits[massPoint]), " std dev: ", numpy.std( obsLimits[massPoint]), " from: ", obsLimits[massPoint] if not obs2 == "": fileObs2 = open(obs2, 'r') observedx2 = [] observedy2 = [] obsLimits2 = {} for entry in fileObs2: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in obsLimits2: obsLimits2[massPoint] = [] obsLimits2[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits2) for massPoint in sorted(obsLimits2): observedx2.append(massPoint) observedy2.append(numpy.mean(obsLimits2[massPoint])) if (numpy.std(obsLimits2[massPoint]) / numpy.mean(obsLimits2[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits2[massPoint]), " std dev: ", numpy.std( obsLimits2[massPoint] ), " from: ", obsLimits2[massPoint] limits = {} expectedx = [] expectedy = [] expected1SigLow = [] expected1SigHigh = [] expected2SigLow = [] expected2SigHigh = [] for entry in fileExp: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in limits: limits[massPoint] = [] limits[massPoint].append(limitEntry) if printStats: print "len limits:", len(limits) for massPoint in sorted(limits): limits[massPoint].sort() numLimits = len(limits[massPoint]) nrExpts = len(limits[massPoint]) medianNr = int(nrExpts * 0.5) #get indexes: upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5)) lower1Sig = int(nrExpts * (1 - 0.68) * 0.5) upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5)) lower2Sig = int(nrExpts * (1 - 0.95) * 0.5) if printStats: print massPoint, ":", limits[massPoint][lower2Sig], limits[ massPoint][lower1Sig], limits[massPoint][medianNr], limits[ massPoint][upper1Sig], limits[massPoint][upper2Sig] #fill lists: expectedx.append(massPoint) print massPoint, limits[massPoint][medianNr] expectedy.append(limits[massPoint][medianNr]) expected1SigLow.append(limits[massPoint][lower1Sig]) expected1SigHigh.append(limits[massPoint][upper1Sig]) expected2SigLow.append(limits[massPoint][lower2Sig]) expected2SigHigh.append(limits[massPoint][upper2Sig]) expX = numpy.array(expectedx) expY = numpy.array(expectedy) values2 = [] xPointsForValues2 = [] values = [] xPointsForValues = [] xPointsForErrors = [] if printStats: print "length of expectedx: ", len(expectedx) if printStats: print "length of expected1SigLow: ", len(expected1SigLow) if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh) #Here is some Voodoo via Sam: for x in range(0, len(expectedx)): values2.append(expected2SigLow[x]) xPointsForValues2.append(expectedx[x]) xPointsForErrors.append(0) for x in range(len(expectedx) - 1, 0 - 1, -1): values2.append(expected2SigHigh[x]) xPointsForValues2.append(expectedx[x]) if printStats: print "length of values2: ", len(values2) for x in range(0, len(expectedx)): values.append(expected1SigLow[x]) xPointsForValues.append(expectedx[x]) for x in range(len(expectedx) - 1, 0 - 1, -1): values.append(expected1SigHigh[x]) xPointsForValues.append(expectedx[x]) if printStats: print "length of values: ", len(values) exp2Sig = numpy.array(values2) xPoints2 = numpy.array(xPointsForValues2) exp1Sig = numpy.array(values) xPoints = numpy.array(xPointsForValues) xPointsErrors = numpy.array(xPointsForErrors) if printStats: print "xPoints2: ", xPoints2 if printStats: print "exp2Sig: ", exp2Sig if printStats: print "xPoints: ", xPoints if printStats: print "exp1Sig: ", exp1Sig GraphErr2SigForHEPData = TGraphAsymmErrors(len(expX), expX, expY, numpy.array(xPointsErrors), numpy.array(xPointsErrors), numpy.array(expected2SigLow), numpy.array(expected2SigHigh)) GraphErr1SigForHEPData = TGraphAsymmErrors(len(expX), expX, expY, numpy.array(xPointsErrors), numpy.array(xPointsErrors), numpy.array(expected1SigLow), numpy.array(expected1SigHigh)) GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig) GraphErr2Sig.SetFillColor(ROOT.kOrange) GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig) GraphErr1Sig.SetFillColor(ROOT.kGreen + 1) #cCL=TCanvas("cCL", "cCL",0,0,567,384) cCL = TCanvas("cCL", "cCL", 0, 0, 600, 450) gStyle.SetOptStat(0) gStyle.SetPadRightMargin(0.063) gStyle.SetPadLeftMargin(0.14) gStyle.SetPadBottomMargin(0.12) if not obs2 == "": plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) plotPad.Draw() ratioPad.Draw() plotPad.cd() else: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) plotPad.Draw() plotPad.cd() expX = numpy.array(expectedx) expY = numpy.array(expectedy) GraphExp = TGraph(len(expX), expX, expY) GraphExp.SetLineWidth(3) GraphExp.SetLineStyle(2) GraphExp.SetLineColor(ROOT.kBlue) obsX = numpy.array(observedx) obsY = numpy.array(observedy) if printStats: print "obsX: ", obsX if printStats: print "obsY: ", obsY if SMOOTH: smooth_obs = TGraphSmooth("normal") GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY) GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0, 0.005) else: GraphObs = TGraph(len(obsX), obsX, obsY) GraphObs.SetLineWidth(3) if not obs2 == "": ratio = [] ratiox = [] for index, val in enumerate(observedy): mass = observedx[index] foundIndex = -1 for index2, mass2 in enumerate(observedx2): if mass == mass2: foundIndex = index2 if foundIndex > 0: ratio.append(observedy2[foundIndex] / val) ratiox.append(mass) ratioA = numpy.array(ratio) ratioX = numpy.array(ratiox) obsX2 = numpy.array(observedx2) obsY2 = numpy.array(observedy2) ratioGraph = TGraph(len(ratioX), ratioX, ratioA) if printStats: print "obsX2: ", obsX2 if printStats: print "obsY2: ", obsY2 if SMOOTH: smooth_obs2 = TGraphSmooth("normal") GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2) GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear", 0, 0.005) else: GraphObs2 = TGraph(len(obsX2), obsX2, obsY2) GraphObs2.SetLineWidth(3) if SPIN2: signals = ["RS_kMpl01", "RS_kMpl005", "RS_kMpl001"] elif GUT: signals = ["ssm", "psi", "kai", "eta", "I", "S", "N"] else: signals = ["ssm", "psi"] xSecCurves = [] for signal in signals: xSecCurves.append(getXSecCurve(signal, kFacs[signal])) #xSecCurves.append(getXSecCurve(signal,kFacs[signal],massDependent=True)) #Draw the graphs: plotPad.SetLogy() DummyGraph = TH1F("DummyGraph", "", 100, 200, 5500) DummyGraph.GetXaxis().SetTitle("M [GeV]") if SPIN2: DummyGraph.GetYaxis().SetTitle( "[#sigma#upoint#font[12]{B}] G_{KK} / [#sigma#upoint#font[12]{B}] Z" ) else: DummyGraph.GetYaxis().SetTitle( "[#sigma#upoint#font[12]{B}] Z' / [#sigma#upoint#font[12]{B}] Z") # if SPIN2: # if chan=="mumu": # DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)") # elif chan=="elel": # DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)") # elif chan=="elmu": # DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)") # else: # if chan=="mumu": # DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)") # elif chan=="elel": # DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)") # elif chan=="elmu": # DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)") gStyle.SetOptStat(0) DummyGraph.GetXaxis().SetRangeUser(200, 5500) DummyGraph.SetMinimum(1e-8) DummyGraph.SetMaximum(1e-4) DummyGraph.GetXaxis().SetLabelSize(0.055) DummyGraph.GetXaxis().SetTitleSize(0.055) DummyGraph.GetXaxis().SetTitleOffset(1.05) DummyGraph.GetYaxis().SetLabelSize(0.055) DummyGraph.GetYaxis().SetTitleSize(0.055) DummyGraph.GetYaxis().SetTitleOffset(1.3) DummyGraph.Draw() if (FULL): GraphErr2Sig.Draw("F") GraphErr1Sig.Draw("F") GraphExp.Draw("lpsame") else: if obs2 == "": GraphExp.Draw("lp") if not EXPONLY: GraphObs.Draw("plsame") if not obs2 == "": GraphObs2.SetLineColor(ROOT.kRed) GraphObs2.SetLineStyle(ROOT.kDashed) GraphObs2.Draw("plsame") for curve in xSecCurves: curve.Draw("lsame") plCMS = TPaveLabel(.16, .81, .27, .88, "CMS", "NBNDC") #plCMS.SetTextSize(0.8) plCMS.SetTextAlign(12) plCMS.SetTextFont(62) plCMS.SetFillColor(0) plCMS.SetFillStyle(0) plCMS.SetBorderSize(0) plCMS.Draw() plPrelim = TPaveLabel(.16, .76, .27, .82, "Preliminary", "NBNDC") plPrelim.SetTextSize(0.6) plPrelim.SetTextAlign(12) plPrelim.SetTextFont(52) plPrelim.SetFillColor(0) plPrelim.SetFillStyle(0) plPrelim.SetBorderSize(0) if "2017" in output or "Combination" in output: plPrelim.Draw() cCL.SetTickx(1) cCL.SetTicky(1) cCL.RedrawAxis() cCL.Update() #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC") #leg=TLegend(0.540517,0.623051,0.834885,0.878644,"","brNDC") Default leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC") if SPIN2: leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC") # leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC") leg.SetTextSize(0.0425) if not obs2 == "": if ratioLabel == "": ratioLabel = "Variant/Default" ratioLabels = ratioLabel.split("/") print ratioLabels leg.AddEntry(GraphObs, "%s Obs. 95%% CL limit" % ratioLabels[1], "l") leg.AddEntry(GraphObs2, "%s Obs. 95%% CL limit" % ratioLabels[0], "l") else: if not EXPONLY: leg.AddEntry(GraphObs, "Obs. 95% CL limit", "l") leg.AddEntry(GraphExp, "Exp. 95% CL limit, median", "l") if (FULL): leg.AddEntry(GraphErr1Sig, "Exp. (68%)", "f") leg.AddEntry(GraphErr2Sig, "Exp. (95%)", "f") leg1 = TLegend(0.7, 0.4, 0.9, 0.55, "", "brNDC") leg1.SetTextSize(0.05) if GUT: leg1 = TLegend(0.6, 0.35, 0.75, 0.623051, "", "brNDC") if SPIN2: leg1 = TLegend(0.7, 0.35, 0.9, 0.58, "G_{KK} (LO x 1.6)", "brNDC") leg1.SetTextSize(0.045) for index, signal in enumerate(signals): xSecCurves[index].SetName(labels[signal]) xSecCurves[index].Write(labels[signal]) leg1.AddEntry(xSecCurves[index], labels[signal], "l") leg1.SetBorderSize(0) leg.SetLineWidth(0) leg.SetLineStyle(0) leg.SetFillStyle(0) leg.SetLineColor(0) leg.Draw("hist") leg1.SetLineWidth(0) leg1.SetLineStyle(0) leg1.SetFillStyle(0) leg1.SetLineColor(0) leg1.Draw("hist") if "Moriond" in output: if (chan == "mumu"): plLumi = TPaveLabel(.65, .885, .9, .99, "36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .885, .9, .99, "35.9 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .27, .885, .9, .99, "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})", "NBNDC") elif "2017" in output or "Combination" in output: if (chan == "mumu"): plLumi = TPaveLabel(.65, .885, .9, .99, "42.4 fb^{-1} (13 TeV, #mu^{+}#mu^{-})", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .885, .9, .99, "41.4 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .27, .885, .9, .99, "77.3 fb^{-1} (13 TeV, ee) + 78.7 fb^{-1} (13 TeV, #mu^{+}#mu^{-})", "NBNDC") else: if (chan == "mumu"): plLumi = TPaveLabel(.65, .905, .9, .99, "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .4, .905, .9, .99, "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") plLumi.SetTextSize(0.5) plLumi.SetTextFont(42) plLumi.SetFillColor(0) plLumi.SetBorderSize(0) plLumi.Draw() plotPad.SetTicks(1, 1) plotPad.RedrawAxis() if not obs2 == "": ratioPad.cd() line = ROOT.TLine(200, 1, 5500, 1) line.SetLineStyle(ROOT.kDashed) ROOT.gStyle.SetTitleSize(0.12, "Y") ROOT.gStyle.SetTitleYOffset(0.35) ROOT.gStyle.SetNdivisions(000, "Y") ROOT.gStyle.SetNdivisions(408, "Y") ratioPad.DrawFrame(200, 0.8, 5500, 1.2, "; ; %s" % ratioLabel) line.Draw("same") ratioGraph.Draw("sameP") #GraphErr2SigForHEPData.SetName("graph2Sig") #GraphErr2SigForHEPData.Write("graph2Sig") #GraphErr1SigForHEPData.SetName("graph1Sig") #GraphErr1SigForHEPData.Write("graph1Sig") #GraphExp.SetName("graphExp") #GraphExp.Write("graphExp") #GraphObs.SetName("graphObs") #GraphObs.Write("graphObs") #fileForHEPData.Write() #fileForHEPData.Close() cCL.Update() printPlots(cCL, output)
format = "png" outputDirectory = "plots" if not os.path.exists(outputDirectory) : os.system("mkdir "+outputDirectory) for var in Vars.keys() : dict_histoS[var].SetLineWidth(3) dict_histoS[var].SetLineWidth(3) dict_histoB[var].SetLineColor(ROOT.kRed) try : dict_histoS[var].Scale(1./float(dict_histoS[var].Integral())) dict_histoB[var].Scale(1./float(dict_histoB[var].Integral())) except ZeroDivisionError : print "Can not renormalize because of integral = 0." leg = TLegend(0.50,0.76,0.89,0.89) leg.AddEntry(dict_histoS[var],"p p #rightarrow H #rightarrow 4l","l") leg.AddEntry(dict_histoB[var],"p p #rightarrow ZZ / Z #gamma^{*} #rightarrow 4l","l") leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetLineColor(0) drawDoublehisto(dict_histoS[var],dict_histoB[var],var,yAxisLabel,leg,leftText,rightText,format,outputDirectory,0)
def makeLimitPlot(output, obs, exp, chan, printStats=False, obs2="", ratioLabel=""): fileObs = open(obs, 'r') fileExp = open(exp, 'r') observedx = [] observedy = [] obsLimits = {} for entry in fileObs: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in obsLimits: obsLimits[massPoint] = [] obsLimits[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits) for massPoint in sorted(obsLimits): observedx.append(massPoint) observedy.append(numpy.mean(obsLimits[massPoint])) if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits[massPoint]), " std dev: ", numpy.std( obsLimits[massPoint]), " from: ", obsLimits[massPoint] if not obs2 == "": fileObs2 = open(obs2, 'r') observedx2 = [] observedy2 = [] obsLimits2 = {} for entry in fileObs2: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in obsLimits2: obsLimits2[massPoint] = [] obsLimits2[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits2) for massPoint in sorted(obsLimits2): observedx2.append(massPoint) observedy2.append(numpy.mean(obsLimits2[massPoint])) if (numpy.std(obsLimits2[massPoint]) / numpy.mean(obsLimits2[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits2[massPoint]), " std dev: ", numpy.std( obsLimits2[massPoint] ), " from: ", obsLimits2[massPoint] limits = {} expectedx = [] expectedy = [] expected1SigLow = [] expected1SigHigh = [] expected2SigLow = [] expected2SigHigh = [] for entry in fileExp: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in limits: limits[massPoint] = [] limits[massPoint].append(limitEntry) if printStats: print "len limits:", len(limits) for massPoint in sorted(limits): limits[massPoint].sort() numLimits = len(limits[massPoint]) nrExpts = len(limits[massPoint]) medianNr = int(nrExpts * 0.5) #get indexes: upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5)) lower1Sig = int(nrExpts * (1 - 0.68) * 0.5) upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5)) lower2Sig = int(nrExpts * (1 - 0.95) * 0.5) if printStats: print massPoint, ":", limits[massPoint][lower2Sig], limits[ massPoint][lower1Sig], limits[massPoint][medianNr], limits[ massPoint][upper1Sig], limits[massPoint][upper2Sig] #fill lists: expectedx.append(massPoint) expectedy.append(limits[massPoint][medianNr]) expected1SigLow.append(limits[massPoint][lower1Sig]) expected1SigHigh.append(limits[massPoint][upper1Sig]) expected2SigLow.append(limits[massPoint][lower2Sig]) expected2SigHigh.append(limits[massPoint][upper2Sig]) expX = numpy.array(expectedx) expY = numpy.array(expectedy) values2 = [] xPointsForValues2 = [] values = [] xPointsForValues = [] if printStats: print "length of expectedx: ", len(expectedx) if printStats: print "length of expected1SigLow: ", len(expected1SigLow) if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh) #Here is some Voodoo via Sam: for x in range(0, len(expectedx)): values2.append(expected2SigLow[x]) xPointsForValues2.append(expectedx[x]) for x in range(len(expectedx) - 1, 0 - 1, -1): values2.append(expected2SigHigh[x]) xPointsForValues2.append(expectedx[x]) if printStats: print "length of values2: ", len(values2) for x in range(0, len(expectedx)): values.append(expected1SigLow[x]) xPointsForValues.append(expectedx[x]) for x in range(len(expectedx) - 1, 0 - 1, -1): values.append(expected1SigHigh[x]) xPointsForValues.append(expectedx[x]) if printStats: print "length of values: ", len(values) exp2Sig = numpy.array(values2) xPoints2 = numpy.array(xPointsForValues2) exp1Sig = numpy.array(values) xPoints = numpy.array(xPointsForValues) if printStats: print "xPoints2: ", xPoints2 if printStats: print "exp2Sig: ", exp2Sig if printStats: print "xPoints: ", xPoints if printStats: print "exp1Sig: ", exp1Sig GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig) GraphErr2Sig.SetFillColor(ROOT.kYellow + 1) GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig) GraphErr1Sig.SetFillColor(ROOT.kGreen) cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500) gStyle.SetOptStat(0) if not obs2 == "": plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) plotPad.Draw() ratioPad.Draw() plotPad.cd() else: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) plotPad.Draw() plotPad.cd() expX = numpy.array(expectedx) expY = numpy.array(expectedy) GraphExp = TGraph(len(expX), expX, expY) GraphExp.SetLineWidth(3) GraphExp.SetLineStyle(2) GraphExp.SetLineColor(ROOT.kBlue) obsX = numpy.array(observedx) obsY = numpy.array(observedy) if printStats: print "obsX: ", obsX if printStats: print "obsY: ", obsY if SMOOTH: smooth_obs = TGraphSmooth("normal") GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY) GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0, 0.005) else: GraphObs = TGraph(len(obsX), obsX, obsY) GraphObs.SetLineWidth(3) if not obs2 == "": ratio = [] ratiox = [] for index, val in enumerate(observedy): mass = observedx[index] foundIndex = -1 for index2, mass2 in enumerate(observedx2): if mass == mass2: foundIndex = index2 if foundIndex > 0: ratio.append(observedy2[foundIndex] / val) ratiox.append(mass) ratioA = numpy.array(ratio) ratioX = numpy.array(ratiox) obsX2 = numpy.array(observedx2) obsY2 = numpy.array(observedy2) ratioGraph = TGraph(len(ratioX), ratioX, ratioA) if printStats: print "obsX2: ", obsX2 if printStats: print "obsY2: ", obsY2 if SMOOTH: smooth_obs2 = TGraphSmooth("normal") GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2) GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear", 0, 0.005) else: GraphObs2 = TGraph(len(obsX2), obsX2, obsY2) GraphObs2.SetLineWidth(3) smoother = TGraphSmooth("normal") smoother2 = TGraphSmooth("normal") zprimeX = [] zprimeY = [] fileZPrime = open('tools/xsec_SSM.txt', 'r') for entries in fileZPrime: entry = entries.split() zprimeX.append(float(entry[0])) zprimeY.append(float(entry[1]) * 1.3 / 1928) zpX = numpy.array(zprimeX) zpY = numpy.array(zprimeY) GraphZPrime = TGraph(481, zpX, zpY) GraphZPrimeSmooth = smoother2.SmoothSuper(GraphZPrime, "linear") GraphZPrimeSmooth.SetLineWidth(3) GraphZPrimeSmooth.SetLineColor(ROOT.kGreen + 3) GraphZPrimeSmooth.SetLineStyle(2) zprimePsiX = [] zprimePsiY = [] fileZPrimePsi = open('tools/xsec_PSI.txt', 'r') for entries in fileZPrimePsi: entry = entries.split() zprimePsiX.append(float(entry[0])) zprimePsiY.append(float(entry[1]) * 1.3 / 1928) zpPsiX = numpy.array(zprimePsiX) zpPsiY = numpy.array(zprimePsiY) GraphZPrimePsi = TGraph(481, zpPsiX, zpPsiY) GraphZPrimePsiSmooth = smoother.SmoothSuper(GraphZPrimePsi, "linear") GraphZPrimePsiSmooth.SetLineWidth(3) GraphZPrimePsiSmooth.SetLineColor(ROOT.kBlue) #Draw the graphs: plotPad.SetLogy() if "Moriond" in output: DummyGraph = TH1F("DummyGraph", "", 100, 120, 4500) else: DummyGraph = TH1F("DummyGraph", "", 100, 400, 4500) DummyGraph.GetXaxis().SetTitle("M [GeV]") if chan == "mumu": DummyGraph.GetYaxis().SetTitle( "#sigma(pp#rightarrowZ'+X#rightarrow#mu#mu+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu#mu+X)" ) elif chan == "elel": DummyGraph.GetYaxis().SetTitle( "#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)" ) elif chan == "elmu": DummyGraph.GetYaxis().SetTitle( "#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)" ) gStyle.SetOptStat(0) if "Moriond" in output: DummyGraph.GetXaxis().SetRangeUser(120, 4500) else: DummyGraph.GetXaxis().SetRangeUser(400, 4500) DummyGraph.SetMinimum(1e-8) DummyGraph.SetMaximum(4e-4) DummyGraph.GetXaxis().SetLabelSize(0.04) DummyGraph.GetXaxis().SetTitleSize(0.045) DummyGraph.GetXaxis().SetTitleOffset(1.) DummyGraph.GetYaxis().SetLabelSize(0.04) DummyGraph.GetYaxis().SetTitleSize(0.045) DummyGraph.GetYaxis().SetTitleOffset(1.) DummyGraph.Draw() if (FULL): GraphErr2Sig.Draw("F") GraphErr1Sig.Draw("F") GraphExp.Draw("lpsame") else: if obs2 == "": GraphExp.Draw("lp") GraphObs.Draw("plsame") if not obs2 == "": GraphObs2.SetLineColor(ROOT.kRed) GraphObs2.SetLineStyle(ROOT.kDashed) GraphObs2.Draw("plsame") if not SPIN2: GraphZPrimeSmooth.Draw("lsame") GraphZPrimePsiSmooth.Draw("lsame") cCL.SetTickx(1) cCL.SetTicky(1) cCL.RedrawAxis() cCL.Update() #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC") leg = TLegend(0.540517, 0.623051, 0.834885, 0.878644, "", "brNDC") # leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC") leg.SetTextSize(0.032) if not obs2 == "": if ratioLabel == "": ratioLabel = "Variant/Default" ratioLabels = ratioLabel.split("/") leg.AddEntry(GraphObs, "% Observed 95% CL limit" % ratioLabel[1], "l") leg.AddEntry(GraphObs2, "%s Observed 95% CL limit" % ratioLabel[0], "l") else: leg.AddEntry(GraphObs, "Observed 95% CL limit", "l") leg.AddEntry(GraphExp, "Expected 95% CL limit, median", "l") if (FULL): leg.AddEntry(GraphErr1Sig, "Expected 95% CL limit, 1 s.d.", "f") leg.AddEntry(GraphErr2Sig, "Expected 95% CL limit, 2 s.d.", "f") leg1 = TLegend(0.665517, 0.483051, 0.834885, 0.623051, "", "brNDC") leg1.SetTextSize(0.032) if not SPIN2: leg1.AddEntry(GraphZPrimePsiSmooth, "Z'_{#Psi} (LOx1.3)", "l") leg1.AddEntry(GraphZPrimeSmooth, "Z'_{SSM} (LOx1.3)", "l") leg.SetLineWidth(0) leg.SetLineStyle(0) leg.SetLineColor(0) leg.Draw("hist") leg1.SetLineWidth(0) leg1.SetLineStyle(0) leg1.SetLineColor(0) leg1.Draw("hist") if "Moriond" in output: if (chan == "mumu"): plLumi = TPaveLabel(.65, .905, .9, .99, "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .4, .905, .9, .99, "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") else: if (chan == "mumu"): plLumi = TPaveLabel(.65, .905, .9, .99, "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .4, .905, .9, .99, "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") plLumi.SetTextSize(0.5) plLumi.SetTextFont(42) plLumi.SetFillColor(0) plLumi.SetBorderSize(0) plLumi.Draw() plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC") #plCMS.SetTextSize(0.8) plCMS.SetTextAlign(12) plCMS.SetTextFont(62) plCMS.SetFillColor(0) plCMS.SetBorderSize(0) plCMS.Draw() plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC") plPrelim.SetTextSize(0.6) plPrelim.SetTextAlign(12) plPrelim.SetTextFont(52) plPrelim.SetFillColor(0) plPrelim.SetBorderSize(0) plPrelim.Draw() if not obs2 == "": ratioPad.cd() line = ROOT.TLine(400, 1, 4500, 1) line.SetLineStyle(ROOT.kDashed) ROOT.gStyle.SetTitleSize(0.12, "Y") ROOT.gStyle.SetTitleYOffset(0.35) ROOT.gStyle.SetNdivisions(000, "Y") ROOT.gStyle.SetNdivisions(408, "Y") ratioPad.DrawFrame(400, 0.9, 4500, 1.1, "; ; %s" % ratioLabel) line.Draw("same") ratioGraph.Draw("sameP") cCL.Update() printPlots(cCL, output)
hs.GetYaxis().SetTitleOffset(1.8) hs.GetYaxis().SetLabelFont(43) hs.GetYaxis().SetLabelSize(15) hs.GetYaxis().SetTitle("Events") gStyle.SetOptStat(0) pad1.SetLogy() # legend legend = TLegend(0.1, 0.75, 0.3, 0.9) #left alignment #legend = TLegend(0.7,0.75,0.9,0.9) #right alignment legend.AddEntry(LepBDTDATA_list[i], "Data", "p") legend.AddEntry(LepBDTMCDY_list[i], "DY MC", "f") legend.AddEntry(LepBDTMCTTbar_list[i], "t#bar{t} MC", "f") legend.SetFillColor(kWhite) legend.SetLineColor(kBlack) legend.SetTextFont(43) legend.SetTextSize(20) legend.Draw() canvas.Update() #lower plot pad canvas.cd() pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3) pad2.SetGridy() pad2.Draw() pad2.cd() #pad2 becomes the current pad #define ratio plot rp = TH1F(LepBDTDATA_list[i].Clone("rp"))
def DrawOverlap(fileVec, histVec, titleVec, legendtext, pngname, logstatus=[0, 0], xRange=[-99999, 99999, 1], text_="", x_=0.5, y_=0.5, legendloc=[0.53, 0.13, 0.93, 0.39]): gStyle.SetOptTitle(0) gStyle.SetOptStat(0) #gStyle.SetTitleOffset(1.1,"Y"); #gStyle.SetTitleOffset(0.9,"X"); gStyle.SetLineWidth(3) gStyle.SetFrameLineWidth(3) i = 0 histList_ = [] histList = [] histList1 = [] maximum = [] ## Legend legpos = legendloc leg = TLegend(legpos[0], legpos[1], legpos[2], legpos[3]) leg.SetBorderSize(0) leg.SetNColumns(2) leg.SetLineColor(1) leg.SetLineStyle(1) leg.SetLineWidth(1) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextFont(42) leg.SetTextSize(0.049) from PlotTemplates import myCanvas1D c = myCanvas1D() c.SetLogy(logstatus[1]) c.SetLogx(logstatus[0]) #c.SetBottomMargin(0.15) #c.SetLeftMargin(0.15) #c1_2 = TPad("c1_2","newpad",0.04,0.13,1,0.994) #c1_2.Draw() print("you have provided " + str(len(fileVec)) + " files and " + str(len(histVec)) + " histograms to make a overlapping plot") print "opening rootfiles" c.cd() #c1_2.SetBottomMargin(0.013) #c1_2.SetLogy(logstatus[1]) #c1_2.SetLogx(logstatus[0]) #c1_2.cd() ii = 0 inputfile = {} print str(fileVec[(len(fileVec) - 1)]) for ifile_ in range(len(fileVec)): print("opening file " + fileVec[ifile_]) inputfile[ifile_] = TFile(fileVec[ifile_]) print "fetching histograms" for ihisto_ in range(len(histVec)): print("printing histo " + str(histVec[ihisto_])) histo = inputfile[ifile_].Get(histVec[ihisto_]) #status_ = type(histo) is TGraphAsymmErrors histList.append(histo) # for ratio plot as they should nt be normalize histList1.append(histo) #print histList[ii].Integral() #histList[ii].Rebin(xRange[2]) #histList[ii].Scale(1.0/histList[ii].Integral()) maximum.append(histList[ii].GetMaximum()) maximum.sort() ii = ii + 1 print histList for ih in range(len(histList)): tt = type(histList[ih]) if logstatus[1] is 1: histList[ih].SetMaximum(100) #1.4 for log histList[ih].SetMinimum(0.00001) #1.4 for log if logstatus[1] is 0: histList[ih].SetMaximum(1.4) #1.4 for log histList[ih].SetMinimum(0.001) #1.4 for log # print "graph_status =" ,(tt is TGraphAsymmErrors) # print "hist status =", (tt is TH1D) or (tt is TH1F) if ih == 0: if tt is TGraphAsymmErrors: histList[ih].Draw("APL") if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I): histList[ih].Draw("hist") if ih > 0: #histList[ih].SetLineWidth(2) if tt is TGraphAsymmErrors: histList[ih].Draw("PL same") if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I): histList[ih].Draw("hist same") if tt is TGraphAsymmErrors: histList[ih].SetMaximum(10) histList[ih].SetMarkerColor(colors[ih]) histList[ih].SetLineColor(colors[ih]) histList[ih].SetMarkerStyle(markerStyle[ih]) histList[ih].SetMarkerSize(1) leg.AddEntry(histList[ih], legendtext[ih], "PL") if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I): histList[ih].SetLineStyle(linestyle[ih]) histList[ih].SetLineColor(colors[ih]) histList[ih].SetLineWidth(3) leg.AddEntry(histList[ih], legendtext[ih], "L") histList[ih].GetYaxis().SetTitle(titleVec[1]) histList[ih].GetYaxis().SetTitleSize(0.052) histList[ih].GetYaxis().SetTitleOffset(1.08) histList[ih].GetYaxis().SetLabelSize(.052) histList[ih].GetXaxis().SetRangeUser(xRange[0], xRange[1]) histList[ih].GetXaxis().SetLabelSize(0.052) histList[ih].GetXaxis().SetTitle(titleVec[0]) histList[ih].GetXaxis().SetLabelSize(0.052) histList[ih].GetXaxis().SetTitleSize(0.052) histList[ih].GetXaxis().SetTitleOffset(1.14) #histList[ih].GetXaxis().SetTickLength(0.07) histList[ih].GetXaxis().SetNdivisions(508) from PlotTemplates import SetCMSAxis histList[ih] = SetCMSAxis(histList[ih], 1.0, 1.15) #histList[ih].GetXaxis().SetMoreLogLabels(); #histList[ih].GetXaxis().SetNoExponent(); #histList[ih].GetTGaxis().SetMaxDigits(3); i = i + 1 ''' pt = TPaveText(0.0877181,0.9,0.9580537,0.96,"brNDC") pt.SetBorderSize(0) pt.SetTextAlign(12) pt.SetFillStyle(0) pt.SetTextFont(22) pt.SetTextSize(0.046) text = pt.AddText(0.2,0.5,"CMS Internal") ''' from PlotTemplates import drawenergy1D pt_ = drawenergy1D(False) for ipt in pt_: ipt.Draw() ''' if len(text_) >0: ltx = TLatex() ltx.SetTextFont(42) ltx.SetTextSize(0.049) #text_f = "#font[42]{Phase Scan}" ltx.DrawTextNDC(x_,y_,text_) ''' from PlotTemplates import ExtraText text_ex = ExtraText(text_, x_, y_) text_ex.Draw() ExtraText("ECAL Endcaps", 0.4, 0.85) ltx_ = TLatex() ltx_.SetTextFont(42) ltx_.SetTextSize(0.049) ltx_.DrawLatexNDC(0.32, 0.81, "L1 e-#gamma object p_{T} > 10 GeV") #text_ex.Draw() #pt = TPaveText(0.0877181,0.9,0.9580537,0.96,"brNDC") #text = pt.AddText(0.65,0.5,"Phase Scan data #sqrt{s} = 13 TeV (2018)") #pt.Draw() # t2a = TPaveText(0.0877181,0.81,0.9580537,0.89,"brNDC") # t2a.SetBorderSize(0) # t2a.SetFillStyle(0) # t2a.SetTextSize(0.040) # t2a.SetTextAlign(12) # t2a.SetTextFont(62) # histolabel1= str(fileVec[(len(fileVec)-1)]) # text1 = t2a.AddText(0.06,0.5,"CMS Internal") # t2a.Draw() leg.SetHeader("Matched TP energy") leg.Draw() # # c.cd() outputdirname = './' histname = outputdirname + pngname c.SaveAs(histname + '.png') c.SaveAs(histname + '.pdf')
class DataMCPlot(object): '''Handles a Data vs MC plot. Features a list of histograms (some of them being stacked), and several Drawing functions. ''' def __init__(self, name): self.histosDict = {} self.histos = [] self.supportHist = None self.name = name self.stack = None self.legendOn = True self.legend = None self.legendBorders = 0.17, 0.46, 0.44, 0.89 # self.lastDraw = None # self.lastDrawArgs = None self.stack = None self.nostack = None self.blindminx = None self.blindmaxx = None self.groups = {} self.axisWasSet = False def Blind(self, minx, maxx, blindStack): self.blindminx = minx self.blindmaxx = maxx if self.stack and blindStack: self.stack.Blind(minx, maxx) if self.nostack: for hist in self.nostack: hist.Blind(minx, maxx) def AddHistogram(self, name, histo, layer=0, legendLine=None): '''Add a ROOT histogram, with a given name. Histograms will be drawn by increasing layer.''' tmp = Histogram(name, histo, layer, legendLine) self.histos.append(tmp) self.histosDict[name] = tmp # tmp.AddEntry( self.legend, legendLine) def Group(self, groupName, namesToGroup, layer=None, style=None): '''Group all histos with names in namesToGroup into a single histo with name groupName. All histogram properties are taken from the first histogram in namesToGroup. See UnGroup as well ''' groupHist = None realNames = [] actualNamesInGroup = [] for name in namesToGroup: hist = self.histosDict.get(name, None) if hist is None: print 'warning, no histo with name', name continue if groupHist is None: groupHist = hist.Clone(groupName) self.histos.append(groupHist) self.histosDict[groupName] = groupHist else: groupHist.Add(hist) actualNamesInGroup.append(name) realNames.append(hist.realName) hist.on = False if groupHist: self.groups[groupName] = actualNamesInGroup groupHist.realName = ','.join(realNames) def UnGroup(self, groupName): '''Ungroup groupName, recover the histograms in the group''' group = self.groups.get(groupName, None) if group is None: print groupName, 'is not a group in this plot.' return for name in group: self.histosDict[name].on = True self.histosDict[groupName].on = False def Replace(self, name, pyhist): '''Not very elegant... should have a clone function in Histogram...''' oldh = self.histosDict.get(name, None) pythist = copy.deepcopy(pyhist) pyhist.layer = oldh.layer pyhist.stack = oldh.stack pyhist.name = oldh.name pyhist.legendLine = oldh.legendLine pyhist.SetStyle(oldh.style) pyhist.weighted.SetFillStyle(oldh.weighted.GetFillStyle()) if oldh is None: print 'histogram', name, 'does not exist, cannot replace it.' return else: index = self.histos.index(oldh) self.histosDict[name] = pyhist self.histos[index] = pyhist def _SortedHistograms(self, reverse=False): '''Returns the histogram dictionary, sorted by increasing layer, excluding histograms which are not "on". This function is used in all the Draw functions.''' byLayer = sorted(self.histos, key=attrgetter('layer')) byLayerOn = [hist for hist in byLayer if (hist.on is True)] if reverse: byLayerOn.reverse() return byLayerOn def Hist(self, histName): '''Returns an histogram. Print the DataMCPlot object to see which histograms are available.''' return self.histosDict[histName] def DrawNormalized(self, opt=''): '''All histograms are drawn as PDFs, even the stacked ones''' same = '' for hist in self._SortedHistograms(): hist.obj.DrawNormalized(same + opt) if same == '': same = 'same' self.DrawLegend() if TPad.Pad(): TPad.Pad().Update() # self.lastDraw = 'DrawNormalized' # self.lastDrawArgs = [ opt ] def Draw(self, opt=''): '''All histograms are drawn.''' same = '' self.supportHist = None for hist in self._SortedHistograms(): if self.supportHist is None: self.supportHist = hist hist.Draw(same + opt) if same == '': same = 'same' yaxis = self.supportHist.GetYaxis() yaxis.SetRangeUser(0.01, ymax(self._SortedHistograms())) self.DrawLegend() if TPad.Pad(): TPad.Pad().Update() # self.lastDraw = 'Draw' # self.lastDrawArgs = [ opt ] def CreateLegend(self, ratio=False): if self.legend is None: self.legend = TLegend(*self.legendBorders) self.legend.SetFillColor(0) self.legend.SetFillStyle(0) self.legend.SetLineColor(0) else: self.legend.Clear() hists = self._SortedHistograms(reverse=True) if ratio: hists = hists[:-1] # removing the last histo. for index, hist in enumerate(hists): hist.AddEntry(self.legend) def DrawLegend(self, ratio=False): '''Draw the legend.''' if self.legendOn: self.CreateLegend(ratio) self.legend.Draw('same') def DrawRatio(self, opt=''): '''Draw ratios : h_i / h_0. h_0 is the histogram with the smallest layer, and h_i, i>0 are the other histograms. if the DataMCPlot object contains N histograms, N-1 ratio plots will be drawn. To take another histogram as the denominator, change the layer of this histogram by doing: dataMCPlot.Hist("histName").layer = -99 ''' same = '' denom = None self.ratios = [] for hist in self._SortedHistograms(): if denom == None: denom = hist continue ratio = copy.deepcopy(hist) ratio.obj.Divide(denom.obj) ratio.obj.Draw(same) self.ratios.append(ratio) if same == '': same = 'same' self.DrawLegend(ratio=True) if TPad.Pad(): TPad.Pad().Update() # self.lastDraw = 'DrawRatio' # self.lastDrawArgs = [ opt ] def DrawDataOverMCMinus1(self, ymin=-0.5, ymax=0.5): stackedHists = [] dataHist = None for hist in self._SortedHistograms(): if hist.stack is False: dataHist = hist continue stackedHists.append(hist) self._BuildStack(stackedHists, ytitle='Data/MC') mcHist = self.stack.totalHist self.dataOverMCHist = copy.deepcopy(dataHist) self.dataOverMCHist.Add(mcHist, -1) self.dataOverMCHist.Divide(mcHist) self.dataOverMCHist.Draw() yaxis = self.dataOverMCHist.GetYaxis() yaxis.SetRangeUser(ymin, ymax) yaxis.SetTitle('Data/MC - 1') yaxis.SetNdivisions(5) fraclines = 0.2 if ymax <= 0.2 or ymin >= -0.2: fraclines = 0.1 self.DrawRatioLines(self.dataOverMCHist, fraclines, 0.) if TPad.Pad(): TPad.Pad().Update() def DrawRatioStack(self, opt='', xmin=None, xmax=None, ymin=None, ymax=None): '''Draw ratios. The stack is considered as a single histogram.''' denom = None # import pdb; pdb.set_trace() histForRatios = [] denom = None for hist in self._SortedHistograms(): if hist.stack is False: # if several unstacked histograms, the highest layer is used denom = hist continue histForRatios.append(hist) self._BuildStack(histForRatios, ytitle='MC/Data') self.stack.Divide(denom.obj) if self.blindminx and self.blindmaxx: self.stack.Blind(self.blindminx, self.blindmaxx) self.stack.Draw(opt, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax) self.ratios = [] for hist in self.nostack: if hist is denom: continue ratio = copy.deepcopy(hist) ratio.obj.Divide(denom.obj) ratio.obj.Draw('same') self.ratios.append(ratio) self.DrawLegend(ratio=True) self.DrawRatioLines(denom, 0.2, 1) if TPad.Pad(): TPad.Pad().Update() def DrawNormalizedRatioStack(self, opt='', xmin=None, xmax=None, ymin=None, ymax=None): '''Draw ratios. The stack is considered as a single histogram. All histograms are normalized before computing the ratio''' denom = None histForRatios = [] for hist in self._SortedHistograms(): # taking the first histogram (lowest layer) # as the denominator histogram. if denom == None: denom = copy.deepcopy(hist) continue # other histograms will be divided by the denominator histForRatios.append(hist) self._BuildStack(histForRatios, ytitle='MC p.d.f. / Data p.d.f.') self.stack.Normalize() denom.Normalize() self.stack.Divide(denom.weighted) self.stack.Draw(opt, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax) self.ratios = [] for hist in self.nostack: # print 'nostack ', hist ratio = copy.deepcopy(hist) ratio.Normalize() ratio.obj.Divide(denom.weighted) ratio.obj.Draw('same') self.ratios.append(ratio) self.DrawLegend(ratio=True) self.DrawRatioLines(denom, 0.2, 1) if TPad.Pad(): TPad.Pad().Update() # self.lastDraw = 'DrawNormalizedRatioStack' # self.lastDrawArgs = [ opt ] def DrawRatioLines(self, hist, frac=0.2, y0=1.): '''Draw a line at y = 1, at 1+frac, and at 1-frac. hist is used to get the x axis range.''' xmin = hist.obj.GetXaxis().GetXmin() xmax = hist.obj.GetXaxis().GetXmax() line = TLine() line.DrawLine(xmin, y0, xmax, y0) line.DrawLine(xmin, y0 + frac, xmax, y0 + frac) line.DrawLine(xmin, y0 - frac, xmax, y0 - frac) def DrawStack(self, opt='', xmin=None, xmax=None, ymin=None, ymax=None): '''Draw all histograms, some of them in a stack. if Histogram.stack is True, the histogram is put in the stack.''' self._BuildStack(self._SortedHistograms(), ytitle='Events') same = 'same' if len(self.nostack) == 0: same = '' self.supportHist = None for hist in self.nostack: hist.Draw() if not self.supportHist: self.supportHist = hist self.stack.Draw(opt + same, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax) if self.supportHist is None: self.supportHist = self.stack.totalHist if not self.axisWasSet: mxsup = self.supportHist.weighted.GetBinContent( self.supportHist.weighted.GetMaximumBin()) mxstack = self.stack.totalHist.weighted.GetBinContent( self.stack.totalHist.weighted.GetMaximumBin()) mx = max(mxsup, mxstack) if ymin is None: ymin = 0.01 if ymax is None: ymax = mx * 1.3 self.supportHist.GetYaxis().SetRangeUser(ymin, ymax) self.axisWasSet = True for hist in self.nostack: if self.blindminx: hist.Blind(self.blindminx, self.blindmaxx) hist.Draw('same') self.DrawLegend() if TPad.Pad(): TPad.Pad().Update() # self.lastDraw = 'DrawStack' # self.lastDrawArgs = [ opt ] def DrawNormalizedStack(self, opt='', xmin=None, xmax=None, ymin=0.001, ymax=None): '''Draw all histograms, some of them in a stack. if Histogram.stack is True, the histogram is put in the stack. all histograms out of the stack, and the stack itself, are shown as PDFs.''' self._BuildStack(self._SortedHistograms(), ytitle='p.d.f.') self.stack.DrawNormalized(opt, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax) for hist in self.nostack: hist.obj.DrawNormalized('same') self.DrawLegend() if TPad.Pad(): TPad.Pad().Update() # self.lastDraw = 'DrawNormalizedStack' # self.lastDrawArgs = [ opt ] def Rebin(self, factor): '''Rebin, and redraw.''' # the dispatching technique is not too pretty, # but keeping a self.lastDraw function initialized to one of the Draw functions # when calling it creates a problem in deepcopy. for hist in self.histos: hist.Rebin(factor) self.axisWasSet = False def NormalizeToBinWidth(self): '''Normalize each Histograms bin to the bin width.''' for hist in self.histos: hist.NormalizeToBinWidth() def _BuildStack(self, hists, ytitle=None): '''build a stack from a list of Histograms. The histograms for which Histogram.stack is False are put in self.nostack''' self.stack = None self.stack = Stack(self.name + '_stack', ytitle=ytitle) self.nostack = [] for hist in hists: if hist.stack: self.stack.Add(hist) else: self.nostack.append(hist) def __str__(self): if self.stack is None: self._BuildStack(self._SortedHistograms(), ytitle='Events') tmp = [' '.join(['DataMCPlot: ', self.name])] tmp.append('Histograms:') for hist in self._SortedHistograms(reverse=True): tmp.append(' '.join(['\t', str(hist)])) tmp.append( 'Stack yield = {integ:7.1f}'.format(integ=self.stack.integral)) return '\n'.join(tmp)