def plotPerLumiSection(options): """Save profile histograms per lumisection to PDF files""" name = options['name'] + '_perLS' f = openRootFileR(name) histname = plotName(options['title'] + '_perLS', timestamp=False) filename = plotName(options['title'] + '_perLS', timestamp=True) filepath = plotPath(options['title'] + '_perLS', timestamp=True) print '<<< Save plot:', filepath hist = f.Get(histname) canvas = TCanvas() canvas.SetLogy(options['logy']) gStyle.SetOptStat(options['optstat']) hist.Draw() gPad.Update() hist.GetXaxis().SetTitle('Lumisection') 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() drawSignature(filename) gPad.Modified() gPad.Update() #canvas.Print(filepath) #canvas.Close() #closeRootFile(f, name) return [canvas, hist, f]
def check(var, nbins, low, up, friend_var="Particle.{}", frame=df): h = f"{origin} {var}" h = frame.Histo1D(RDF.TH1DModel(h, h, nbins, low, up), f"f{var}") friend_var = friend_var.format(var) h2 = f"{friend} {friend_var}" h2 = df_delphes.Histo1D(RDF.TH1DModel(h2, h2, nbins, low, up), friend_var) h2.SetLineColor(2) h2.SetLineStyle(3) can = canvas(var, diff=True) can.cd(1) h.SetDirectory(0) h2.SetDirectory(0) hdrawn = [h.DrawCopy(), h2.DrawCopy("same")] for i in hdrawn: i.SetDirectory(0) leg = TLegend(.7, .5, .9, .75) leg.AddEntry(h.GetValue()) leg.AddEntry(h2.GetValue()) leg.Draw() gPad.Update() can.cd(2) hdiff = h.DrawCopy() hdiff.SetDirectory(0) hdiff.SetName("hdiff") hdiff.SetTitle("diff") hdiff.Add(h2.GetValue(), -1) hdiff.GetYaxis().SetRangeUser(-1, 1) gPad.Update() for i in range(1, hdiff.GetNbinsX() + 1): diff = hdiff.GetBinContent(i) if diff != 0: return False return True
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 make_pdf_with_twoTH2Fs(th2_first, th2_sec, outpdf_path): hist_ls = [th2_first, th2_sec] canv = TCanvas() style = setTDRStyle(pad_right_margin=0.15) gStyle.SetPaintTextFormat(".3g") gStyle.SetOptStat(0) canv.Print(outpdf_path + "[") for h2 in hist_ls: h2.GetXaxis().CenterLabels() h2.GetYaxis().CenterLabels() h2.UseCurrentStyle() h2.Draw("colz text") gPad.Update() pave = make_pave_with_stats(h2, xmin=0.15, ymin=0.8, xmax=0.4, ymax=0.9) pave.Draw("same") # statsbox = h2.FindObject("stats") # statsbox.SetX1NDC(0.55) # statsbox.SetX2NDC(0.8) # statsbox.SetY1NDC(0.8) # statsbox.SetY2NDC(0.9) canv.Print(outpdf_path) canv.Print(outpdf_path + "]")
def fit(hhh): hh = hhh.Clone("h" + hhh.GetName()) nbins = hh.GetNbinsX() for i in range(1, nbins): ### FIXME : 288 is hard-coded pedestal val = hh.GetBinContent(i) hh.SetBinContent(i, val) hh.SetBinError(i, 0.01 * (val + 288.)) func = TF1("langaus", langaufun, 0, 60, 4) func.SetParameter(0, .5) func.SetParameter(1, 17) ## most probable value func.SetParameter(2, 170) ## normalization (area) func.SetParameter(3, 2) ## width of gaussian ## the way I set up the histogram the peak is usually ## around bin 15-17. We get some of the pre-pulse ## but avoid the undershoot by cutting off pretty early func.SetRange(10, 27) hh.Fit("langaus", "R") peaktime = func.GetParameter(1) peak = func.Eval(peaktime) hh.Write() ## if you comment out these next two lines it'll probably go faster gPad.Modified() gPad.Update() return peak
def show_sample(self, fnameP='/data/Samples/TMSPlane/Dec26/sample_{0:d}.adc', Ns=10, ich=8): from ROOT import TGraph, gPad, TLatex s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5) data1 = s1.generate_adcDataBuf() data2 = s1.generate_sdmDataBuf() data3 = ((s1.ANALYSIS_WAVEFORM_BASE_TYPE * s1.nSamples) * Ns)() dataList = [] for i in range(Ns): fname = fnameP.format(i) s1.read_data([fname, ''], data1, data2) x = array.array('f', range(s1.nSamples)) # s1.filters_trapezoidal(data1[ich], data3[i], [100,100,200,-1]) s1.filters_trapezoidal(data1[ich], data3[i], [100, 100, 100, 0.000722]) g1 = TGraph(s1.nSamples, x, data3[i]) # g1 = TGraph(s1.nSamples, x, data1[ich]) opt = 'AP' if i == 0 else "PSame" g1.Draw(opt + ' PLC PMC') dataList.append(g1) lt = TLatex() lt.DrawLatexNDC(0.2, 0.8, "Chan={0:d}".format(ich)) gPad.Update() waitRootCmdX()
def drawcounts(h): txt = TPaveText(0.75, 0.55, 0.88, 0.7, "NDC") for i in h: txt.AddText("{}={}".format(i.GetTitle(), i.GetEntries())) txt.Draw() latexdrawn.append(txt) gPad.Update()
def get_ccdb_obj(ccdb_path, timestamp, out_path, host, show, verbose): """ Gets the ccdb object from 'ccdb_path' and 'timestamp' and downloads it into 'out_path' """ if verbose: print("Getting obj", ccdb_path, "with timestamp", timestamp, convert_timestamp(timestamp)) cmd = f"o2-ccdb-downloadccdbfile --host {host} --path {ccdb_path} --dest {out_path} --timestamp {timestamp}" subprocess.run(cmd.split()) if verbose: f = TFile(os.path.join(out_path, ccdb_path, "snapshot.root"), "READ") meta = f.Get("ccdb_meta") if False: print("Metadata") for i in meta: print(i) def print_info(entry): print("Object", entry, meta[entry]) print_info("Last-Modified") if show: obj = f.Get("ccdb_object") obj.Draw() time_box = TPaveText(.01, .9, 0.3, 0.99, "NDC") time_box.AddText(ccdb_path) time_box.AddText(f"timestamp {timestamp}") time_box.AddText(f"{convert_timestamp(timestamp)}") time_box.Draw() gPad.Update() input("Press enter to continue")
def DrawScat2XLine(graph, title, fname, ycoord1, ycoord2): #, grid): c = TCanvas("c", "c", 800, 600) graph.SetTitle(title) graph.GetXaxis().SetTitleSize(.04) graph.GetYaxis().SetTitleSize(.04) graph.GetXaxis().SetTitleOffset(1.2) graph.GetYaxis().SetTitleOffset(1.25) graph.GetXaxis().CenterTitle(1) graph.GetYaxis().CenterTitle(1) graph.GetYaxis().SetMaxDigits(4) graph.SetMarkerStyle(20) # Full circle graph.Draw() gPad.Update() line1 = TLine(gPad.GetUxmin(), ycoord1, gPad.GetUxmax(), ycoord1) line2 = TLine(gPad.GetUxmin(), ycoord2, gPad.GetUxmax(), ycoord2) # print(gPad.GetUymin(),gPad.GetUymax()) line1.SetLineStyle(2) line1.SetLineColor(2) line1.SetLineWidth(3) line2.SetLineStyle(2) line2.SetLineColor(2) line2.SetLineWidth(3) graph.Draw("AP") line1.Draw("same") line2.Draw("same") c.SaveAs(fname + ".C") c.SaveAs(fname + ".pdf") return
def SaveHisto2D(histin, tokens, data=False): proc = 'DY' if not data else 'DATA' histname = histin.GetName() cam = TCanvas(histname, histname, 2000, 2000) cam.SetTopMargin(0.1) cam.SetBottomMargin(0.15) cam.SetLeftMargin(0.215) cam.SetRightMargin(0.15) cam.cd().SetLogz() histin.Draw("colztextE") histin.SetTitle(histname) #needed to move the axis a bit z_begin = 0.875 palette = histin.GetListOfFunctions().FindObject("palette") palette.SetX1NDC(z_begin) palette.SetX2NDC(z_begin + 0.05) histin.GetZaxis().SetTitle('N_SS/N_OS') gPad.Modified() gPad.Update() cam.SaveAs('plots/%s/Ratio_%s_%s.png' % (tokens, tokens, proc)) cam.SaveAs('plots/%s/Ratio_%s_%s.pdf' % (tokens, tokens, proc)) #cam.SaveAs('plots/%s/Ratio_%s_DY.C' %(histname.split('_')[-1],histname)) return
def draw_2histograms( histo1, histo2, x_axisName, y_axisName, leg1Name, leg2Name ): histo1.GetXaxis().SetTitle(x_axisName) if (y_axisName==""): histo1.GetYaxis().SetTitle("Entries/per bin") else: histo1.GetYaxis().SetTitle(y_axisName) histo2.SetLineColor(2) if (leg1Name!=""): histo1.SetStats(0) histo2.SetStats(0) legend=TLegend(0.45,0.78,0.9,0.9) legend.AddEntry(histo1, leg1Name, "l") legend.AddEntry(histo2, leg2Name, "l") legend.SetTextSize(0.05) SetOwnership( legend, 0 ) maximum1 = 1.2*histo1.GetMaximum() maximum2 = 1.2*histo2.GetMaximum() maximum = maximum1 if (maximum2>maximum): maximum = maximum2 histo1.SetMaximum(maximum) histo1.Draw() histo2.Draw("same") if (leg1Name!=""): legend.Draw("same") gPad.Update() return
def plot(self, gD01, gDbar01, repeat=False): N = gD01.GetN() xD01 = gD01.GetX() yD01 = gD01.GetY() zD01 = gD01.GetZ() xDbar01 = gDbar01.GetX() yDbar01 = gDbar01.GetY() zDbar01 = gDbar01.GetZ() gr1 = TGraph2D(N) gr1.SetName("delta" + self.obj) for i in range(N): x1 = xD01[i] y1 = yD01[i] if self.obj=="gAbs": z1 = gDbar01.Interpolate(y1,x1) / zD01[i] * 100 else: z1 = gDbar01.Interpolate(y1, x1) - zD01[i] * 100 if (z1 < 0): z1 += 2 * pi #z1 *= 1/(2*pi) #z1 = zDbar01[i] - gD01.Interpolate(y1,x1) gr1.SetPoint(i, x1, y1, z1) xD1 = gr1.GetX() yD1 = gr1.GetY() zD1 = gr1.GetZ() #set_palette() theta = 89.9 phi=0.1 c1 = TCanvas("c1", "c1", 4000, 4000) gPad.SetLeftMargin(0.1) c1.cd() titles = { "gArg":"#delta_{D}", "gAbs": "|A_{#bar{D}^{0}}|/|A_{D^{0}}|" } title = titles[self.obj] if (repeat): title = "#Delta" + title gr1.SetTitle("%s ; m^{2}_{K_{S}^{0} #pi^{+}} ; m^{2}_{K_{S}^{0} #pi^{-}}" % (title)) gr1.GetXaxis().SetLabelOffset(15) gr1.GetYaxis().SetLabelOffset(15) gr1.GetZaxis().SetLabelOffset(15) gr1.SetMargin(0.02) gr1.Draw(self.draw2D) gPad.SetTheta(theta) gPad.SetPhi(phi) gPad.SetLeftMargin(0.15) gStyle.SetPalette(55) gPad.Update() c1.SaveAs("%s/Delta_%s.%s" % (self.output, self.obj, self.imgtype)) return gr1
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 printCanvas(histogram, title): "to print histogram for debugging" can = TCanvas() histogram.Draw("colz") gStyle.SetOptStat("") histogram.SetTitle("") histogram.GetXaxis().SetTitle("pixel number") histogram.GetYaxis().SetTitle("pixel number") histogram.GetZaxis().SetTitle("measured energy in cells") gPad.Update() palette = histogram.GetListOfFunctions().FindObject("palette") can.SetRightMargin(0.2) palette.SetX1NDC(0.8) palette.SetX2NDC(0.815) palette.SetY1NDC(0.1) palette.SetY2NDC(0.9) gPad.Modified() gPad.Update() can.Print(title + ".png")
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 draw_1histogram( histo, x_axisName, y_axisName ): histo.GetXaxis().SetTitle(x_axisName) if (y_axisName==""): histo.GetYaxis().SetTitle("Entries/per bin") else: histo.GetYaxis().SetTitle(y_axisName) maximum = 1.2*histo.GetMaximum() histo.SetMaximum(maximum) histo.Draw() gPad.Update() return
def plotGraph(self, x='vv', y='acc'): ''' Plot a graph with specified quantities on x and y axes , and saves the graph ''' if (x not in self.quantities.keys()) or (y not in self.quantities.keys()): raise RuntimeError('selected quantities not available, available quantities are: \n{}'.format(self.quantities.keys())) xq = self.quantities[x] yq = self.quantities[y] #graph = TGraphAsymmErrors() #graph = TGraph() graph = TGraphErrors() for i,s in enumerate(self.samples): graph.SetPoint(i,getattr(s, xq.name), getattr(s, yq.name) ) #if xq.err: # graph.SetPointEXhigh(i, getattr(s, xq.name+'_errup')) # errup errdn # graph.SetPointEXlow (i, getattr(s, xq.name+'_errdn')) if yq.err: graph.SetPointError(i, 0, getattr(s, yq.name+'_errup')) # graph.SetPointEYhigh(i, getattr(s, yq.name+'_errup')) # graph.SetPointEYlow (i, getattr(s, yq.name+'_errdn')) c = TCanvas() graph.SetLineWidth(2) graph.SetMarkerStyle(22) graph.SetTitle(';{x};{y}'.format(y=yq.title,x=xq.title)) graph.Draw('APLE') if yq.forceRange: graph.SetMinimum(yq.Range[0]) graph.SetMaximum(yq.Range[1]) gPad.Modified() gPad.Update() if yq.name=='expNevts': line = TLine(gPad.GetUxmin(),3,gPad.GetUxmax(),3) line.SetLineColor(ROOT.kBlue) line.Draw('same') #graph.SetMinimum(0.01) #graph.SetMaximum(1E06) if xq.log: c.SetLogx() if yq.log: c.SetLogy() c.SetGridx() c.SetGridy() c.SaveAs('./plots/{}{}/{}_{}VS{}.pdf'.format(self.label,suffix,self.name,yq.name,xq.name)) c.SaveAs('./plots/{}{}/{}_{}VS{}.C'.format(self.label,suffix,self.name,yq.name,xq.name)) c.SaveAs('./plots/{}{}/{}_{}VS{}.png'.format(self.label,suffix,self.name,yq.name,xq.name)) self.graphs['{}VS{}'.format(yq.name,xq.name)] = graph # add the graph container for memory? graph_saver.append(graph)
def draw_data(self): self.mframe = self.xvar.frame() self.data.plotOn(self.mframe) self.underlying_model.plotOn(self.mframe) for icomp, compname in enumerate(self.pdfs): self.underlying_model.plotOn(self.mframe, RooFit.Components(compname), RooFit.LineColor(icomp + 1)) self.mframe.Draw() gPad.Modified() gPad.Update()
def drawTemplates(plot): global cantemp cantemp = TCanvas('cantemp', 'templates', 800,800) cantemp.cd() for hist in plot.histosDict.values(): if hist.name not in ['TTJets','Ztt','WJets', 'QCD']: continue hist.Draw() gPad.Update() cantemp.SaveAs(hist.name + '.png') time.sleep(1)
def ReadOneFile(PairsDat, alpha, h2d): hist_px = TH1F("px", "; p_{x} [MeV]; Entries", 120, -20, 100) hist_py = TH1F("py", "; p_{y} [MeV]; Entries", 200, -10, 10) hist_pz = TH1F("pz", "; p_{z} [MeV]; Entries", 200, -1000, 1000) with open(PairsDat, "r") as fp: lines = fp.readlines() for line in lines: if len(line.split()) < 2: continue pdgCode = float(line.split()[1]) sign = np.sign(pdgCode) e = 1 #float(line.split()[9]) charge = -sign px = float(line.split()[6]) * e py = float(line.split()[7]) * e pz = float(line.split()[8]) * e hist_px.Fill(px * 1000) hist_py.Fill(py * 1000) hist_pz.Fill(pz * 1000) canvx = TCanvas("px", "px") hist_px.Draw() gPad.SetLogy() gPad.Update() gPad.Modified() canvy = TCanvas("py", "py") hist_py.Draw() gPad.SetLogy() gPad.Update() gPad.Modified() canvz = TCanvas("pz", "pz") hist_pz.Draw() gPad.SetLogy() gPad.Update() gPad.Modified() bla = raw_input()
def fun(): c1 = TCanvas("c1", "c1", 600, 500) t.Draw() u.Draw("SAMES") v.Draw("SAMES") w.Draw("SAMES") o.Draw("SAMES") v.GetXaxis().SetTitle("Photons in Evt") v.GetYaxis().SetTitle("Events") v.GetYaxis().SetTitleOffset(1.3) u.GetXaxis().SetTitle("Photons in Evt") u.GetYaxis().SetTitle("Events") u.GetYaxis().SetTitleOffset(1.3) t.GetXaxis().SetTitle("Photons in Evt") t.GetYaxis().SetTitle("Events") t.GetYaxis().SetTitleOffset(1.3) w.GetXaxis().SetTitle("Photons in Evt") w.GetYaxis().SetTitle("Events") w.GetYaxis().SetTitleOffset(1.3) o.GetXaxis().SetTitle("Photons in Evt") o.GetYaxis().SetTitle("Events") o.GetYaxis().SetTitleOffset(1.3) #Stats/Fit Options, stat box placement (top/bottom) gPad.Update() # su = u.FindObject("stats") # su.SetY1NDC(.1) # su.SetY2NDC(.25) # su.SetTextColor(ROOT.kRed) u.Fit(fit_u) # sv = v.FindObject("stats") # sv.SetY1NDC(.25) # sv.SetY2NDC(.4) # sv.SetTextColor(ROOT.kGreen) v.Fit(fit_v) # sw = w.FindObject("stats") # sw.SetY1NDC(.4) # sw.SetY2NDC(.55) # sw.SetTextColor(ROOT.kViolet) w.Fit(fit_w) gStyle.SetOptFit(0) gStyle.SetOptStat(0) # st = t.FindObject("stats") # st.SetY1NDC(.55) # st.SetY2NDC(.7) # st.SetTextColor(ROOT.kBlue) t.Fit(fit_t) #so = o.FindObject("stats") #so.SetY1NDC(.7) #so.SetY2NDC(.85) #so.SetTextColor(ROOT.kCyan) o.Fit(fit_o) return c1
def plot(fname, nbins=50, xmin=10, xmax=200): root_file = TFile(fname) tree = root_file.Get('events') canvas = TCanvas("canvas", "canvas", 600, 600) hist = TH1F("hist", ";mass of all particles (GeV)", nbins, 0, 200) tree.Draw('sum_all_m>>hist', '', '') hist.Fit("gaus", "LM", "", xmin, xmax) gPad.Update() gPad.SaveAs('sum_all_m.png') time.sleep(1) func = hist.GetFunction("gaus") holder.extend([root_file, tree, canvas, hist, func]) return func.GetParameter(1), func.GetParameter(2)
def lumiVsRunHisto(histograms, tree, minRun=165000, maxRun=168000, minLum=0, maxLum=3000): nbinsLum = maxLum - minLum nbinsRun = maxRun - minRun histograms.hlumVSrun = TH2F('hlumVSrun', ';Run number;Lumi number', nbinsRun, minRun, maxRun, nbinsLum, minLum, maxLum) tree.Draw('lumi:run>>' + histograms.hlumVSrun.GetName(), '', 'col') gPad.Modified() gPad.Update()
def plot(fname): root_file = TFile(fname) tree = root_file.Get('events') canvas = TCanvas("canvas", "canvas", 600,600) hist = TH1F("h", "higgs di-jet mass;m_{jj} (GeV)", 50, 0, 200) tree.Draw('higgs_m>>h', 'zed_m>50') # h.GetYaxis().SetRangeUser(0, 120) hist.Fit("gaus") gPad.Update() gPad.SaveAs('ee_ZH_mjj.png') time.sleep(1) func = hist.GetFunction("gaus") holder.extend([root_file, tree, canvas, hist, func]) return func.GetParameter(1), func.GetParameter(2)
def printCanvas(histogram,title,theRange,maximum): can=TCanvas() histogram.Draw("colz") gStyle.SetOptStat("") histogram.SetTitle("") histogram.GetXaxis().SetTitle("pixel number") histogram.GetYaxis().SetTitle("pixel number") histogram.GetZaxis().SetTitle("measured energy in cells") histogram.GetXaxis().SetRangeUser(theRange[0]-20,theRange[1]+20) histogram.GetYaxis().SetRangeUser(theRange[2]-20,theRange[3]+20) histogram.GetZaxis().SetRangeUser(0,maximum) gPad.Update() palette=histogram.GetListOfFunctions().FindObject("palette") can.SetRightMargin(0.2) palette.SetX1NDC(0.8) palette.SetX2NDC(0.815) palette.SetY1NDC(0.1) palette.SetY2NDC(0.9) gPad.Modified() gPad.Update() print ("title",title) can.Print("test/"+str(title)+".png")
def plot_2d(plot_pdf): plot_pdf.pdf.GetXaxis().SetTitleOffset(2.3) plot_pdf.pdf.GetYaxis().SetTitleOffset(1.9) plot_pdf.pdf.GetZaxis().SetTitleOffset(1.7) gPad.SetTopMargin(0.01) gPad.SetRightMargin(0.05) gPad.SetBottomMargin(0.11) gPad.SetLeftMargin(0.12) plot_pdf.plot() gPad.SetPhi(-125.) gPad.Update()
def drawTH2DColMap(h, c): """ Drawing a TH2D as color map requires some tweaking for a (more or less) nice result Most importantly the color axis has to be moved to the left for readable axis labels """ from ROOT import gPad, TPaletteAxis c.SetRightMargin(0.175) # make some space for color axis c.cd() h.Draw("colz") c.Update() # draw first, since the TPaletteAxis won't be available else p = h.GetListOfFunctions().FindObject("palette") p.SetX1NDC(0.84) # move to the right p.SetX2NDC(0.89) gPad.Modified() gPad.Update()
def draw_1histogram( histo, x_axisName, y_axisName="", colour = 9, markerStyle = 21): prepare_histogram(histo) histo.SetMarkerStyle(markerStyle) histo.SetMarkerColor(colour) histo.SetLineColor(colour) histo.GetXaxis().SetTitle(x_axisName) if (y_axisName==""): histo.GetYaxis().SetTitle("Entries/per bin") else: histo.GetYaxis().SetTitle(y_axisName) maximum = 1.2*histo.GetMaximum() histo.SetMaximum(maximum) histo.Draw("ep") gPad.Update() return
def D1H_txt_to_root(filename, outputpath=''): from ROOT import TFile, TCanvas, TPad, TH1D, TLatex, TStyle, gStyle, TText, gPad, TPaveText from inspect import currentframe, getframeinfo #gStyle.SetOptStat(0) can = TCanvas("can", "can", 200, 10, 500, 500) fileroot = filename.replace(".txt", "") fileroot = fileroot + "_F.root" f = open(filename, "r") lineList = f.readlines() Nbin = (len(lineList)) # get number of bins Line_string = str(lineList[0]) _, bin_init, _, _ = Line_string.split() bin_init = float(bin_init) # get initial bin Line_string = str(lineList[len(lineList) - 1]) _, _, bin_final, _ = Line_string.split() bin_final = float(bin_final) # get final bin f.seek(0) # reset python read line hist = TH1D("h1f", "h1f", Nbin, bin_init, bin_final) total_e = 0 for i in range(1, Nbin + 1): Line_string = str(f.readline()) _, _, _, bin_c = Line_string.split() bin_c = float(bin_c) hist.SetBinContent(i, bin_c) total_e = total_e + bin_c total_e = int(total_e) hist.Draw() text = TText(hist.GetXaxis().GetBinCenter(2), hist.GetYaxis().GetBinCenter(1), "Recycled. Total Entry : %i" % total_e) text.SetTextFont(10) text.Draw() gPad.Update() can.Update() if (outputpath == ''): wf = TFile(fileroot, "RECREATE") print(fileroot, " root file is generated !!!") else: fileroot = outputpath + "/_processed.root" wf = TFile(fileroot, "RECREATE") print(fileroot, " root file is generated !!!") hist.Write() wf.Close() return fileroot
def draw(self, var, cut): same = '' hists = [] for comp in self.comps.values(): comp.tree.Draw(var, cut, 'histnorm'+same) hist = comp.tree.GetHistogram() hists.append(hist) if hasattr(comp, 'style'): comp.style.formatHisto(hist) if same == '': var = var.split('>>')[0] same = 'same' maxy = max(h.GetMaximum() for h in hists) hists[0].GetYaxis().SetRangeUser(0, maxy*1.1) gPad.Modified() gPad.Update()