def trigger(nbins, low, high): # dataFile = TFile("../anaRoots/data.root","OPEN") # treeTrig = dataFile.Get("Trigger") # cutter = cuts[region] can = TCanvas("can", "can", 1000, 900) # can.SetBottomMargin(0.3) # can.SetRightMargin(0.06) gStyle.SetOptStat(0) histNumerator = TH1F('histNumerator', ";Photon p_{T} [GeV];Efficiency", nbins, low, high) treeTrig['Data'].Draw('TrigPhoton_pt>>histNumerator', '((isHLT165==1) && (isPrescaled==1))') # treeTrig['Data'].Draw('TrigPhoton_pt>>histNumerator','((isHLT165==True))') histDenominator = TH1F('histDenominator', ";Photon p_{T} [GeV];Efficiency", nbins, low, high) treeTrig['Data'].Draw('TrigPhoton_pt>>histDenominator', '(isPrescaled==1)') histNumerator.Sumw2() histDenominator.Sumw2() histNumerator.SetMaximum(1.1) print histNumerator.Integral() print histDenominator.Integral() histNumerator.Divide(histDenominator) histNumerator.Draw('e1') latex2 = TLatex() latex2.SetNDC() latex2.SetTextSize(0.035) latex2.SetTextAlign(31) # align right latex2.DrawLatex( 0.87, 0.95, "Work In Progress, " + str(lumi) + " fb^{-1} at #sqrt{s} = 13 TeV") can.SaveAs("plots/trigger.pdf") can.Close()
def __make_summary_plot(self, name, ibin2, successful): # Nominal histogram successful_tmp = copy(successful) successful_tmp.sort() filename = f"finalcross{self.case}{self.typean}mult{ibin2}.root" filepath = join(self.nominal_analyzer_merged.d_resultsallpdata, filename) nominal_histo = self.__get_histogram(filepath, name) histos = [] ml_trials = [] for succ in successful_tmp: filename = f"finalcross{self.case}{self.typean}mult{ibin2}.root" filepath = join(self.analyzers_syst[succ].d_resultsallpdata, filename) histos.append(self.__get_histogram(filepath, name)) ml_trials.append( list(map(itemgetter(self.mcopt), self.ml_wps[succ]))) nptbins = self.nominal_processer_mc.p_nptfinbins gr = [TGraphErrors(0) for _ in range(nptbins)] for ipt in range(nptbins): gr[ipt].SetTitle("pT bin %d" % ipt) gr[ipt].SetPoint(0, self.cent_cv_cut[ipt], nominal_histo.GetBinContent(ipt + 1)) gr[ipt].SetPointError(0, 0.0001, nominal_histo.GetBinError(ipt + 1)) for iml, succ in enumerate(successful_tmp): gr[ipt].SetPoint(iml + 1, ml_trials[succ][ipt], histos[succ].GetBinContent(ipt + 1)) gr[ipt].SetPointError(iml + 1, 0.0001, histos[succ].GetBinError(ipt + 1)) canvas = TCanvas("cvsml%d" % ibin2, "", 1200, 800) if len(gr) <= 6: canvas.Divide(3, 2) elif len(gr) <= 12: canvas.Divide(4, 3) else: canvas.Divide(5, 4) for i, graph in enumerate(gr): canvas.cd(i + 1) graph.Draw("a*") save_path = join(self.nominal_analyzer_merged.d_resultsallpdata, self.syst_out_dir, f"ml_wp_syst_{name}_vs_MLcut_ibin2_{ibin2}.eps") canvas.SaveAs(save_path) save_path = join(self.nominal_analyzer_merged.d_resultsallpdata, self.syst_out_dir, f"ml_wp_syst_{name}_vs_MLcut_ibin2_{ibin2}.root") file_out = TFile.Open(save_path, "RECREATE") file_out.cd() for i, graph in enumerate(gr): graph.Write("%s%d" % (graph.GetName(), i)) canvas.Write() file_out.Close() canvas.Close()
def writeHistogramsToFileTest(): print ">>> write a root file with a histogram." filein = TFile("tree.root", "read") fileout = TFile("test.root", "recreate") tree = filein.Get("dir1/tree2") hist1 = TH1D("hist1", "hist1", 100, 0, 40) tree.Draw("normal5 >> hist1") hist2 = TH1D("hist2", "hist2", 100, 0, 40) hist2.SetLineColor(kRed) tree.Draw("normal5 + 5 >> hist2") # ... canvas = TCanvas("canvas", "canvas", 100, 100, 600, 800) hist1.Draw() hist2.Draw("same") # ... canvas.SaveAs("test.png") fileout.Write() fileout.Close() canvas.Close()
def checklatex(texts, tag=""): """Check legend entries: colors, titles, ...""" # https://root.cern.ch/doc/master/classTPaveText.html LOG.header("checklegend" + tag.replace('_', ' ')) output = ensuredir('plots') fname = "%s/testLatex%s" % (output, tag) xdim = 500 ydim = 50 * (len(texts) + 2.5) print ">>> Canvas: %sx%s (nlines=%d)" % (xdim, ydim, len(texts)) canvas = TCanvas('canvas', 'canvas', xdim, int(ydim)) #pave1 = TPaveText(0.0,0,0.5,1,'ARC') #,'BR') pave2 = TPaveText(0.04, 0.04, 0.96, 0.96) #'ARC') #,'BR') #pave1.SetBorderSize(0) pave2.SetBorderSize(0) #pave1.SetTextAlign(12) pave2.SetTextAlign(12) #pave1.SetTextFont(42) pave2.SetTextFont(42) #pave1.SetFillColor(0) pave2.SetFillColor(0) #pave1.SetCornerRadius(0.05) #pave2.SetCornerRadius(0.05) #pave1.SetMargin(0.12) #pave1.SetTextSize(tsize) #pave2.Copy(pave1) for line in texts: latex = makelatex(line) print ">>> %r -> %r" % (line, latex) #pave1.AddText(line) pave2.AddText(latex) #pave1.Draw() pave2.Draw() canvas.SaveAs(fname + ".png") #canvas.SaveAs(fname+".pdf") canvas.Close()
def drawEWKNLOCorr(): filename1 = path + "merged_kfactors_zjets.root" filename2 = path + "merged_kfactors_wjets.root" histname = "kfactor_monojet_ewk" file1 = ensureTFile(filename1) file2 = ensureTFile(filename2) hist1 = file1.Get(histname) hist2 = file2.Get(histname) hist1.SetDirectory(0) hist2.SetDirectory(0) file1.Close() file2.Close() c1 = TCanvas("c1", "sf plot", 800, 600) hist1.SetTitle("EWK NLO SF") hist1.GetXaxis().SetTitle("V p_{T} (GeV)") hist1.GetYaxis().SetTitle("EWK NLO SF") hist1.GetYaxis().SetRangeUser(0.7, 1.0) hist1.SetLineColor(4) hist2.SetLineColor(2) hist1.SetLineWidth(3) hist1.SetMarkerStyle(8) hist1.SetMarkerColor(4) hist2.SetMarkerStyle(8) hist2.SetMarkerColor(2) leg = TLegend(0.7, 0.65, 0.85, 0.8) leg.AddEntry(hist1, "Z+Jets") leg.AddEntry(hist2, "W+Jets") hist1.Draw("LP HIST") hist2.Draw("LP HIST SAME") leg.Draw("SAME") gStyle.SetOptStat(0) c1.SaveAs("./plotsSF/EWKNLOCorr.pdf") c1.SaveAs("./plotsSF/EWKNLOCorr.png") c1.Close()
def plot_2(var, cuts): for s in attr: c1 = TCanvas("c1", "Signals", 800, 800) c1.cd() c1.SetGrid() #gStyle.SetTitleFontSize(8.1) if s in ('elf', 'muf', 'chm', 'cm', 'nm'): c1.SetLogx() for cc in channel: #hist[cc][s].SetMaximum(0.44) hist[cc][s].Draw('colz same') if CHS == 1: hist_CHS[cc][s].Draw('colz same') legend = TLegend(0.90, 0.90, 0.99, 0.99) #legend.SetHeader('Samples') for cc in channel: legend.AddEntry(hist[cc][s], cc) if CHS == 1: legend.AddEntry(hist_CHS[cc][s], cc + 'CHS') legend.Draw() c1.Print(path1 + s + var + cuts.replace('(', '_').replace( ')', '_').replace('&&', 'A').replace('>', 'LG').replace( '<', 'LS').replace('=', 'EQ').replace('.', 'P').replace( '-', 'N').replace('Jet', 'J').replace('GenBquark', 'GBQ') + ".pdf") c1.Update() c1.Close() print('|||||||||||||||||||||||||||||||||||||||||||||||||||')
def plot_histograms(histos, use_log_y=False, ratio=False, legend_titles=None, title="", x_label="", y_label_up="", y_label_ratio="", save_path="./plot.eps", **kwargs): """ Throws all given histograms into one canvas. If desired, a ratio plot will be added. """ linestyles = kwargs.get("linestyles", None) markerstyles = kwargs.get("markerstyles", None) colors = kwargs.get("colors", None) canvas_name = kwargs.get("canvas_name", "Canvas") style_histograms(histos, linestyles, markerstyles, colors) canvas = TCanvas('canvas', canvas_name, 800, 800) pad_up_start = 0.4 if ratio else 0. pad_up = TPad("pad_up", "", 0., pad_up_start, 1., 1.) if ratio: pad_up.SetBottomMargin(0.) pad_up.Draw() put_in_pad(pad_up, use_log_y, histos, title, "", y_label_up) pad_up.cd() legend = None if legend_titles is not None: legend = TLegend(.45, .65, .85, .85) legend.SetBorderSize(0) legend.SetFillColor(0) legend.SetFillStyle(0) legend.SetTextFont(42) legend.SetTextSize(0.02) for h, l in zip(histos, legend_titles): legend.AddEntry(h, l) legend.Draw() canvas.cd() pad_ratio = None histos_ratio = None if ratio: histos_ratio = divide_all_by_first(histos) pad_ratio = TPad("pad_ratio", "", 0., 0.05, 1., pad_up_start) pad_ratio.SetTopMargin(0.) pad_ratio.SetBottomMargin(0.3) pad_ratio.Draw() put_in_pad(pad_ratio, False, histos_ratio, "", x_label, y_label_ratio) canvas.SaveAs(save_path) canvas.Close()
def plotHist(h): colors = [633, 416 + 1, 862, 800, 921, 922, 1] n = len(h) c1 = TCanvas("c1", "Signals", 800, 600) c1.cd() #c1.GetPad(1).SetPadTopMargin(0.06) #c1.GetPad(1).SetPadRightMargin(0.05) c1.GetPad(0).SetTicky(2) for i in range(n): col = sample[ h[i].GetTitle()]['linecolor'] if n > len(colors) else colors[i] h[i].SetMarkerColor(col) h[i].SetLineColor(col) if "Counter" in h[0].GetName(): h[0].GetYaxis().SetRangeUser(0., -1) else: for i in range(n): h[i].SetMarkerStyle(20) #h[i].SetMarkerSize(1) h[i].SetLineWidth(2) ymax = 0. for i in range(n): if h[i].GetMaximum() > ymax: ymax = h[i].GetMaximum() h[0].SetMaximum(ymax * 1.2) if h[0].Integral() / h[0].GetNbinsX() < 1.: #h[0].GetYaxis().SetTitle("Efficiency") h[0].GetYaxis().SetRangeUser(0., 1.) style = "HIST" if "Counter" in h[0].GetName() or "Barrel" in h[0].GetName( ) or "Endcap" in h[0].GetName() or h[0].GetName().startswith( "Gen") else "PE1" h[0].Draw(style) for i in range(1, n): h[i].Draw("SAME, " + style) leg = TLegend(0.50, 0.55 - 0.05 * n, 0.85, 0.55) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) for i in range(n): if h[i].GetTitle() != "": if h[i].GetTitle() in sample.keys(): leg.AddEntry(h[i], sample[h[i].GetTitle()]['label'], "pl") else: leg.AddEntry(h[i], h[i].GetTitle(), "pl") leg.Draw() drawCMS(-1, "Simulation", True) c1.Print("plots/Leptons/" + h[-1].GetName() + ".png") c1.Print("plots/Leptons/" + h[-1].GetName() + ".pdf") #raw_input("Press Enter to continue...") c1.Close() return True
def draweffb(btag): upline = TGraph() downline = TGraph() if btag == '2b': eff_b = { 800: [0.961, 1.040], 1000: [0.955, 1.046], 1200: [0.944, 1.058], 1400: [0.913, 1.093], 1600: [0.889, 1.119], 1800: [0.877, 1.133], 2000: [0.873, 1.138], 2500: [0.869, 1.141], 3000: [0.868, 1.142], 3500: [0.868, 1.143], 4000: [0.868, 1.143], 4500: [0.866, 1.145], 5000: [0.862, 1.150] } else: eff_b = { 800: [1.007, 0.993], 1000: [1.009, 0.991], 1200: [1.013, 0.988], 1400: [1.025, 0.976], 1600: [1.033, 0.968], 1800: [1.038, 0.963], 2000: [1.041, 0.961], 2500: [1.050, 0.952], 3000: [1.054, 0.948], 3500: [1.057, 0.945], 4000: [1.059, 0.944], 4500: [1.061, 0.941], 5000: [1.063, 0.940] } for i, signal in enumerate(signal_list): upline.SetPoint(i, signal, eff_b[signal][1]) downline.SetPoint(i, signal, eff_b[signal][0]) c1 = TCanvas("c1", "sf plot", 800, 600) upline.SetTitle("b-tagging uncertainty %s" % btag) upline.GetXaxis().SetTitle("m_{X} (GeV)") upline.GetYaxis().SetTitle("Uncertainty") upline.GetYaxis().SetRangeUser(0.7, 1.3) upline.SetLineColor(4) downline.SetLineColor(2) upline.SetLineWidth(3) downline.SetLineWidth(3) leg = TLegend(0.7, 0.75, 0.85, 0.85) leg.AddEntry(upline, "+ 1 s. d.", "L") leg.AddEntry(downline, "- 1 s. d.", "L") upline.Draw("AC") downline.Draw("C SAME") leg.Draw("SAME") c1.SaveAs("./plotsSF/effb_%s.pdf" % btag) c1.SaveAs("./plotsSF/effb_%s.png" % btag) c1.Close()
def LoopPlotOnCanvas(pdf_name, list_histo): for idx, inst in enumerate(list_histo, 1): # inst is a class object -> inst.histo = TH1/TH2 # Open file # if idx == 1: c2 = TCanvas() c2.Print(pdf_name + '.pdf[') c2.Close() # Print each plot # inst.PlotOnCanvas(pdf_name=pdf_name + '.pdf') # Close file # if idx == len(list_histo): c2 = TCanvas() c2.Print(pdf_name + '.pdf') # Otherwise last plot does not have title c2.Print(pdf_name + '.pdf]') c2.Close() logging.info('Plots saved at %s' % (pdf_name + '.pdf'))
def drawDsPlot(ds,catNum = 0): from ROOT import RooAbsData,TCanvas etaHist = RooAbsData.createHistogram(ds,'eta',100); theCanvas = TCanvas('dsCanvas','Eta histogram (category' + str(catNum) + ')' ) etaHist.Draw("hist PFC"); theCanvas.SaveAs("etaCat"+str(catNum)+"Hist"+TIME_NOW+".pdf"); #s = raw_input("Press Enter to continue..."); theCanvas.Close();
def plotHists(hists,xtitle,plotname,header,ctexts=[ ],otext="",logy=False,y1=0.70): colors = [ kBlue, kRed, kGreen+2, kOrange, kMagenta+1 ] canvas = TCanvas('canvas','canvas',100,100,800,700) canvas.SetMargin(0.12,0.03,0.14,0.06 if otext else 0.03) textsize = 0.040 height = 1.28*(len(hists)+1)*textsize y1 legend = TLegend(0.65,y1,0.88,y1-height) legend.SetTextSize(textsize) legend.SetBorderSize(0) legend.SetFillStyle(0) legend.SetFillColor(0) legend.SetTextFont(62) legend.SetHeader(header) legend.SetTextFont(42) legend.SetMargin(0.2) latex = TLatex() latex.SetTextAlign(13) latex.SetTextFont(42) latex.SetNDC(True) frame = hists[0] frame.GetXaxis().SetTitle(xtitle) frame.GetYaxis().SetTitle("Fraction [%]") frame.GetXaxis().SetLabelSize(0.074) frame.GetYaxis().SetLabelSize(0.046) frame.GetXaxis().SetTitleSize(0.048) frame.GetYaxis().SetTitleSize(0.052) frame.GetXaxis().SetTitleOffset(1.38) frame.GetYaxis().SetTitleOffset(1.12) frame.GetXaxis().SetLabelOffset(0.009) frame.SetMaximum(1.25*max(h.GetMaximum() for h in hists)) if logy: canvas.SetLogy() frame.SetMinimum(1e-3) else: frame.SetMinimum(0) for i, hist in enumerate(hists): hist.Draw('HISTE0E1SAME') hist.SetLineWidth(2) hist.SetLineColor(colors[i%len(colors)]) legend.AddEntry(hist,hist.GetTitle(),'le') legend.Draw() for i, text in enumerate(ctexts): textsize = 0.024 #if i>0 else 0.044 latex.SetTextSize(textsize) latex.DrawLatex(0.14,0.98-canvas.GetTopMargin()-1.7*i*textsize,text) if otext: latex.SetTextSize(0.05) latex.SetTextAlign(31) latex.DrawLatex(1.-canvas.GetRightMargin(),1.-0.84*canvas.GetTopMargin(),otext) canvas.SaveAs(plotname+".png") canvas.SaveAs(plotname+".pdf") canvas.Close() for hist in hists: gDirectory.Delete(hist.GetName())
def draw2d(hist, xtitle, ytitle, number=False, nxbins=0, nybins=0): """Draw 2D histogram.""" tsize = 0.045 lines = [] xmin, xmax = hist.GetXaxis().GetXmin(), hist.GetXaxis().GetXmax() ymin, ymax = hist.GetYaxis().GetXmin(), hist.GetYaxis().GetXmax() canvas = TCanvas('canvas', 'canvas', 100, 100, 900, 800) canvas.SetMargin(0.11, 0.16, 0.10, 0.02) # LRBT canvas.SetLogz() hist.GetXaxis().SetTitle(xtitle) hist.GetYaxis().SetTitle(ytitle) hist.GetZaxis().SetTitle("Events") hist.GetXaxis().SetTitleSize(tsize) hist.GetYaxis().SetTitleSize(tsize) hist.GetZaxis().SetTitleSize(tsize) hist.GetXaxis().SetLabelSize(0.9 * tsize) hist.GetYaxis().SetLabelSize(0.9 * tsize) hist.GetZaxis().SetLabelSize(0.9 * tsize) hist.GetXaxis().SetTitleOffset(1.04) hist.GetYaxis().SetTitleOffset(1.14) hist.GetZaxis().SetTitleOffset(1.08) hist.Draw('COLZ') if number: latex = TLatex() latex.SetTextSize(0.8 * tsize) latex.SetTextAlign(22) latex.SetTextFont(62) latex.SetTextColor(kRed) for ix in range(1, hist.GetXaxis().GetNbins() + 1): x = hist.GetXaxis().GetBinCenter(ix) for iy in range(1, hist.GetYaxis().GetNbins() + 1): y = hist.GetYaxis().GetBinCenter(iy) latex.DrawLatex(x, y, str(Unroll.GetBin(x, y))) if nxbins > 0: # divide with nlines for i in range(1, nxbins): x = xmin + (xmax - xmin) * i / nxbins line = TLine(x, ymin, x, ymax) line.SetLineColor(kRed) line.SetLineStyle(kDashed) line.SetLineWidth(1) line.Draw() lines.append(line) if nybins > 0: # divide with nlines for i in range(1, nybins): y = ymin + (ymax - ymin) * i / nybins line = TLine(xmin, y, xmax, y) line.SetLineColor(kRed) line.SetLineStyle(kDashed) line.SetLineWidth(2) line.Draw() lines.append(line) canvas.RedrawAxis() canvas.SaveAs(hist.GetName() + ".png") #canvas.SaveAs(hist.GetName()+".pdf") canvas.Close()
def draw_syst(self, save_dir, results_dir, root_dir=None): """Draw all fits one-by-one Args: save_dir: directory where to save plots results_dir: where to find intermediate results of the multi trial root_dir: TDirectory where to save summary plots """ gStyle.SetOptStat(0) gStyle.SetOptStat(0000) gStyle.SetPalette(1) gStyle.SetCanvasColor(0) gStyle.SetFrameFillColor(0) bins1_ranges = self.pars_factory.bins1_edges_low.copy() bins1_ranges.append(self.pars_factory.bins1_edges_up[-1]) for (ibin1, ibin2), fit in self.syst_fits.items(): if not fit: self.logger.warning( "No systematic fit for bins (%i, %i). Skip...", ibin1, ibin2) continue bin_id_match = self.pars_factory.bin_matching[ibin1] # Some variables set for drawing title = f"{self.pars_factory.bins1_edges_low[ibin1]:.1f} < #it{{p}}_{{T}} < " \ f"{self.pars_factory.bins1_edges_up[ibin1]:.1f}" \ f"(prob > {self.pars_factory.prob_cut_fin[bin_id_match]:.2f})" suffix_write = self.pars_factory.make_suffix(ibin1, ibin2) fit.results_path = os.path.join( results_dir, f"multi_trial_bin1_{ibin1}_bin2_{ibin2}.root") # Central fits canvas = TCanvas("fit_canvas", suffix_write, 1400, 800) fit.draw(canvas, title=title) if self.pars_factory.apply_weights is False: canvas.SaveAs( make_file_path(save_dir, "multi_trial", "eps", None, suffix_write)) else: canvas.SaveAs( make_file_path(save_dir, "multi_trial_weights", "eps", None, suffix_write)) if root_dir: root_dir.cd() canvas.Write(f"multi_trial_{suffix_write}") canvas.Close()
def plotRatio(var,name,hist1,hist2): """Plot minimal ratio of two histograms.""" canvas = TCanvas('canvas','canvas',100,100,800,800) canvas.Divide(2) canvas.cd(1) gPad.SetPad('pad1','pad1',0,0.42,1,1,0,-1,0) gPad.SetTopMargin( 0.10 ); gPad.SetBottomMargin( 0.01 ) hist1.Draw() hist2.Draw('SAME') hist1.SetLineColor(kBlue) hist2.SetLineColor(kRed) hist1.SetLineWidth(2) hist2.SetLineWidth(2) hist1.SetLineStyle(1) hist2.SetLineStyle(2) hist1.Draw('HIST') hist2.Draw('HIST SAMES') gPad.Update() stats1 = hist1.GetListOfFunctions().FindObject('stats') stats2 = hist2.GetListOfFunctions().FindObject('stats') stats1.SetY1NDC(.74); stats1.SetY2NDC(.94) stats2.SetY1NDC(.50); stats2.SetY2NDC(.70) stats1.Draw() stats2.Draw() canvas.cd(2) gPad.SetPad('pad2','pad2',0,0,1,0.41,0,-1,0) gPad.SetTopMargin( 0.05 ); gPad.SetBottomMargin( 0.24 ) ratio = hist1.Clone('ratio') ratio.Divide(hist2) for i, (y1, y2, r) in enumerate(zip(hist1,hist2,ratio),0): if hist1.GetBinContent(i)==0 and hist2.GetBinContent(i)==0: ratio.SetBinContent(i,1) ratio.GetXaxis().SetTitle(var) ratio.GetXaxis().SetLabelSize(0.045) ratio.GetYaxis().SetLabelSize(0.045) ratio.GetXaxis().SetTitleSize(0.060) ratio.SetMinimum(0.2) ratio.SetMaximum(1.8) ratio.Draw() statsr = ratio.GetListOfFunctions().FindObject('stats') statsr.SetY1NDC(.65); statsr.SetY2NDC(.98) canvas.SaveAs(name) canvas.Close() gDirectory.Delete(hist1.GetName()) gDirectory.Delete(hist2.GetName()) gDirectory.Delete(ratio.GetName())
def LoopPlotOnCanvas(pdf_name, list_histo): #c = TCanvas('c','c') canvas = TCanvas('c', 'c', 600, 600) canvas.Print(pdf_name + '.pdf[') canvas.Close() for idx, inst in enumerate(list_histo, 1): canvas, title = inst.PlotOnCanvas(pdf_name=pdf_name + '.pdf') # if isinstance(canvas,list): # for c in canvas: # c.Print(pdf_name+'.pdf') # if idx == len(list_histo): # canvas[-1].Print(pdf_name+'.pdf]') # for c in canvas: # c.Close() canvas.Print(pdf_name + '.pdf', 'Title:' + title) if idx == len(list_histo): canvas.Print(pdf_name + '.pdf]') canvas.Close() logging.info('Plots saved at %s' % (pdf_name + '.pdf'))
def plot2D(histname, hist, log=False, year=''): """Plot efficiency.""" dir = ensureDirectory('plots/Efficiency') name = "%s/%s" % (dir, histname) if log: name += "_log" xtitle = 'jet p_{T} [GeV]' ytitle = 'jet #eta' ztitle = 'b tag efficiencies' if '_b_' in histname else 'b miss-tag rate' name = name + "_" + str(year) canvas = TCanvas('canvas', 'canvas', 100, 100, 800, 700) canvas.SetFillColor(0) canvas.SetBorderMode(0) canvas.SetFrameFillStyle(0) canvas.SetFrameBorderMode(0) canvas.SetTopMargin(0.07) canvas.SetBottomMargin(0.13) canvas.SetLeftMargin(0.12) canvas.SetRightMargin(0.17) canvas.SetTickx(0) canvas.SetTicky(0) canvas.SetGrid() if log: canvas.SetLogz() canvas.cd() hist.Draw('COLZTEXT77') hist.GetXaxis().SetTitle(xtitle) hist.GetYaxis().SetTitle(ytitle) hist.GetZaxis().SetTitle(ztitle) hist.GetXaxis().SetLabelSize(0.048) hist.GetYaxis().SetLabelSize(0.048) hist.GetZaxis().SetLabelSize(0.048) hist.GetXaxis().SetTitleSize(0.058) hist.GetYaxis().SetTitleSize(0.058) hist.GetZaxis().SetTitleSize(0.056) hist.GetXaxis().SetTitleOffset(1.03) hist.GetYaxis().SetTitleOffset(1.04) hist.GetZaxis().SetTitleOffset(1.03) hist.GetZaxis().SetLabelOffset(-0.005 if log else 0.005) hist.SetMinimum(0.01 if log else 0.0) hist.SetMaximum(1.0) gStyle.SetPaintTextFormat('.2f') hist.SetMarkerSize(1.0) hist.SetMarkerColor(kRed) hist.SetMarkerSize(1) canvas.SaveAs(name + '.pdf') canvas.SaveAs(name + '.png') canvas.Close()
def DrawHists2d(self, options=None): for hist in self.hists2d: name = hist.GetName() canvas = TCanvas(name, name) if hist.GetLogY(): gPad.SetLogy(1) if options: hist.SetOption(options) hist.Draw() for ext in self.GetExtensions(): canvas.SaveAs("%s/%s%s" % (self.GetOutputDir(), canvas.GetTitle(), ext)) canvas.Write() canvas.Clear() canvas.Close() return
def plotPerTimeStamp(options): """Save profile histograms per timestamp to PDF files""" name = options['name'] + '_' + options['scan'] + '_perTime' if options['extra']: name += '_' + options['extra'] f = openRootFileR(options['name'] + '_perTime') histname = plotName(name, timestamp=False) filename = plotName(name, timestamp=True) filepath = plotPath(name, timestamp=True) print '<<< Save plot:', filepath hist = f.Get(histname) hist.SetErrorOption(options['error']) if options['big']: canvas = TCanvas('c', '', 8000, 1200) else: canvas = TCanvas('c', '', 1400, 500) canvas.SetLogy(options['logy']) gStyle.SetOptStat(options['optstat']) hist.Draw() gPad.Update() hist.GetXaxis().SetTimeDisplay(1) hist.GetXaxis().SetTimeFormat('#splitline{%d.%m.%y}{%H:%M:%S}%F1969-12-31' \ +' 22:00:00') hist.GetXaxis().SetLabelOffset(0.03) hist.GetXaxis().SetTitle('') if 'xmin' in options and 'xmax' in options: hist.GetXaxis().SetRangeUser(options['xmin'], options['xmax']) hist.GetYaxis().SetTitle(options['ytitle']) hist.GetYaxis().SetTitleOffset(1.2) for axis in [hist.GetXaxis(), hist.GetYaxis()]: axis.SetTitleFont(133) axis.SetTitleSize(16) axis.SetLabelFont(133) axis.SetLabelSize(12) axis.CenterTitle() if options['big']: axis.SetTickLength(0.01) if options['big']: hist.GetYaxis().SetTitleOffset(0.25) drawSignature(filename) gPad.Modified() gPad.Update() if options['retrn']: return [canvas, hist, f] else: canvas.Print(filepath) canvas.Close() closeRootFile(f, options['name'] + '_perTime')
def compare_variables(sample, var_list, name): cv = TCanvas("cv", "cv", 1000, 800) cv.SetGrid() cv.cd() if "CSV" in name: leg = TLegend(0.12, 0.6, 0.45, 0.88) elif "pT" in name: leg = TLegend(0.62, 0.6, 0.95, 0.88) nomefile[sample] = TFile.Open( NTUPLEDIR + samples[sample]['file'] + ".root", 'read') leg.SetHeader(samples[sample]['leg_name']) massimo = 0 for i, s in enumerate(var_list): histo[s] = nomefile[sample].Get(samples[sample]['type'] + "/" + s) histo[s].SetLineColor(colors[i]) histo[s].SetLineWidth(3) histo[s].SetTitle("") if "CSV" in name: histo[s].GetXaxis().SetTitle("CSV score") elif "pT" in name: histo[s].GetXaxis().SetTitle("p_{T} [GeV]") leg.AddEntry(histo[s], variables[s]['legend_label']) histo[s].GetXaxis().SetRangeUser(variables[s]['xmin'], variables[s]['xmax']) if sample == "ZH_MS-40_ctauS-1": print i, s, massimo massimo = max(massimo, histo[s].GetMaximum()) histo[s].Draw("same") histo[s].SetMaximum(massimo * 1.2) uncert[s] = histo[s].Clone(s + "_err") uncert[s].SetMarkerStyle(0) uncert[s].SetFillColor(colors[i]) uncert[s].SetFillStyle(3001) uncert[s].Draw("SAME,E2") if variables[s]['log']: cv.SetLogy() leg.Draw() latex = TLatex() latex.SetNDC() latex.SetTextAlign(33) latex.SetTextSize(0.04) latex.SetTextFont(62) latex.DrawLatex(0.20, 0.96, "CMS") latex.SetTextFont(52) latex.DrawLatex(0.36, 0.96, "Simulation") cv.Print(PLOTDIR + name + "_" + sample + '.png') cv.Print(PLOTDIR + name + "_" + sample + '.pdf') cv.Close()
def plotEfficiencies2D(filename, prefix, workingpoint, label=""): print ">>>\n>>> plotEfficiencies2D - %s" % (filename) file = TFile(filename, 'READ') dirname = "bTagEff" histnames = [ "%s_%s_%s_eff" % (prefix, "udsg", workingpoint), "%s_%s_%s_eff" % (prefix, "b", workingpoint), ] for histname in histnames: print ">>> %s" % (histname) flavor = "b" if "udsg" in histname: flavor = "light" if "_c_" in histname: flavor = "c" range = [0.25, 0.70] if flavor == "light": range = [0.0, 0.10] hist = file.Get("%s/%s" % (dirname, histname)) canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600) canvas.SetBottomMargin(0.12) canvas.SetRightMargin(0.11) canvas.SetLeftMargin(0.10) canvas.SetTopMargin(0.08) hist.Draw("colz") hist.SetTitle("") hist.GetZaxis().SetRangeUser(*range) #hist.GetXaxis().SetRangeUser(0,100) #hist.GetYaxis().SetRangeUser(0,200) hist.GetXaxis().SetTitle("%s jet p_{T}" % (flavor)) hist.GetYaxis().SetTitle("%s jet #eta" % (flavor)) hist.GetYaxis().CenterTitle() hist.GetXaxis().SetLabelSize(0.042) hist.GetYaxis().SetLabelSize(0.042) hist.GetXaxis().SetTitleSize(0.05) hist.GetYaxis().SetTitleSize(0.05) hist.GetXaxis().SetTitleOffset(1.10) hist.GetYaxis().SetTitleOffset(0.99) gStyle.SetOptStat(0) CMS_lumi.CMS_lumi(canvas, 13, 0) canvas.SaveAs("%s/%s%s.png" % (OUT_DIR, histname, label)) canvas.Close() file.Close()
def getCurve(h): # Temporary draw c = TCanvas() c.cd() h.Smooth() h.SetContour(2) #h.Draw("COLZ") h.Draw("CONT Z LIST") c.Update() # Get contours curves = [] conts = TObjArray(gROOT.GetListOfSpecials().FindObject("contours")) gs = TGraphSmooth("normal") gin = TGraph(conts.At(0).At(0)) gout = gs.SmoothSuper(gin, "", 3) x_m = array('d', []) x_p = array('d', []) y_m = array('d', []) y_p = array('d', []) for p in xrange(0, gout.GetN()): gr_x = ROOT.Double(0.) gr_y = ROOT.Double(0.) gout.GetPoint(p, gr_x, gr_y) x_m.append(-gr_x) y_m.append(-gr_y) x_p.append(gr_x) y_p.append(gr_y) # if opt == 'w': # x_p[0] = 0. # x_m[0] = 0. curves.append(TGraph(len(x_p), x_p, y_p)) curves.append(TGraph(len(x_m), x_m, y_m)) curves.append(TGraph(len(x_p), x_p, y_m)) curves.append(TGraph(len(x_m), x_m, y_p)) c.Close() return curves
def PlotOnCanvas(self, pdf_name): tdrstyle.setTDRStyle() canvas = TCanvas("c1", "c1", 600, 600) self.histo.SetTitleOffset(1.6, 'xyz') if self.option == "colz": canvas.SetRightMargin(0.2) self.histo.SetContour(100) self.histo.Draw(self.option) if self.logx: canvas.SetLogx() if self.logy: canvas.SetLogy() if self.logz: canvas.SetLogz() canvas.Print(pdf_name, 'Title:' + self.title) canvas.Close()
def PlotOnCanvas(self, pdf_name): tdrstyle.setTDRStyle() canvas = TCanvas("c1", "c1", 600, 600) self.histo.SetTitleOffset(1.6, 'xyz') self.histo.SetMinimum(0) self.histo.SetLineWidth(2) self.histo.SetTitle(self.title) if self.logx: canvas.SetLogx() if self.logy: canvas.SetLogy() self.histo.SetMinimum(1) self.histo.Draw(self.option) canvas.Print(pdf_name, 'Title:' + self.title + " (sample : %s)" % self.filename) canvas.Close()
def drawQCDNNLOCorr(): filename = path + "lindert_qcd_nnlo_sf.root" histname1 = "eej" histname2 = "evj" histname3 = "vvj" file1 = ensureTFile(filename) hist1 = file1.Get(histname1) hist2 = file1.Get(histname2) hist3 = file1.Get(histname3) hist1.SetDirectory(0) hist2.SetDirectory(0) hist3.SetDirectory(0) file1.Close() c1 = TCanvas("c1", "sf plot", 800, 600) hist1.SetTitle("QCD NNLO SF") hist1.GetXaxis().SetTitle("V p_{T} (GeV)") hist1.GetYaxis().SetTitle("QCD NNLO SF") hist1.GetYaxis().SetRangeUser(1., 1.18) hist1.SetLineColor(3) hist2.SetLineColor(2) hist3.SetLineColor(4) hist1.SetLineWidth(3) hist2.SetLineWidth(3) hist3.SetLineWidth(3) hist1.SetMarkerStyle(8) hist1.SetMarkerColor(3) hist2.SetMarkerStyle(8) hist2.SetMarkerColor(2) hist3.SetMarkerStyle(8) hist3.SetMarkerColor(4) leg = TLegend(0.15, 0.6, 0.3, 0.8) leg.AddEntry(hist1, "DY+Jets") leg.AddEntry(hist2, "W+Jets") leg.AddEntry(hist3, "Z+Jets") c1.SetLogx() hist1.Draw("LP HIST") hist2.Draw("LP HIST SAME") hist3.Draw("LP HIST SAME") leg.Draw("SAME") gStyle.SetOptStat(0) c1.SaveAs("./plotsSF/QCDNNLOCorr.pdf") c1.SaveAs("./plotsSF/QCDNNLOCorr.png") c1.Close()
def plotPerBxStep(options): """Save histograms (per BX and step) to PDF files""" name = options['scan'] + '_' + options['name'] + options['extra'] if 'method' in options: name += '_' + options['method'] f = openRootFileR(name) for bx in options['crossings']: for step in range(len(O['nominalPos'][options['scan']])): histname = plotName(name+'_bx'+str(bx)+'_step'+str(step), \ timestamp=False) filename = plotName(name+'_bx'+str(bx)+'_step'+str(step), \ timestamp=True) filepath = plotPath(name+'_bx'+str(bx)+'_step'+str(step), \ timestamp=True) print '<<< Save plot:', filepath hist = f.Get(histname) canvas = TCanvas() canvas.SetLogx(options['logx']) canvas.SetLogy(options['logy']) gStyle.SetOptStat(options['optstat']) gStyle.SetOptFit(options['optfit']) hist.Draw() gPad.Update() hist.GetXaxis().SetTitle(options['xtitle']) hist.GetXaxis().SetRangeUser(options['xmin'], options['xmax']) hist.GetYaxis().SetTitle(options['ytitle']) hist.GetYaxis().SetTitleOffset(1.2) for axis in [hist.GetXaxis(), hist.GetYaxis()]: axis.SetTitleFont(133) axis.SetTitleSize(16) axis.SetLabelFont(133) axis.SetLabelSize(12) axis.CenterTitle() stats = hist.FindObject('stats') stats.SetTextFont(133) stats.SetTextSize(16) drawSignature(filename) gPad.Modified() gPad.Update() if 'custom' in options: extragraphs = options['custom'](hist) canvas.Print(filepath) canvas.Close() closeRootFile(f, name)
def Draw(self, option_=None): name = self.hist.GetName() canvas = TCanvas(name, name) canvas.Draw() if self.hist.GetLogY(): gPad.SetLogy(1) if option_: option = option_ else: option = self.options self.h().Draw(option) self.h().SetTitle("") self.h().GetXaxis().SetTitle(self.GetXaxis()) self.h().GetYaxis().SetTitle(self.GetYaxis()) if self.hist.GetLegend(): self.hist.GetLegend().Draw() for ext in self.hist.GetExtensions(): canvas.SaveAs("%s/%s%s" % (self.hist.GetOutputDir(), canvas.GetTitle(), ext)) canvas.Write() canvas.Clear() canvas.Close()
def draw(fitter, save_name, **kwargs): """Draw helper function This can safely be ignored in view of understanding this script and it doesn't do anything but drawing a fit. It won't change any number. """ c = TCanvas("canvas", "", 500, 500) try: fitter.draw(c, **kwargs) # NOTE The broad-except is only used to make this script running under # any circumstances and ignore any reason for which a fit could not # be drawn. except Exception as e: # pylint: disable=broad-except print(f"Could not draw fit") print(fitter) print(e) c.SaveAs(save_name) c.Close()
def draweffplot(filename1, histname1, name1, ptvseta): if 'Electron' in filename1: lepton = "electron" else: lepton = "muon" file1 = ensureTFile(filename1) hist1 = file1.Get(histname1) hist = hist1 hist.SetDirectory(0) file1.Close() if '2016' in filename1: year = '2016' elif '2017' in filename1: year = '2017' elif '2018' in filename1: year = '2018' c1 = TCanvas("c1", "sf plot", 800, 600) hist.SetOption("COLZ") hist.SetTitle("%s trigger scale factor %s" % (lepton, year)) if ptvseta: hist.GetXaxis().SetTitle("#eta") hist.GetYaxis().SetTitle("p_{T}") if lepton == "muon": if year == '2016': hist.GetYaxis().SetRangeUser(0, 800) else: hist.GetYaxis().SetRangeUser(0, 1200) else: if year == '2017': hist.GetYaxis().SetRangeUser(0, 1000) else: hist.GetYaxis().SetRangeUser(0, 1000) hist.GetYaxis().SetTitleOffset(1.2) else: hist.GetXaxis().SetTitle("p_{T}") hist.GetYaxis().SetTitle("#eta") hist.GetZaxis().SetRangeUser(0.7, 1.0) hist.Draw() gStyle.SetOptStat(0) c1.SaveAs("./plotsSF/%s_trigger_sf_%s.pdf" % (lepton, year)) c1.SaveAs("./plotsSF/%s_trigger_sf_%s.png" % (lepton, year)) c1.Close()
def checklegend(samples,tag=""): """Check legend entries: colors, titles, ...""" # https://root.cern.ch/doc/master/classTLegend.html LOG.header("checklegend"+tag.replace(' ','')) output = ensuredir('plots') fname = "%s/testStyle_legend%s"%(output,tag) #height = 0.05*(len(samples)) xdim = 550 ydim = 50*(len(samples)+2) #width = 0.4 #x1, y1 = 0.1, 0.9 print ">>> Canvas: %sx%s (nsamples=%d)"%(xdim,ydim,len(samples)) canvas = TCanvas('canvas','canvas',xdim,ydim) #legend = TLegend(x1,y1,x1+width,y1-height) legend = TLegend(0,0,1,1) legend.SetBorderSize(0) legend.SetMargin(0.12) #legend.SetTextSize(tsize) #legend.SetNColumns(ncols) #legend.SetColumnSeparation(colsep) #legend.SetHeader("HTT style",'C') legend.SetTextFont(42) # bold for title hists = [ ] for sample in samples: color = STYLE.getcolor(sample,verb=2) title = STYLE.gettitle(sample,latex=True,verb=2) style = 'ep' if 'Data' in sample else 'f' hist = TH1F(sample,title,1,0,1) hist.SetFillColor(color) #hist.SetLineColor(kBlack) hist.SetLineWidth(2) hist.SetMarkerColor(kBlack) #hist.SetMarkerStyle(1) legend.AddEntry(hist,title,style) if 'Data' in sample: hist.Draw('E1') hists.append(hist) legend.Draw() canvas.SaveAs(fname+".png") canvas.SaveAs(fname+".pdf") canvas.Close()