def post_clusterpos(pad, tree, hist): """Process the cluster position histogram and find beam area""" post_nostat(pad, tree, hist) maxbin = hist.GetMaximumBin() maxval = hist.GetBinContent(maxbin) thresh = 0.25 #look to the left and then to the right currbin = maxbin while (hist.GetBinContent(currbin) > thresh * maxval): currbin -= 1 left = hist.GetXaxis().GetBinLowEdge(currbin) currbin = maxbin while (hist.GetBinContent(currbin) > thresh * maxval): currbin += 1 right = hist.GetXaxis().GetBinUpEdge(currbin) hist.GetYaxis().SetRangeUser(0, maxval * 1.1) from ROOT import TLine l1 = TLine(left, 0, left, maxval * 1.1) pad.posl1 = l1 l1.Draw() l2 = TLine(right, 0, right, maxval * 1.1) pad.posl2 = l2 l2.Draw() pad.Update() return "clustersPosition > {} && clustersPosition < {}".format(left, right)
def mcplot(): hzjets1, hzjets2, hzjets3, hzjets4 = createHists("Zjets") htruth1, htruth2, htruth3, htruth4 = createHists("truth") hratio_pt_10_60 = createRatio(hzjets1, htruth1) hratio_pt_60_90 = createRatio(hzjets2, htruth2) hratio_pt_90_130 = createRatio(hzjets3, htruth3) hratio_pt_130_1000 = createRatio(hzjets4, htruth4) c, pad1, pad2 = createCanvasPads() gStyle.SetOptStat(0) #draw QmisID values first pad1.cd() pad1.SetLogy() hzjets1.GetYaxis().SetTitle("#in_{mis-id}") hzjets1.SetMinimum(0.00002) hzjets1.SetMaximum(1) hzjets1.GetYaxis().SetTitleSize(0.05) hzjets1.GetYaxis().SetTitleOffset(0.9) hzjets1.Draw("e") hzjets2.Draw("e same") hzjets3.Draw("e same") hzjets4.Draw("e same") htruth1.Draw("e same") htruth2.Draw("e same") htruth3.Draw("e same") htruth4.Draw("e same") createLabels("zjets") leg1 = createLegends("zjets", hzjets1, hzjets2, hzjets3, hzjets4) leg2 = createLegends("truth", htruth1, htruth2, htruth3, htruth4) leg1.Draw("same") leg2.Draw("same") #draw ratio pad2.cd() #painful adjustment for axis, lables, titles, never friendly.. hratio_pt_10_60.GetXaxis().SetTitle("|#eta|") hratio_pt_10_60.GetYaxis().SetTitle("Likelihood/Truth-matching") hratio_pt_10_60.GetYaxis().SetLabelSize(0.15) hratio_pt_10_60.GetYaxis().SetTitleSize(0.08) hratio_pt_10_60.GetXaxis().SetLabelSize(0.15) hratio_pt_10_60.GetXaxis().SetTitleSize(0.15) hratio_pt_10_60.GetXaxis().SetTitleOffset(1) hratio_pt_10_60.GetYaxis().SetTitleOffset(0.5) hratio_pt_10_60.GetYaxis().SetNdivisions(204) #set ranges, draw lines hratio_pt_10_60.SetMinimum(0) hratio_pt_10_60.SetMaximum(2.15) line1 = TLine(0, 0.5, 2.47, 0.5) line2 = TLine(0, 1.5, 2.47, 1.5) line3 = TLine(0, 1.0, 2.47, 1.0) hratio_pt_10_60.Draw("e") hratio_pt_60_90.Draw("e same") hratio_pt_90_130.Draw("e same") hratio_pt_130_1000.Draw("e same") line1.SetLineStyle(2) line2.SetLineStyle(2) line3.SetLineStyle(2) line1.Draw("same") line2.Draw("same") line3.Draw("same") c.SaveAs("mc_QmisID.pdf")
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 drawEtaValues(): """Function to draw the eta. Function to draw the eta references on top of an already existing TCanvas. The lines and labels drawn are collected inside a list and the list is returned to the user to extend the live of the objects contained, otherwise no lines and labels will be drawn, since they will be garbage-collected as soon as this function returns. """ # Add eta labels keep_alive = [] etas = [0.2 * i for i in range(-17, 18)] etax = 2850. etay = 1240. lineL = 110. offT = 10. for ieta in etas: th = 2 * atan(exp(-ieta)) talign = 21 #IP lineh = TLine(-20., 0., 20., 0.) lineh.Draw() linev = TLine(0., -10., 0., 10.) linev.Draw() keep_alive.append(lineh) keep_alive.append(linev) x1 = 0 y1 = 0 if ieta > -1.6 and ieta < 1.6: x1 = etay / tan(th) y1 = etay elif ieta <= -1.6: x1 = -etax y1 = -etax * tan(th) talign = 11 elif ieta >= 1.6: x1 = etax y1 = etax * tan(th) talign = 31 x2 = x1 + lineL * cos(th) y2 = y1 + lineL * sin(th) xt = x2 yt = y2 + offT line1 = TLine(x1, y1, x2, y2) line1.Draw() keep_alive.append(line1) text = "%3.1f" % ieta t1 = TLatex(xt, yt, '%s' % ('#eta = 0' if ieta == 0 else text)) t1.SetTextSize(0.03) t1.SetTextAlign(talign) t1.Draw() keep_alive.append(t1) return keep_alive
def drawCut(hist): #drawCut(80, 140, 0., hist['BkgSum'].GetMaximum()) line1 = TLine(80, 0, 80, hist['BkgSum'].GetMaximum()) line1.SetLineWidth(2) line1.SetLineStyle(7) line1.SetLineColor(1) line1.Draw() line2 = TLine(140, 0, 140, hist['BkgSum'].GetMaximum()) line2.SetLineWidth(2) line2.SetLineStyle(7) line2.SetLineColor(1) line2.Draw() line1 = TLine(0.841, 0, 0.841, 15) line1.SetLineWidth(2) line1.SetLineStyle(7) line1.SetLineColor(1) line1.Draw() line1 = TLine(100, 0, 100, hist['BkgSum'].GetMaximum()) line1.SetLineWidth(2) line1.SetLineStyle(7) line1.SetLineColor(1) line1.Draw()
def saveTuplePlot2D(events, inHisto1, inHisto2, nBinsX, minX, maxX, nBinsY, minY, maxY, mincut, maxcut, outfile, canvas, XaxisTitle="", YaxisTitle="", plotTitle="", stats=0, logY=0): events.Draw("{0}:{1}>>histo({2},{3},{4},{5},{6},{7})".format( inHisto2, inHisto1, nBinsX, minX, maxX, nBinsY, minY, maxY)) histo = ROOT.gROOT.FindObject("histo") histo.SetTitle(plotTitle) histo.GetXaxis().SetTitle(XaxisTitle) histo.GetYaxis().SetTitle(YaxisTitle) histo.SetStats(stats) histo.Draw("COLZ") minline = TLine(minX, mincut, maxX, mincut) minline.SetLineColor(2) minline.Draw("same") maxline = TLine(minX, maxcut, maxX, maxcut) maxline.SetLineColor(2) maxline.Draw("same") canvas.SetLogy(logY) canvas.Print(outfile + ".pdf") del histo
def post_tdc_prof(pad, tree, hist): """Process the charge v. TDC profile and find timing cut""" ymin = hist.GetMinimum() if ymin < 0: ymin *= 1.2 else: ymin *= 0.8 ymax = hist.GetMaximum() if ymax < 0: ymax *= 0.8 else: ymax *= 1.2 hist.GetYaxis().SetRangeUser(ymin, ymax) isneg = (ymax < 0) or (ymin < 0 and abs(ymin) > abs(ymax)) if isneg: b = hist.GetMinimumBin() else: b = hist.GetMaximumBin() from ROOT import TLine l1 = TLine(b - 1.5, ymin, b - 1.5, ymax) pad.tdcl1 = l1 l1.Draw() l2 = TLine(b + 1.5, ymin, b + 1.5, ymax) pad.tdcl2 = l2 l2.Draw() return "abs(clustersTDC - {}) <= 1.5".format(b)
def plot_calibrations(group_data, voltage, cal_pars_list, stacked=False): group_name = str(group_data[0].run_number) run = group_data[2] name = str(run.run_number) hists_and_lines = [] for cal_pars in cal_pars_list: pars = parameters.gain_pars[cal_pars] run.calibrate_energies(voltage, pars) hist = make_hist(name, run.calibrated_energies, 0, 3500) K_line = TLine(1460.820, 0, 1460.820, 1000000) K_line.SetLineColor(632) Tl_line = TLine(2614.511, 0, 2614.511, 1000000) Tl_line.SetLineColor(632) hists_and_lines.append([hist, K_line, Tl_line]) if stacked: print('Plotting stacked calibrated histograms.') run_canvas = TCanvas() run_canvas.SetLogy() colors = [808, 397, 436, 424, 628, 852, 800, 863, 403, 797] color_index = 0 hs = THStack('hs', 'Group %s Histograms' % group_name) for entry in hists_and_lines: title = str(run.run_number) entry[0].SetLineColor(colors[color_index]) color_index += 1 hs.Add(entry[0]) hs.Draw('nostack') K_line = TLine(1460.820, 0, 1460.820, 1000000) K_line.SetLineColor(632) K_line.Draw() Tl_line = TLine(2614.511, 0, 2614.511, 1000000) Tl_line.SetLineColor(632) Tl_line.Draw() run_canvas.BuildLegend() path = 'output/group_' + str(group_data[0].run_number) + '/' run_canvas.Print((path + str(group_data[0].run_number) + '_stacked_calibrated_histogram.pdf[')) run_canvas.Print((path + str(group_data[0].run_number) + '_stacked_calibrated_histogram.pdf')) run_canvas.Print((path + str(group_data[0].run_number) + '_stacked_calibrated_histogram.pdf]')) else: print('Plotting calibrated energy histogram.') run_canvas = TCanvas("run_canvas", "run canvas") run_canvas.Divide(3, int(len(cal_pars_list) / 2)) canvas_index = 1 for entry in hists_and_lines: pad = run_canvas.cd(canvas_index) pad.SetLogy() entry[0].Draw() entry[1].Draw() entry[2].Draw() pad.Update() canvas_index += 1 path = 'output/group_' + group_name + '/' run_canvas.Print((path + name + '_calibrated_histograms.pdf[')) run_canvas.Print((path + name + '_calibrated_histograms.pdf')) run_canvas.Print((path + name + '_calibrated_histograms.pdf]'))
def plot_sector_beam(canvas, histos, title_formatter, label, save_name): canvas.Clear() canvas.Divide(3, 2) vert = TLine(0, -1.2, 0, 1.2) hori = TLine(-1.2, 0, 1.2, 0) vert.SetLineStyle(8) vert.SetLineStyle(1) vert.SetLineWidth(1) hori.SetLineStyle(8) hori.SetLineStyle(1) hori.SetLineWidth(1) xtitle = '#Delta E_{beam} (#theta_{e}, p_{e})' ytitle = '#Delta E_{beam} (#theta_{e}, #theta_{p})' for i in range(1, 7): canvas.cd(i) histos[title_formatter.format(i)].GetXaxis().SetRangeUser(-1.2, 1.2) histos[title_formatter.format(i)].GetYaxis().SetRangeUser(-1.2, 1.2) histos[title_formatter.format(i)].Draw('colz') vert.Draw() hori.Draw() label.DrawLatex(0.1, 0.925, '#Delta E_{beam} = E_{beam} - E_{pred}') label.DrawLatex(0.5, 0.015, xtitle) label.SetTextAngle(90) label.DrawLatex(0.045, 0.5, ytitle) label.SetTextAngle(0) canvas.Print(save_name)
def makePlot(mds, ds, pdf): """ Mass fit plot """ frame = mds.frame() ds.plotOn(frame, DataError(RooAbsData.SumW2), MarkerSize(1)) pdf.plotOn(frame, LineWidth(2)) # pull histogram pullHist = frame.pullHist() pullFrame = mds.frame(Title('')) pullFrame.addPlotable(pullHist, 'P') pullFrame.GetYaxis().SetRangeUser(-5, 5) canvas = TCanvas('m(Ds)', 'm(Ds)', 600, 700) canvas.cd() pad1 = TPad('pad1', 'pad1', .01, .20, .99, .99) pad2 = TPad('pad2', 'pad2', .01, .01, .99, .20) pad1.Draw() pad2.Draw() pad1.cd() pad1.SetLeftMargin(0.15) pad1.SetFillColor(0) frame.GetXaxis().SetTitleSize(0.05) frame.GetXaxis().SetTitleOffset(0.85) frame.GetXaxis().SetLabelSize(0.04) frame.GetYaxis().SetTitleOffset(1.6) frame.Draw() pad2.cd() pad2.SetLeftMargin(0.15) pad2.SetFillColor(0) pullFrame.SetMarkerSize(0.05) pullFrame.Draw() mdsRange = fitRange()['mDs'] lineUp = TLine(mdsRange[0], 3, mdsRange[1], 3) lineUp.SetLineColor(kBlue) lineUp.SetLineStyle(2) lineUp.Draw() lineCe = TLine(mdsRange[0], 0, mdsRange[1], 0) lineCe.SetLineColor(kBlue) lineCe.SetLineStyle(1) lineCe.SetLineWidth(2) lineCe.Draw() lineD0 = TLine(mdsRange[0], -3, mdsRange[0], -3) lineD0.SetLineColor(kBlue) lineD0.SetLineStyle(2) lineD0.Draw() canvas.Update()
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 plot_event_selection(canvas, histos, save_name, label): canvas.Clear() canvas.Divide(2, 1) histos['histos_w_in_ctof'].SetLineColor(1) histos['histos_w_pass_angle_in_ctof'].SetLineColor(1) histos['histos_w_pass_angle_in_ctof'].SetFillColorAlpha(64, 1.0) histos['histos_angle_ep'].SetLineColor(1) histos['histos_angle_ep_pass_w_in_ctof'].SetLineColor(1) histos['histos_angle_ep_pass_w_in_ctof'].SetFillColorAlpha(64, 1.0) histos['histos_w_in_ctof'].SetMinimum(0) histos['histos_w_pass_angle_in_ctof'].SetMinimum(0) # Fix missing bins histos['histos_w_in_ctof'].GetXaxis().SetRangeUser(0.7, 1.3) histos['histos_w_pass_angle_in_ctof'].GetXaxis().SetRangeUser(0.7, 1.3) wleft = TLine(0.8, histos['histos_w_in_ctof'].GetMinimum(), 0.8, 0.8 * histos['histos_w_in_ctof'].GetMaximum()) wright = TLine(1.08, histos['histos_w_in_ctof'].GetMinimum(), 1.08, 0.8 * histos['histos_w_in_ctof'].GetMaximum()) wleft.SetLineColor(99) wleft.SetLineWidth(1) wright.SetLineColor(99) wright.SetLineWidth(1) canvas.cd(1) histos['histos_w_in_ctof'].Draw() histos['histos_w_pass_angle_in_ctof'].Draw('same') wleft.Draw() wright.Draw() label.DrawLatex(0.1, 0.925, 'Electron (forward) and Proton (central)') label.DrawLatex(0.5, 0.015, 'W (GeV/c^{2})') label.DrawLatex(0.67, 0.86, '#color[64]{#phi_{ep} > 174}') canvas.cd(2) histos['histos_angle_ep'].Draw() histos['histos_angle_ep_pass_w_in_ctof'].Draw('same') left = TLine(174, 0.0, 174, 0.8 * histos['histos_angle_ep'].GetMaximum()) left.SetLineColor(99) left.SetLineWidth(1) left.Draw() label.DrawLatex(0.1, 0.925, 'Electron (forward) and Proton (central)') label.DrawLatex(0.5, 0.015, '#phi_{ep}') label.DrawLatex(0.57, 0.86, '#color[64]{W \in [0.8, 1.08]}') canvas.Print(save_name)
def addTRUGrid(subsystem, hist): """ Add a grid of TLines representing the TRU on a canvas. Note: Assumes that the canvas is already created. Note: Allocates a large number of TLines which have SetOwnership(obj, False), so this could lead to memory problems. """ # TEMP logger.debug("TRU Grid histName: {0}".format(hist.histName)) # Draw grid for TRUs in full EMCal SMs for x in range(8, 48, 8): line = TLine(x, 0, x, 60) SetOwnership(line, False) line.Draw() # 60 + 1 to ensure that 60 is plotted for y in range(12, 60 + 1, 12): line = TLine(0, y, 48, y) SetOwnership(line, False) line.Draw() # Draw grid for TRUs in 1/3 EMCal SMs line = TLine(0, 64, 48, 64) SetOwnership(line, False) line.Draw() line = TLine(24, 60, 24, 64) SetOwnership(line, False) line.Draw() # Draw grid for TRUs in 2/3 DCal SMs for x in range(8, 48, 8): if (x == 24): # skip PHOS hole continue line = TLine(x, 64, x, 100) SetOwnership(line, False) line.Draw() for y in range(76, 100, 12): line = TLine(0, y, 16, y) SetOwnership(line, False) line.Draw() # skip PHOS hole line = TLine(32, y, 48, y) SetOwnership(line, False) line.Draw() # Draw grid for TRUs in 1/3 DCal SMs line = TLine(0, 100, 48, 100) SetOwnership(line, False) line.Draw() line = TLine(24, 100, 24, 104) SetOwnership(line, False) line.Draw()
def addCuts(histdict, outdir): c_2D = TCanvas('c_2D', 'ISR photons theta versus Energy', 700, 500) c_2D.cd(1) histdict["h_ISR_Theta_vs_E"].Draw("colz") f1 = TF1("cutThetaPos", "1.48", -1., 200) f1.SetLineStyle(7) f1.SetLineColor(2) f1.Draw("same") f2 = TF1("cutThetaNeg", "-1.48", -1., 200) f2.SetLineStyle(7) f2.SetLineColor(2) f2.Draw("same") # gPad.DrawFrame(0, -3.5, 150, 3.5) cutE = TLine(0.2, -3.5, 0.2, 3.5) cutE.SetLineColor(2) cutE.SetLineStyle(7) cutE.Draw("same") outfilename = "{}.root".format(outdir) outfile = TFile(outfilename, "UPDATE") c_2D.Write("", TObject.kOverwrite) outfile.Write() outfile.Close()
def ROCMGDraw(TGraphArray, c1): c1.Clear() colorArray = [1, 2, 3, 4, 6, 7] AOC = 0 leg = TLegend(0.1, 0.7, 0.48, 0.9) mg = TMultiGraph() title_text = [] l_count = 0 for TGraphInstance, title in TGraphArray: print TGraphInstance, title TGraphInstance.SetLineColor(colorArray[l_count]) mg.Add(TGraphInstance) AOC = TGraphInstance.Integral(0, -1) + .5 leg.AddEntry(TGraphInstance, "{} AOC: {}".format(title, AOC)) title_text.append(title) l_count = l_count + 1 title_text = "_".join(title_text) yEqualsX = TLine(0, 0, 1, 1) yEqualsX.SetLineStyle(7) TH2F_range = TH2F("range_{}".format(title_text), "range_{}".format(title_text), 10, 0, 1, 10, 0, 1) TH2F_range.Draw() mg.Draw("AL") leg.Draw("L") yEqualsX.Draw() title_text = title_text.replace(" ", "_") c1.SaveAs("output/ROC_{}.png".format(title_text)) c1.Clear()
def makeROC(self, fillHistogramClass, c1): self.TH1F_ratio.SetLineColor(2) self.TH1F_ratio.Draw() fillHistogramClass.TH1F_ratio.SetLineColor(3) fillHistogramClass.TH1F_ratio.Draw("same") c1.SaveAs("output/ratio_{}_{}.png".format(self.name, fillHistogramClass.name)) #TGraph_ROC = TGraph("roc_{}_{}".format(self.name, fillHistogramClass.name), "roc_{}_{}".format(self.name, fillHistogramClass.name), ) integralSelf = self.TH1F_ratio.GetIntegral() integralExternal = fillHistogramClass.TH1F_ratio.GetIntegral() if (len(integralSelf) == len(integralExternal)): for i in range(self.nBins): binCount = i + 1 # print self.TH1F_ratio.GetXaxis().GetBinCenter(binCount) # #print fillHistogramClass.TH1F_ratio.GetXaxis().GetBinCenter(binCount) print "self", integralSelf[binCount] print "external", integralExternal[binCount] c1.Clear() yEqualsX = TLine(0, 0, 1, 1) yEqualsX.SetLineStyle(7) TGraph_ROC = TGraph(self.nBins + 1, integralSelf, integralExternal) TGraph_ROC.Draw() yEqualsX.Draw() c1.SaveAs("output/ROC_{}_{}.png".format(self.name, fillHistogramClass.name)) AOC = TGraph_ROC.Integral(0, -1) + .5 print " AOC ROC between {} and {}: {}".format( self.name, fillHistogramClass.name, AOC) else: print "not same length hists"
def write_spikeroothistogram(vectorspikes, histogramtitle, ytitle, rootdirectory, deltatime): """Function to perform ROOT histograms""" #Set ROOT histograms TH1Hist = TH1F(histogramtitle, "", 3, 0, 3) vectorspikes = [x[5:len(x)] for x in vectorspikes] #Fill histograms in for loop for entry in range(len(vectorspikes)): TH1Hist.Fill(vectorspikes[entry], 1. / (deltatime / 60)) #Draw + DrawOptions histograms c = TCanvas() c.SetName(histogramtitle + "_canvas") Style = gStyle Style.SetLineWidth(1) #TH1Hist Style.SetOptStat(0) #Show statistics gROOT.ForceStyle() TH1Hist.SetCanExtend(TH1.kAllAxes) TH1Hist.SetFillColor(38) TH1Hist.LabelsDeflate() TH1Hist.SetMinimum(0) TH1Hist.SetMaximum(2) YAxis = TH1Hist.GetYaxis() YAxis.SetTitle(ytitle) rootdirectory.WriteTObject(TH1Hist) line = TLine(0., 1.0, len(set(vectorspikes)), 1.0) line.SetLineStyle(2) line.SetLineColor(2) TH1Hist.Draw("histo") line.Draw() rootdirectory.WriteTObject(c)
def drawLine(x1, y1, x2, y2, color=1): line = TLine(x1, y1, x2, y2) line.SetLineStyle(2) line.SetLineWidth(2) line.SetLineColor(color) line.Draw() return line
def CheckToysTempFiles(sample='tW', histo='dnn'): path = baseoutpath%(year, ms, ml) f = TFile.Open(path+sample+ ('.root' if not sample.endswith('.root') else '')) hnom = f.Get(histo) nom = hnom.Integral() h = TH1F('h', 'h', 20, 0.24, 0.26) for i in range(nToys): ht = f.Get(histo+'_NormToy%i'%i) h.Fill(ht.Integral()) c = TCanvas('c', 'c', 10, 10, 1200, 800) h.SetStats(0) h.SetTitle('') h.GetXaxis().SetTitle("Yield %s"%sample) h.GetYaxis().SetTitle("Number of toys") h.SetLineWidth(2); h.SetLineColor(kOrange+1) h.SetFillColor(0) h.Draw('hist') l = TLine(nom, 0, nom, h.GetMaximum()) l.SetLineColor(kGray+3); l.SetLineWidth(2); l.SetLineStyle(2) l.Draw("same") name = 'toys_%s_%s'%(sample, histo) for form in ['png', 'pdf']: c.SaveAs(webpath+name+'.'+form)
def drawLine(xlow, ylow, xup, yup, lineWidth, lineStyle, lineColor): L1 = TLine(xlow, ylow, xup, yup) L1.SetLineWidth(lineWidth) L1.SetLineColor(lineColor) L1.SetLineStyle(lineStyle) L1.Draw("same") return L1
def overlayProfile(l_prof, l_axis, l_histo, l_legend, l_text, l_legInfo, saveAs, saveString): aString, xLabel, yLabel, xOffset, yOffset, aLabSize, aTextSize = l_axis hString, c_x, c_y, yMin, yMax, hBins, hFile = l_histo lString, l_x1, l_y1, l_x2, l_y2, l_textSize = l_legend t_str, plotText, t_textSize, t_alignment, t_start, t_gap, t_x = l_text l_bins = PythonUtils.makeListFromString(hBins, ';') gROOT.SetBatch(1) c = TCanvas('c', 'c', int(c_x), int(c_y)) gStyle.SetOptStat(0) c.SetTicks(1, 1) for i in xrange(len(l_prof)): if i == 0: l_prof[i].Draw('eps') setupAxes(l_prof[i], xLabel, yLabel, xOffset, yOffset, aTextSize, l_bins[0], l_bins[len(l_bins) -1], 1) l_prof[i].SetMinimum(float(yMin)) l_prof[i].SetMaximum(float(yMax)) l_prof[i].SetTitle('') hLine = TLine(l_prof[i].GetXaxis().GetXmin(), 1, l_prof[i].GetXaxis().GetXmax(), 1) hLine.SetLineWidth(2) hLine.SetLineColor(1) hLine.SetLineStyle(2) hLine.Draw('same') else: l_prof[i].Draw('eps same') setupTextOnPlot(plotText, t_textSize, t_alignment, t_x, t_start, t_gap) setupLegend(l_legInfo, l_x1, l_y1, l_x2, l_y2, l_textSize) savePlots(c, saveString, saveAs)
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 draw_line(lineList,x1,x2,y1,y2,width=1,style=1,color=1): from ROOT import TLine l=TLine(x1,y1,x2,y2) l.SetBit(ROOT.kCanDelete) l.SetLineWidth(width) l.SetLineStyle(style) l.SetLineColor(color) l.Draw() lineList.append(l)
def ratioplot(): # create required parts leg = getLegend() latex = getLatex() c = TCanvas() c.SetLogy() #Draw input histograms hists = ['h_frac_recoil_', 'h_full_recoil_'] label = ['recoil with MET triggers', 'recoil without MET triggers'] combineHist(hists, label, leg) #leg.Draw() #c.SaveAs("Combinehists_D.pdf") ratio = [] h1 = f.Get('h_frac_recoil_') #h1=setHistStyle(h1,bins) h2 = f.Get('h_full_recoil_') #h2=setHistStyle(h2,bins) h3 = createRatio(h1, h2) gr = TGraphAsymmErrors(h1, h2) gr.GetXaxis().SetRangeUser(0, 1500) gr.GetYaxis().SetRangeUser(0, 1.2) gr.SetMarkerStyle(20) gr.SetMarkerSize(0.5) gr.SetLineColor(1) gr.GetYaxis().SetTitle("Trigger Efficiency") gr.GetXaxis().SetTitle("Recoil [GeV]") gr.SetTitle("") # print ("ratio",ratio ) # c, pad1, pad2 = createCanvasPads() # # # draw everything # pad1.cd() # h1.Draw() # h2.Draw("same") # to avoid clipping the bottom zero, redraw a small axis # h1.GetYaxis().SetLabelSize(0.0) # axis = TGaxis(-5, 20, -5, 220, 20, 220, 510, "") # axis.SetLabelFont(43) # axis.SetLabelSize(15) # axis.Draw() # pad2.cd() gr.Draw() latex.DrawLatex(0.41, 0.93, "Trigger Efficincy in MET Run2017E") xmin = 0.0 line = TLine(max(xmin, gr.GetXaxis().GetXmin()), 1, 1500, 1) line.SetLineColor(1) line.SetLineWidth(1) line.SetLineStyle(7) line.Draw() #h3.Draw('pl') c.SaveAs("test.pdf")
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 PlotDeposit(hist, outname): from ROOT import TCanvas, gStyle, kBird, TLine gStyle.SetPalette(kBird) canvas = TCanvas('canvas', 'canvas', 800, 500) canvas.SetRightMargin(0.15) hist.GetXaxis().SetTitle("Depth from Calorimeter Center [mm]") hist.GetYaxis().SetTitle("#eta direction [mm]") hist.GetZaxis().SetTitle("Local Energy Deposit [MeV]") hist.Draw('colz') # taken from: https://github.com/jodafons/lorenzet/blob/master/src/SteppingAction.cc vertical_lines = [(150, 0, 150, 480), (450, 0, 450, 480), (480, 0, 480, 480), (880, 0, 880, 480), (1280, 0, 1280, 480)] first_em_layer = [] second_em_layer = [] third_em_layer = [] first_had_layer = [] second_had_layer = [] third_had_layer = [] # horizontal lines for y in range(0, 480, int(480 / 96)): # (x1,y,x2,y) first_em_layer.append((0, y, 150, y)) for y in range(0, 480, int(480 / 12)): # (x1,y,x2,y) second_em_layer.append((150, y, 450, y)) for y in range(0, 480, int(480 / 6)): # (x1,y,x2,y) third_em_layer.append((450, y, 480, y)) # horizontal lines for y in range(0, 480, int(480 / 8)): # (x1,y,x2,y) first_had_layer.append((480, y, 880, y)) for y in range(0, 480, int(480 / 8)): # (x1,y,x2,y) second_had_layer.append((880, y, 1280, y)) for y in range(0, 480, int(480 / 4)): # (x1,y,x2,y) third_had_layer.append((1280, y, 1480, y)) objects = [] for l in vertical_lines + first_em_layer + second_em_layer + third_em_layer + first_had_layer + second_had_layer + third_had_layer: obj = TLine(l[0], l[1], l[2], l[3]) obj.Draw('sames') objects.append(obj) #hist.GetXaxis().SetLimits(0,480) #hist.GetYaxis().SetLimits(0,480) canvas.SaveAs(outname)
def AddBinLines(can, hist, useHistMax=False, horizotalLine=1., lineStyle=2): tobject_collector = [] from ROOT import TH1, TGraph, THStack, TColor, kGray, kBlue, TLine, kRed if can.GetPrimitive('pad_top'): tobject_collector.extend( AddBinLines(can.GetPrimitive('pad_top'), hist, useHistMax, horizotalLine)) if can.GetPrimitive('pad_bot'): # TODO Move this to another function pad = GetBotPad(can) tobject_collector.extend(AddBinLines(pad, hist)) if horizotalLine is not None and pad.GetUymax( ) > horizotalLine > pad.GetUymin(): pad.cd() maxValue = pad.GetUxmax() minValue = pad.GetUxmin() l = TLine(minValue, horizotalLine, maxValue, horizotalLine) l.SetLineColor(kRed) l.SetLineStyle(2) l.Draw() tobject_collector.append(l) return tobject_collector can.cd() #listOfPlottedObjects = [o for o in can.GetListOfPrimitives() if isinstance(o,(TH1, THStack))] #listOfPlottedObjects += [o.GetHistogram() for o in can.GetListOfPrimitives() if isinstance(o,TGraph)] #if listOfPlottedObjects: #maxValue = max([o.GetBinContent(o.GetMaximumBin()) + o.GetBinError(o.GetMaximumBin()) for o in listOfPlottedObjects]) #minValue = min([o.GetBinContent(o.GetMinimumBin()) - o.GetBinError(o.GetMinimumBin()) for o in listOfPlottedObjects]) maxValue = hist.GetBinContent( hist.GetMaximumBin()) if useHistMax else can.GetUymax() minValue = can.GetUymin() for x in range(2, hist.GetXaxis().GetNbins() + 1): xv = hist.GetBinLowEdge(x) line = TLine(xv, minValue, xv, maxValue) line.SetLineColor(17) line.SetLineStyle(lineStyle) line.Draw() tobject_collector.append(line) return tobject_collector
def plot_sector_page_single(canvas, histos, title_formatter, save_name, xtitle=None, ytitle=None, title=None, x_range=None, log=False, hline=None): """ Plot one histogram for each sector. """ label = TLatex() label.SetNDC() label.SetTextSize(0.045) canvas.Clear() canvas.Divide(3, 2) root_garbage_can = [] for i in range(1, 7): canvas.cd(i) if x_range: histos.get(title_formatter.format(i), default_histo2d).GetXaxis().SetRangeUser( x_range[0], x_range[1]) histos.get(title_formatter.format(i), default_histo2d).Draw('colz') if log: gPad.SetLogz() if title: label.DrawLatex(0.1, 0.925, title) if xtitle: label.DrawLatex(0.45, 0.015, xtitle) if ytitle: label.SetTextAngle(90) label.DrawLatex(0.0325, 0.65, ytitle) label.SetTextAngle(0) if hline: xmin = histos.get(title_formatter.format(i)).GetXaxis().GetXmin() xmax = histos.get(title_formatter.format(i)).GetXaxis().GetXmax() line = TLine(xmin, hline, xmax, hline) line.SetLineColor(1) line.SetLineStyle(1) line.Draw('same') root_garbage_can.append(line) canvas.Print(save_name)
def gen_line_90(x, ymin, ymax, text): from ROOT import TLine, TLatex ymax = 1.05 * ymax l = TLine(x, ymin, x, ymax) l.SetLineStyle(2) l.Draw() txt = TLatex() txt.SetTextFont(12) txt.SetTextAngle(90) txt.SetTextSize(0.04) txt.DrawLatex(x - 1, (ymax - ymin) / 2., text) return l, txt
def evalDiode(): datalist = loadCSVToList('../data/part1/Kennlinie.txt') data = DataErrors() U0 = datalist[0][1] sU0 = 0.05 + 0.01 * U0 for I, u in datalist: U = u - U0 su = 5 + 0.01 * u sU = sqrt(su**2 + sU0**2) data.addPoint(I, U, 0.1, sU) xmin, xmax = 53, 71.5 c = TCanvas('c_diode', '', 1280, 720) g = data.makeGraph('g_diode', "Laserstrom I_{L} / mA", "Photodiodenspannung U_{ph} / mV") g.GetXaxis().SetRangeUser(-5, 90) g.SetMinimum(-50) g.SetMaximum(1400) g.Draw('APX') # y=0 line line = TLine(-5, 0, 90, 0) line.SetLineColor(OPData.CH2ECOLOR) line.Draw() data.filterX(xmin, xmax) g2 = data.makeGraph('g_diode_2', "Laserstrom I_{L} / mA", "Photodiodenspannung U_{ph} / mV") g2.SetMarkerColor(OPData.CH1COLOR) g2.SetLineColor(OPData.CH1COLOR) fit = Fitter('fit_diode', '[0] * (x-[1])') fit.function.SetNpx(1000) fit.setParam(0, 'a', 1) fit.setParam(1, 'I_{th}', 50) fit.fit(g2, 40, 77) fit.saveData('../fit/part1/kennlinie.txt') l = TLegend(0.15, 0.55, 0.4, 0.85) l.SetTextSize(0.03) l.AddEntry(g, 'Laserdiodenkennlinie', 'p') l.AddEntry(g2, 'Ausschnitt zum Fitten', 'p') l.AddEntry(fit.function, 'Fit mit U_{ph} = a (I_{ L} - I_{ th} )', 'l') fit.addParamsToLegend(l, (('%.1f', '%.1f'), ('%.2f', '%.2f')), chisquareformat='%.2f', units=['mV/mA', 'mA']) l.Draw() g.Draw('P') g2.Draw('P') c.Update() c.Print('../img/part1/diodenkennlinie.pdf', 'pdf')