def addEnergyAxisToPatches(subsystem, hist, processingOptions): """ Adds an additional axis showing the conversion from ADC counts to Energy. These conditions are set for "{EMCal,DCal}(Max)PatchAmp". It creates a new TGaxis that shows the ADC to Energy conversion. It then draws it on selected histogram. Warning: This function assumes that there is already a canvas created. Note: TGaxis removes ownership from Python to ensure that it continues to exist outside of the function scope. Args: hist (TH1): The histogram to be processed. Returns: None """ kEMCL1ADCtoGeV = 0.07874 # Conversion from EMCAL Level1 ADC to energy adcMin = hist.hist.GetXaxis().GetXmin() adcMax = hist.hist.GetXaxis().GetXmax() EMax = adcMax * kEMCL1ADCtoGeV EMin = adcMin * kEMCL1ADCtoGeV #yMax = gPad.GetUymax() # this function does not work here (log problem) yMax = 2 * hist.hist.GetMaximum() energyAxis = TGaxis(adcMin, yMax, adcMax, yMax, EMin, EMax, 510, "-") SetOwnership(energyAxis, False) energyAxis.SetTitle("Energy (GeV)") energyAxis.Draw()
def testIthr(): lines = get_lines('DAC_scan_ithr_0x40to0xf0.dat') gr1 = TGraphErrors() gr2 = TGraphErrors() fUnit = 1000. / 0.7 yUnit = 'e^{-}' for line in lines: if len(line) == 0: continue if line[0] in ['#', '\n']: continue fs = line.rstrip().split() ix = int(fs[0]) gr1.SetPoint(ix, float(fs[1]), float(fs[2]) * fUnit) gr1.SetPointError(ix, 0, float(fs[3]) * fUnit) gr2.SetPoint(ix, float(fs[1]), float(fs[4]) * fUnit) gr2.SetPointError(ix, 0, float(fs[5]) * fUnit) useAtlasStyle() gStyle.SetMarkerStyle(20) gr1.SetMarkerStyle(20) gr1.Draw('AP') h1 = gr1.GetHistogram() h1.GetYaxis().SetTitle("Threshold [" + yUnit + "]") h1.GetXaxis().SetTitle("I_{Thre} code") # h1.GetYaxis().SetRangeUser(0,0.2) gPad.SetTicks(1, 0) gPad.SetRightMargin(0.16) y1b = 0 y2b = 15 x1 = h1.GetXaxis().GetXmax() y1 = h1.GetYaxis().GetXmin() y2 = h1.GetYaxis().GetXmax() raxis = TGaxis(x1, y1, x1, y2, y1b, y2b, 506, "+L") raxis.SetLineColor(2) raxis.SetLabelColor(2) raxis.SetTitleColor(2) raxis.SetTitle("ENC [" + yUnit + "]") raxis.Draw() nP = gr2.GetN() Ys = gr2.GetY() EYs = gr2.GetEY() Y = array( 'd', [y1 + (y2 - y1) / (y2b - y1b) * (Ys[i] - y1b) for i in range(nP)]) EY = array('d', [(y2 - y1) / (y2b - y1b) * EYs[i] for i in range(nP)]) gr2x = TGraphErrors(nP, gr2.GetX(), Y, gr2.GetEX(), EY) gr2x.SetMarkerStyle(24) gr2x.SetLineColor(2) gr2x.SetMarkerColor(2) gr2x.Draw('Psame') waitRootCmdX()
def addVerticalAxis(self, title, ymin, ymax): self.yaxis2 = TGaxis(self.xmax, self.ymin, self.xmax, self.ymax, ymin, ymax, 510, "+L") self.yaxis2.SetName("axis") self.yaxis2.SetLabelOffset(0.01) self.yaxis2.SetTitle(title) self.yaxis2.Draw() self.ymin2 = ymin self.ymax2 = ymax return self.yaxis2
def get_rank_section(directory): # do Rank histo png imgname = "RankSummary.png" gStyle.SetPadTickY(0) c = TCanvas("ranks", "ranks", 500, 400) #gStyle.SetOptStat(0) c.cd() h = directory.rank_histo rank_histof = TH1F(h.GetName(), "", h.GetNbinsX(), h.GetXaxis().GetXmin(), h.GetXaxis().GetXmax()) rank_histof.SetLineWidth(2) for i in xrange(0, h.GetNbinsX() + 1): rank_histof.SetBinContent(i, h.GetBinContent(i)) h.SetTitle("Ranks Summary;Rank;Frequency") h.Draw("Hist") c.Update() rank_histof.ComputeIntegral() integral = rank_histof.GetIntegral() rank_histof.SetContent(integral) rightmax = 1.1 * rank_histof.GetMaximum() scale = gPad.GetUymax() / rightmax rank_histof.SetLineColor(kRed) rank_histof.Scale(scale) rank_histof.Draw("same") #draw an axis on the right side axis = TGaxis(gPad.GetUxmax(), gPad.GetUymin(), gPad.GetUxmax(), gPad.GetUymax(), 0, rightmax, 510, "+L") axis.SetTitle("Cumulative") axis.SetTitleColor(kRed) axis.SetLineColor(kRed) axis.SetLabelColor(kRed) axis.Draw() rank_histof.Draw("Same") c.Print(imgname) page_html = '<div class="span-20"><h2 class="alt"><a name="rank_summary">Ranks Summary</a></h2>' page_html += '<div class="span-19"><img src="%s"></div>' % imgname page_html += '</div> <a href="#top">Top...</a><hr>' return page_html
def ratioplot(): # create required parts h1 = createH1() h2 = createH2() h3 = createRatio(h1, h2) 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() h3.Draw("ep")
def make_comparison_plot(outdir, var, groupname1, groupname2, category, weight = "PU_weight*MC_weight*bTagSF_weight*leptonSF_weight*triggerSF_weight*FR_weight", dataset = "ttH"): var_name = var[0] n_bins = var[3] range_low = var[4] range_high = var[5] histos = [] plot_name = "p" #segfault when using different names for each #"%s_%s_%s_%s_%s_vs_%s" % (outdir, var_name, dataset, category, groupname1, groupname2) name1 = "plot_%s_%s" % (groupname1, plot_name) plot1 = single_plot("%s/%s" % (groups[groupname1]["inputPath"], groups[groupname1]["inputFiles"][dataset]), name1, "%s_%s" % (groups[groupname1]["treePrefix"], category), var_name, weight, n_bins, range_low, range_high) name2 = "plot_%s_%s" % (groupname2, plot_name) plot2 = single_plot("%s/%s" % (groups[groupname2]["inputPath"], groups[groupname2]["inputFiles"][dataset]), name2, "%s_%s" % (groups[groupname2]["treePrefix"], category), var_name, weight, n_bins, range_low, range_high) histos.append(plot1) histos.append(plot2) leg_entry = [] leg_entry.append("%s:\t N=%d, mean=%.2f, RMS=%.2f" % (groupname1, plot1.GetEntries(), plot1.GetMean(), plot1.GetRMS())) leg_entry.append("%s:\t N=%d, mean=%.2f, RMS=%.2f" % (groupname2, plot2.GetEntries(), plot2.GetMean(), plot2.GetRMS())) leg=TLegend(0.45,0.74,0.85,0.89) leg.SetHeader(get_header(category)); leg.SetBorderSize(0) leg.SetTextSize(0.04) leg.SetFillColor(0) for i in range(len(histos)): normalize_histogram(histos[i]) leg.AddEntry(histos[i], leg_entry[i]) histos[0].SetLineColor(ROOT.kOrange-2) histos[0].SetFillColor(ROOT.kOrange-2) histos[0].SetStats(0) histos[0].SetTitle("") histos[1].SetLineColor(1) histos[1].SetLineWidth(2) c=TCanvas("c_%s" % plot_name,"c_%s" % plot_name, 800, 600) pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.SetLeftMargin(0.15) pad1.SetBottomMargin(0) # Upper and lower plot are joined pad1.Draw() # Draw the upper pad: pad1 pad1.cd() # pad1 becomes the current pad max_val = 0.1 min_val = 0 for i in range(len(histos)): max_val = max(histos[i].GetMaximum(), max_val) min_val = min(histos[i].GetMinimum(), min_val) for i in range(len(histos)): histos[i].SetMaximum(1.4*max_val) histos[i].SetMinimum(1.4*min_val) histos[i].GetXaxis().SetTitle(var_name) histos[i].GetYaxis().SetTitle("a.u.") histos[i].GetYaxis().SetTitleOffset(1.7) #histos[i].GetYaxis().SetTickLength(0) #histos[i].GetYaxis().SetLabelOffset(999) texl = TLatex(histos[0].GetBinLowEdge(1), 1.01*1.4*max_val, "CMS Preliminary, Simulation ttH #sqrt{s}=13 TeV") texl.SetTextSize(0.04) texl.Draw("same") histos[0].Draw("hist") histos[1].Draw("same") leg.Draw("same") texl.Draw("same") histos[0].GetYaxis().SetLabelSize(0.) axis = TGaxis(range_low, min_val, range_low, max_val, min_val, max_val, 510, "") axis.SetLabelFont(43) #Absolute font size in pixel (precision 3) axis.SetLabelSize(15) axis.Draw() # lower plot will be in pad c.cd() # Go back to the main canvas before defining pad2 pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3) pad2.SetLeftMargin(0.15) pad2.SetTopMargin(0) pad2.SetBottomMargin(0.35) pad2.Draw() pad2.cd() h_ratio = make_ratio_histogram("h_ratio", histos[1], histos[0]) """ h_ratio = h[1].Clone("h_ratio") """ h_ratio.SetTitle("") h_ratio.Draw() #Draw the ratio plot # Y axis histo_emul plot settings histos[0].GetYaxis().SetTitleSize(20) histos[0].GetYaxis().SetTitleFont(43) histos[0].GetYaxis().SetTitleOffset(1.5) # Ratio plot (h_ratio) settings #h_ratio.SetTitle("") # Remove the ratio title h_ratio.GetYaxis().SetLabelSize(0.) axis2 = TGaxis( range_low, 0.01, range_low, 1.99, 0.01, 1.99, 505,"") axis2.SetLabelFont(43) # Absolute font size in pixel (precision 3) axis2.SetLabelSize(15) axis2.Draw() # Y axis ratio plot settings h_ratio.GetYaxis().SetTitle("%s/%s" % (groupname2, groupname1)) h_ratio.GetYaxis().SetNdivisions(505) h_ratio.GetYaxis().SetTitleSize(20) h_ratio.GetYaxis().SetTitleFont(43) h_ratio.GetYaxis().SetTitleOffset(1.5) #h_ratio.GetYaxis().SetLabelFont(43) # Absolute font size in pixel (precision 3) #h_ratio.GetYaxis().SetLabelSize(15) # X axis ratio plot settings h_ratio.GetXaxis().SetTitleSize(20) h_ratio.GetXaxis().SetTitleFont(43) h_ratio.GetXaxis().SetTitleOffset(4.) h_ratio.GetXaxis().SetLabelFont(43) # Absolute font size in pixel (precision 3) h_ratio.GetXaxis().SetLabelSize(15) line = TLine(range_low, 1., range_high,1.) line.Draw("same") plot_file_name="%s" % (var_name) dirname = ("%s_vs_%s/%s/%s" % (groupname1, groupname2, category, outdir)).replace(" ", "_") for file_format in ["png", "pdf"]: mkdir_p("plots_test/%s/%s" % (dirname, file_format)) c.SaveAs("plots_test/%s/%s/%s.%s" % (dirname, file_format, plot_file_name, file_format))
texts[-2].SetTextColor(level['color']) lines[-1].SetLineColor(level['color']) if 'life' in level: texts.append( TText( xcenter, level['energy'] + 2 * param['TextFloat'] + (plot_range['ymax'] - plot_range['ymin']) * param['TextSize'], str(level['life']))) texts[-1].SetTextAlign(21) texts[-1].SetTextColor(texts[-2].GetTextColor()) if 'Axis' in param: paxis = param['Axis'] axis_margin = 0.015 * (plot_range['ymax'] - plot_range['ymin']) axis = TGaxis(-param['space'], paxis['range_min'], -param['space'], paxis['range_max'], paxis['range_min'], paxis['range_max'], paxis['ticks'], "") axis.SetTitle(paxis['title']) axis.SetLabelSize(paxis['label_size']) axis.SetTitleSize(paxis['title_size']) axis.SetTitleOffset(paxis['title_offset']) axis.Draw() for line in lines: line.SetLineWidth(param['LineWidth']) line.Draw() for text in texts: text.SetTextSize(param['TextSize']) text.Draw()
c_allmases.cd(3) ymax = 1. graph_pratio_allmases.Draw("AP") graph_pratio_allmases.GetXaxis().SetTitle("Nr of tracks") graph_pratio_allmases.GetYaxis().SetTitle("<ratio>") graph_pratio_allmases.GetYaxis().SetRangeUser(0., ymax) graph_pratio_allmases.Draw("AP") graph_ntr_allmases.Draw("*") leg_all = TLegend(0.65, 0.35, 0.9, 0.55) leg_all.AddEntry(graph_pratio_allmases, "pratio", "l") leg_all.AddEntry(graph_ntr_allmases, "number of tracks", "p") leg_all.SetTextSize(0.015) leg_all.Draw() axis = TGaxis(10.8, 0., 10.8, ymax, 0, ymax * rightmax / leftmax, 510, "+L") axis.SetLineColor(2) axis.SetLabelColor(2) axis.Draw() c_allmases.cd(4) zmax = 0.07 graph_deltar_allmases.Draw("AP") graph_deltar_allmases.GetXaxis().SetTitle("Nr of tracks") graph_deltar_allmases.GetYaxis().SetTitle("deltaR") graph_deltar_allmases.GetYaxis().SetRangeUser(0., zmax) graph_deltar_allmases.Draw("AP") graph_ntr_allmases2.Draw("*") axis2 = TGaxis(10.8, 0., 10.8, zmax, 0, zmax * rightmax2 / leftmax2, 510, "+L") axis2.SetLineColor(2)
def doTH1Plots(datasets, TH1List, signifCutDirection=None): # Loop over all hName and expressions in the histogram list. Create & Draw plot counter = 0 for h in TH1List: print "*** Processing histo", h.name hName = h.name units = h.units xLabel = h.xlabel bLogX = h.bLogX binWidthX = h.binWidthX yLabel = h.ylabel bLogY = h.bLogY bRatio = h.bRatio bNormalizeToOne = h.bNormalizeToOne xLegMin = h.xLegMin xLegMax = h.xLegMax yLegMin = h.yLegMin yLegMax = h.yLegMax # Create customised legend histograms.createLegend.setDefaults(x1=xLegMin, x2=xLegMax, y1=yLegMin, y2=yLegMax) # Create the plot p = createTH1Plot(datasets, hName, normalizeToOne=bNormalizeToOne) xAxis = TGaxis() if "Discriminant" in h.name: xAxis.SetMaxDigits(3) else: xAxis.SetMaxDigits(6) # Customise the plot drawPlot = getCustomisedHisto(datasets, h, False) # Determine name of file that histos will be saved to according to the user-options saveName = getFullSaveName(datasets, histoName="TH1_%s" % (hName), dataEra=myDataEra, bNormalized=bNormalizeToOne, bStackedHistos=bStackHistos) # Draw the plot drawPlot(p, saveName, xlabel=xLabel, ylabel=yLabel, rebinToWidthX=binWidthX, cutLine=getHistoCutLines(h)) if len(signifCutDirection) != 0: doBinSignifPlots(p, drawPlot, datasets, h, hName, xLabel, yLabel, saveName) for cutDir in signifCutDirection: if (cutDir == ">" or cutDir == "<"): doSignifPlots(p, drawPlot, datasets, h, hName, xLabel, yLabel, saveName, cutDir) return
simple_nue.SetStats(0) rebin_nue.SetLineColor(38) simple_nue.SetLineColor(46) rebin_nue.SetLineWidth(6) simple_nue.SetLineWidth(6) simple_nue.GetXaxis().SetRangeUser(0, 4) rebin_nue.GetXaxis().SetRangeUser(0, 4) simple_nue.Draw("hist") rebin_nue.Draw("hist same") # Do not draw the Y axis label on the upper plot and redraw a small # axis instead, in order to avoid the first label (0) to be clipped. rebin_nue.GetYaxis().SetLabelSize(0.) axis = TGaxis(-5, 20, -5, 220, 20, 220, 510, "") axis.SetLabelFont(43) # Absolute font size in pixel (precision 3) axis.SetLabelSize(15) axis.Draw() leg_nue = TLegend(0.75, 0.95, 0.75, 0.95) leg_nue.AddEntry(simple_nue, "nue gSimple Flux", "l") leg_nue.AddEntry(rebin_nue, "nue dk2nu Flux", "l") leg_nue.Draw() c6.cd() pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3) pad2.SetTopMargin(0.1) pad2.SetBottomMargin(0.1) pad2.SetGridx() # vertical grid pad2.Draw()
hRawYieldDistr.append( inFileMT.Get(f'hRawYield_pT_{ptMin*10:.0f}-{ptMax*10:.0f}')) rms = hRawYieldDistr[-1].GetRMS() / hRawYieldDistr[-1].GetMean() * 100 shift = TMath.Abs( hRawYields.GetBinContent(iPt) - hRawYieldDistr[-1].GetMean()) / hRawYieldDistr[-1].GetMean() * 100 syst = TMath.Sqrt(rms**2 + shift**2) hRMS.SetBinContent(iPt, rms) hMeanShift.SetBinContent(iPt, shift) hSyst.SetBinContent(iPt, syst) cRMS = TCanvas('cRMS', '', 800, 800) cRMS.DrawFrame(hRMS.GetBinLowEdge(1), 0.1, ptMax, 20., ';#it{p}_{T} (GeV/#it{c});RMS (%)') hRMS.DrawCopy('same') axisSoverB = TGaxis(gPad.GetUxmax(), gPad.GetUymin(), gPad.GetUxmax(), gPad.GetUymax(), 0.01, 20., 510, "+LG") axisSoverB.SetLineColor(kRed + 1) axisSoverB.SetLabelColor(kRed + 1) axisSoverB.SetLabelFont(42) axisSoverB.SetLabelSize(0.045) axisSoverB.SetTitle('S/B (3#sigma)') axisSoverB.SetTitleOffset(1.2) axisSoverB.SetLabelOffset(0.012) axisSoverB.SetTitleColor(kRed + 1) axisSoverB.SetTitleFont(42) axisSoverB.SetTitleSize(0.05) axisSoverB.SetMaxDigits(3) axisSoverB.Draw() hSoverB.DrawCopy('same') cRMS.Update()
gr_plus.SetMarkerSize(3) gr_plus.SetMarkerStyle(20) gr_plus.SetMarkerColor(2) gr_minus.SetLineColor(4) gr_minus.SetLineWidth(4) gr_minus.SetMarkerSize(3) gr_minus.SetMarkerStyle(21) gr_minus.SetMarkerColor(4) gr_plus.Draw("ep same") gr_minus.Draw("ep same") canvas.Update() axis = TGaxis(ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymin(), ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymax(), 0, 2, 510, "+L") axis.SetTitle("Temperature (before - after) [degC]") axis.SetTitleOffset(1.5) axis.SetTitleFont(42) axis.SetLineColor(6) axis.SetTextColor(6) axis.SetLabelFont(42) axis.Draw() gr_temp.SetLineColor(6) gr_temp.SetLineWidth(4) gr_temp.SetMarkerSize(3) gr_temp.SetMarkerStyle(22) gr_temp.SetMarkerColor(6)
def makeTwoScalesGraph(file): print(file) ch1 = OPData.fromPath('../data/part3/%s' % file, 1) ch2 = OPData.fromPath('../data/part3/%s' % file, 2) print('make canvas + pad') c = TCanvas('c-%s' % file, '', 1280, 720) pad = TPad('pad-%s' % file, '', 0, 0, 1, 1) pad.Draw() pad.cd() print('frame') frame = pad.DrawFrame(0, min(ch1.getY()) * 1.1, 0.051, max(ch1.getY()) * 1.1) frame.SetXTitle('Zeit t / s') frame.GetXaxis().CenterTitle() frame.SetYTitle('Spannung Spule 2: U_{2} / V') frame.GetYaxis().CenterTitle() frame.GetYaxis().SetLabelColor(4) frame.GetYaxis().SetTitleColor(4) print('g1') g1 = ch1.makeGraph('g1-%s' % file) prepareGraph(g1) g1.Draw('PX') print('overlay') c.cd() overlay = TPad('overlay-%s' % file, '', 0, 0, 1, 1) overlay.SetFillStyle(4000) # transparent overlay.SetFillColor(0) # white overlay.SetFrameFillStyle(4000) # transparent overlay.Draw() overlay.cd() print('g2') g2 = ch2.makeGraph('g2-%s' % file) prepareGraph(g2, 2) g2ymin = min(ch2.getY()) xmin = pad.GetUxmin() xmax = pad.GetUxmax() ymin = 1.1 * g2ymin ymax = abs(ymin) if file == '07.tab': # same scale like 06.tab ymin, ymax = -0.07128, 0.07128 oframe = overlay.DrawFrame(xmin, ymin, xmax, ymax) oframe.GetXaxis().SetLabelOffset(99) oframe.GetYaxis().SetLabelOffset(99) oframe.GetYaxis().SetTickLength(0) g2.Draw('PX') print('axis') axis = TGaxis(xmax, ymin, xmax, ymax, ymin, ymax, 510, "+L") axis.SetTitle('Spannung Photodiode: U_{ph} / V') axis.CenterTitle() axis.SetTitleOffset(1.2) axis.Draw() print('print') c.Update() c.Print('../img/part3/%s.pdf' % file[:-4], 'pdf')
def makeBeamspotCutPlots(name, points): nPoints = len(points) x = TGraphErrors(nPoints) x.SetName(name) x.SetTitle(name + " x; lb; x [mm]") y = TGraphErrors(nPoints) y.SetName(name) y.SetTitle(name + " y; lb; y [mm]") z = TGraphErrors(nPoints) z.SetName(name) z.SetTitle(name + " z; lb; z [mm]") sx = TGraphErrors(nPoints) sx.SetName(name) sx.SetTitle(name + " sx; lb; #sigma(x) [mm]") sy = TGraphErrors(nPoints) sy.SetName(name) sy.SetTitle(name + " sy; lb; #sigma(y) [mm]") sz = TGraphErrors(nPoints) sz.SetName(name) sz.SetTitle(name + " sz; lb; #sigma(z) [mm]") xrms = TGraphErrors(nPoints) xrms.SetName(name + "_rms") xrms.SetTitle(name + "_rms" + " x") yrms = TGraphErrors(nPoints) yrms.SetName(name + "_rms") yrms.SetTitle(name + "_rms" + " y") zrms = TGraphErrors(nPoints) zrms.SetName(name + "_rms") zrms.SetTitle(name + "_rms" + " z") sxrms = TGraphErrors(nPoints) sxrms.SetName(name + "_rms") sxrms.SetTitle(name + "_rms" + " sx") syrms = TGraphErrors(nPoints) syrms.SetName(name + "_rms") syrms.SetTitle(name + "_rms" + " sy") szrms = TGraphErrors(nPoints) szrms.SetName(name + "_rms") szrms.SetTitle(name + "_rms" + " sz") graphs.extend([x, y, z, sx, sy, sz, xrms, yrms, zrms, sxrms, syrms, szrms]) print len(points) for i in range(len(points)): xval = points[i][0] yvals = points[i][1] xerr = 0 x.SetPoint(i, xval, yvals[0][0]) y.SetPoint(i, xval, yvals[1][0]) z.SetPoint(i, xval, yvals[2][0]) sx.SetPoint(i, xval, yvals[3][0]) sy.SetPoint(i, xval, yvals[4][0]) sz.SetPoint(i, xval, yvals[5][0]) x.SetPointError(i, xerr, yvals[0][1]) y.SetPointError(i, xerr, yvals[1][1]) z.SetPointError(i, xerr, yvals[2][1]) sx.SetPointError(i, xerr, yvals[3][1]) sy.SetPointError(i, xerr, yvals[4][1]) sz.SetPointError(i, xerr, yvals[5][1]) xrms.SetPoint(i, xval, yvals[0][2]) yrms.SetPoint(i, xval, yvals[1][2]) zrms.SetPoint(i, xval, yvals[2][2]) sxrms.SetPoint(i, xval, yvals[3][2]) syrms.SetPoint(i, xval, yvals[4][2]) szrms.SetPoint(i, xval, yvals[5][2]) xrms.SetPointError(i, xerr, yvals[0][3]) yrms.SetPointError(i, xerr, yvals[1][3]) zrms.SetPointError(i, xerr, yvals[2][3]) sxrms.SetPointError(i, xerr, yvals[3][3]) syrms.SetPointError(i, xerr, yvals[4][3]) szrms.SetPointError(i, xerr, yvals[5][3]) c = TCanvas("cx") c.Divide(3, 1) c.cd(1) x.Draw("ap") c.cd(2) y.Draw("ap+Y+") c.cd(3) yaxis_xrms = TGaxis(-1, 0.2, 1, 0.2, -1, 2, 510, "+R") yaxis_xrms.ImportAxisAttributes(y.GetHistogram().GetYaxis()) #g = TMultiGraph() #g.Add(x,"aXp") #g.Add(y,"aY*") #g.Draw("a") # graphs.append(g) # aa = y.GetHistogram() #x.Draw("ap") yaxis_xrms.Draw() #axis.PaintAxis(0,0.5,0.1,0.6,0.4,1.4,510,"+R") #y.Draw("pY+sames") #b.Draw("sames") c.Modified() c.Update() #c.Print() canvases.append(c)
def PlotOnCanvas(self,pdf_name): tdrstyle.setTDRStyle() canvas = TCanvas("c", "c", 600, 600) pad1 = TPad("pad1", "pad1", 0, 0.0, 1, 1.0) pad1.SetTopMargin(0.15) pad1.SetBottomMargin(0.32) pad1.SetRightMargin(0.05) pad1.SetLeftMargin(0.15) if self.title == '': pad1.SetTopMargin(0.05) pad1.SetGridx() pad1.Draw() pad1.cd() self.histo1.SetStats(0) self.histo1.Draw(self.option) self.histo2.Draw(self.option+" same") if self.logx: pad1.SetLogx() if self.logy: pad1.SetLogy() # Redraw axis to avoid clipping 0 self.histo1.GetXaxis().SetLabelSize(0.) self.histo1.GetXaxis().SetTitle('') axis = TGaxis(-9,-2.8,-9,2.8,0,10000,50510,"") axis.SetLabelFont(43) axis.SetLabelSize(15) axis.Draw("same") pad2 = TPad("pad2", "pad2", 0, 0.0, 1, 0.3) pad2.SetTopMargin(0) pad2.SetBottomMargin(0.4) pad2.SetRightMargin(0.05) pad2.SetLeftMargin(0.15) pad2.SetGridx() pad2.Draw() pad2.cd() if self.logx: pad2.SetLogx() self.ratio.SetLineColor(ROOT.kBlack) self.ratio.SetMinimum(0.5) self.ratio.SetMaximum(1.5) self.ratio.SetStats(0) self.ratio.SetMarkerStyle(21) self.ratio.Draw("ep") self.histo1.SetLineColor(ROOT.kBlue+1) self.histo1.SetLineWidth(2) max_y = max(self.histo1.GetMaximum(),self.histo2.GetMaximum()) self.histo1.SetMaximum(max_y*1.1) self.histo1.GetXaxis().SetTitleOffset(1.5) self.histo1.GetXaxis().SetLabelSize(0.) self.histo1.GetXaxis().SetTitleSize(0.) self.histo1.GetYaxis().SetTitleOffset(1.5) self.histo1.GetYaxis().SetLabelSize(0.03) self.histo1.GetYaxis().SetTitleSize(0.05) self.histo1.GetYaxis().SetNdivisions(505) self.histo2.SetLineColor(ROOT.kRed) self.histo2.SetLineWidth(2) self.ratio.SetTitle("") self.ratio.GetXaxis().SetNdivisions(510) self.ratio.GetXaxis().SetTitleOffset(1.1) self.ratio.GetXaxis().SetLabelSize(0.10) self.ratio.GetXaxis().SetTitleSize(0.15) if len(self.xlabel) > 30: self.ratio.GetXaxis().SetTitleSize(0.13) if len(self.xlabel) > 60: self.ratio.GetXaxis().SetTitleSize(0.11) self.ratio.GetYaxis().SetTitle("Ratio") self.ratio.GetYaxis().SetNdivisions(505) self.ratio.GetYaxis().SetTitleOffset(0.5) self.ratio.GetYaxis().SetLabelSize(0.10) self.ratio.GetYaxis().SetTitleSize(0.15) if len(self.ylabel) > 30: self.ratio.GetYaxis().SetTitleSize(0.13) if len(self.ylabel) > 60: self.ratio.GetYaxis().SetTitleSize(0.11) # Legend # canvas.cd() if self.title == '': self.legend = TLegend(0.60,0.80,0.93,0.93) else: self.legend = TLegend(0.60,0.70,0.93,0.83) self.legend.SetTextSize(0.05) self.legend.SetBorderSize(0) self.legend.SetFillColor(0) self.legend.AddEntry(self.histo1,self.legend1,"l") self.legend.AddEntry(self.histo2,self.legend2,"l") self.legend.Draw() ROOT.SetOwnership(canvas, False) ROOT.SetOwnership(pad1, False) ROOT.SetOwnership(pad2, False) return canvas,self.filename
ctau_cms_8TeV_1g) graph_exclusion_cms_8TeV_1g.SetFillColorAlpha(kAzure + 10, 0.65) graph_exclusion_cms_8TeV_1g.SetLineColorAlpha(kAzure + 10, 0.65) ######CMS 8TeV, two photons mass_cms_8TeV_2g = np.array([198., 227., 256., 256., 227., 198.]) ctau_cms_8TeV_2g = 0.01 * np.array([0.4, 2, 9, 9, 25., 50.]) graph_exclusion_cms_8TeV_2g = TGraph(6, mass_cms_8TeV_2g, ctau_cms_8TeV_2g) graph_exclusion_cms_8TeV_2g.SetFillColorAlpha(kGray, 0.6) graph_exclusion_cms_8TeV_2g.SetLineColorAlpha(kGray, 0.6) ####legend #Lambda axis f1_lambda = TF1("f1", "(x+6.00)/1.454", 72.902, 416.78) A1_lambda = TGaxis(100.0, 0.0125, 600.0, 0.0125, "f1", 1010, "NI") A1_lambda.SetLabelFont(42) A1_lambda.SetLabelSize(0.035) A1_lambda.SetTextFont(42) A1_lambda.SetTextSize(1.3) A1_lambda.SetTitle("#Lambda (TeV)") A1_lambda.SetTitleSize(0.04) A1_lambda.SetTitleOffset(0.9) ### only graph_exclusion_exp_ = TGraph( len(lambda_point_boundary_exp_), np.array(1.454 * lambda_point_boundary_exp_ - 6.0), 0.01 * np.array(ctau_points)) graph_exclusion_exp_p1sig_ = TGraph( len(lambda_point_boundary_exp_p1sig_),
def plot_ratio(ih_,max_val_,xbins__,comb_ID_): # // Define two gaussian histograms. Note the X and Y title are defined # // at booking time using the convention "Hist_title ; X_title ; Y_title" # TH1F *h1 = new TH1F("h1", "Two gaussian plots and their ratio;x title; h1 and h2 gaussian histograms", 100, -5, 5); # TH1F *h2 = new TH1F("h2", "h2", 100, -5, 5); # h1.FillRandom("gaus"); # h2.FillRandom("gaus"); # // Define the Canvas #TCanvas *c = new TCanvas("c", "canvas", 800, 800); cc = TCanvas("cc", "canvas", 800, 800) h1 = ih_[0][0] h2 = ih_[1][0] #print 'h1 = ',h1 #print 'h2 = ',h2 #print'h1.GetMaximum() = ' ,h1.GetMaximum() #// Upper plot will be in pad1 pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.SetBottomMargin(0) # Upper and lower plot are joined #pad1.SetGridx() #Vertical grid, dashed lines pad1.Draw() #Draw the upper pad: pad1 pad1.cd() # pad1 becomes the current pad h1.SetStats(0) # No statistics on upper plot h1.GetXaxis().SetNdivisions(xbins__) h1.Draw() # Draw h1 # pad1.Update() # lline = TLine(pad1.GetUxmin(),20,pad1.GetUxmax(),20) # #lline.SetNDC(1) # lline.SetLineStyle(3) # lline.Draw('same') h2.Draw("same") # Draw h2 on top of h1 # // Do not draw the Y axis label on the upper plot and redraw a small # // axis instead, in order to avoid the first label (0) to be clipped. h1.GetYaxis().SetLabelSize(0.) #TGaxis *axis = new TGaxis( -5, 20, -5, 220, 20,220,510,""); #axis = TGaxis( -5, 20, -5, 220, 20,220,510,"") #xmin ymin xmax ymax axis = TGaxis( 0, 0, 0, max_val_, 0.001,max_val_,510,"") axis.SetLabelFont(43) #Absolute font size in pixel (precision 3) axis.SetLabelSize(15) axis.Draw() #lower plot will be in pad cc.cd() # Go back to the main canvas before defining pad2 #TPad *pad2 = new TPad("pad2", "pad2", 0, 0.05, 1, 0.3) pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3) pad2.SetTopMargin(0) # can change to separate top and bottom #pad2.SetBottomMargin(0.2) #pad2.SetBottomMargin(0) #pad2.SetGridx() # vertical grid, dashed lines pad2.Draw() pad2.cd() # pad2 becomes the current pad # Define the ratio plot #TH1F *h3 = (TH1F*)h1.Clone("h3"); h3 = h2.Clone("h3") h3.SetLineColor(1) h3.SetMinimum(0.5) # Define Y .. h3.SetMaximum(1.5) # .. range h3.Sumw2() h3.SetStats(0) # No statistics on lower plot h3.Divide(h1) h3.SetMarkerStyle(21) #gPad.Modified() #gPad.Update() h3.Draw("ep") # Draw the ratio plot pad2.Update() lline = TLine(pad2.GetUxmin(),1,pad2.GetUxmax(),1) #lline.SetNDC(1) lline.SetLineStyle(1) lline.Draw('same') #// h1 settings h1.SetLineColor(600+1) h1.SetLineWidth(2) #// Y axis h1 plot settings h1.GetYaxis().SetTitleSize(20) h1.GetYaxis().SetTitleFont(43) h1.GetYaxis().SetTitleOffset(1.55) #print 'xbins__ = ',xbins__ h1.GetXaxis().SetNdivisions(xbins__) #h1.GetXaxis().SetNdivisions(0) #// h2 settings h2.SetLineColor(632) h2.SetLineWidth(2) # // Ratio plot (h3) settings h3.SetTitle("") # Remove the ratio title #// Y axis ratio plot settings h3.GetYaxis().SetTitle("Reco/Gen") h3.GetYaxis().SetNdivisions(505) h3.GetYaxis().SetTitleSize(20) h3.GetYaxis().SetTitleFont(43) h3.GetYaxis().SetTitleOffset(1.55) h3.GetYaxis().SetLabelFont(43) #Absolute font size in pixel (precision 3) h3.GetYaxis().SetLabelSize(15) # // X axis ratio plot settings #h3.GetXaxis().SetNdivisions(xbins__) h3.GetXaxis().SetNdivisions(xbins__) #h3.GetXaxis().SetNdivisions(0) h3.GetXaxis().SetTitleSize(20) h3.GetXaxis().SetTitleFont(43) h3.GetXaxis().SetTitleOffset(4.) h3.GetXaxis().SetLabelFont(43) # Absolute font size in pixel (precision 3) h3.GetXaxis().SetLabelSize(15) pad1.cd() leg_ = TLegend(0.6, 0.75, 0.89, 0.89) #for hi_,h_ in enumerate(hists_): a = ih_[:] #print'a = ',a #for i,hist_info_ in enumerate(a): for hist_info_ in a: this_h = hist_info_[0] this_label = hist_info_[1] leg_.AddEntry(this_h,this_label,'lf') # histo object, ID #leg.SetTextSize(0.02) leg_.Draw('same') #cc.SaveAs(output_Loc + "Gen_Reco_" + comb_ID_ + ".png") cc.SaveAs(output_Loc + "Gen_Reco_" + comb_ID_ + ".pdf") cc.SaveAs(output_Loc + "Gen_Reco_" + comb_ID_ + ".png") return 0
def plot_dir(dlist, binfo, outfile, prefix, infix, color=[kBlack], legend=[], norm=False): c = TCanvas() c.SetGrid(0) bnarr = binfo.keys() bnarr.sort() bncode = reduce(lambda x, y: x + y, bnarr) namex = bnarr[-2] namey = bnarr[-1] xarr = binfo[namex] yarr = binfo[namey] c.GetPad(0).SetMargin(0.2, 0.15, 0.2, 0.15) c.Divide(len(xarr) - 1, len(yarr) - 1, 0.0, 0.0) #CanvasPartition(c,len(xarr)-1,len(yarr)-1) Ntot = 1 for k in range(len(bnarr) - 2): Ntot *= len(binfo[bnarr[k]]) - 1 for k in range(Ntot): indarr = [] fact = 1 for n in range(len(bnarr) - 2): edg = binfo[bnarr[n]] indarr.append((k / fact) % (len(edg) - 1)) fact *= len(binfo[bnarr[n]]) - 1 for j in range(len(yarr) - 1, 0, -1): YMAX = -100000000. YMIN = 100000000. row = j for i in range(len(xarr) - 1): col = i + 1 bcode = reduce(lambda x, y: str(x) + str(y), indarr) bcode = str(bcode) + str(col - 1) + str(row - 1) cnt = 0 for d in dlist: h = d.Get(prefix[cnt] + bncode + "_" + bcode) maxb = h.GetMaximumBin() minb = h.GetMinimumBin() ymaxtest = h.GetBinContent(maxb) ymintest = h.GetBinContent(minb) # if True: # print "before::" + d.GetPath() + "/" + h.GetName() + "::row::" + str(row) + ":: ymax / integral / bin / content(bin): " + str(ymaxtest) + " / " + str(h.Integral()) + " / " + str( maxb) + " / " + str( h.GetBinContent(maxb)) if norm and h.Integral() != 0: ymaxtest = ymaxtest / h.Integral() ymintest = ymintest / h.Integral() if norm and h.Integral() == 0: ymaxtest = 0 ymintest = 0 if ymaxtest > YMAX: YMAX = ymaxtest if ymintest < YMIN: YMIN = ymintest cnt += 1 # if norm: # print bncode + "::row::" + str(row) + "::ymax: " + str(YMAX) for i in range(len(xarr) - 1): col = i + 1 pad = c.cd(col + (len(yarr) - 1 - row) * (len(xarr) - 1)) pad.SetGridy(0) #pad.SetGridx(0) pad.SetTicks(0, 0) bcode = reduce(lambda x, y: str(x) + str(y), indarr) bcode = str(bcode) + str(col - 1) + str(row - 1) cnt = 0 leg = TLegend(0.77, 0.64, 0.95, 0.89) leg.SetTextSize(0.15) for d in dlist: h = d.Get(prefix[cnt] + bncode + "_" + bcode) h.GetYaxis().SetRangeUser(YMIN, YMAX * 1.1) if "ac" in prefix[cnt] or "Acceptance" in d.GetPath(): h.GetYaxis().SetRangeUser(0, 1) h.GetYaxis().SetLabelSize(0.15) h.GetXaxis().SetLabelSize(0.1) h.GetYaxis().SetLabelSize(0.15) xtitle = str( binfo[namex][col - 1]) + '<' + namex + '<' + str( binfo[namex][col]) + " " + prefix[cnt].split( '_')[0][1:] h.GetXaxis().SetTitle(xtitle) h.GetXaxis().CenterTitle() h.GetXaxis().SetTitleSize(0.12) ytitle = str( binfo[namey][row - 1]) + '<' + namey + '<' + str( binfo[namey][row]) h.GetXaxis().SetNdivisions(505) h.GetYaxis().SetNdivisions(505) h.SetLineWidth(3) h.SetLineColor(color[cnt]) h.SetMarkerColor(color[cnt]) if (legend != []): le = leg.AddEntry(h, legend[cnt], 'lp') le.SetTextColor(color[cnt]) if cnt == 0: if not norm: h.DrawCopy() elif (h.Integral() != 0): hnorm = h.DrawNormalized("e") hnorm.GetYaxis().SetRangeUser(YMIN, YMAX * 1.1) else: h.DrawCopy() if 'hM_' in h.GetName(): rhopeak = TLine(0.77, 0, 0.77, YMAX) rhopeak.SetLineStyle(kDashed) rhopeak.SetLineWidth(1) rhopeak.SetLineColor(kRed) rhopeak.DrawLine(0.77, 0, 0.77, YMAX) pad.Update() pt = pad.FindObject("title") pt.SetX1NDC(0.15) pt.SetTextSizePixels(12) if col == len(xarr) - 1: yaxis = TGaxis(pad.GetUxmax(), pad.GetUymin(), pad.GetUxmax(), pad.GetUymax(), 0, 1, 1, "U+-") yaxis.SetTitle(ytitle + " ") yaxis.SetTitleSize(0.12) yaxis.SetTitleOffset(-0.25) yaxis.SetName(h.GetName() + "_ax_y") yaxis.Draw("") pad.GetListOfPrimitives().Add(yaxis) pad.Update() else: if not norm: h.DrawCopy("same") elif (h.Integral() != 0): hnorm = h.DrawNormalized("samee") hnorm.GetYaxis().SetRangeUser(YMIN, YMAX * 1.1) else: h.DrawCopy("samee") cnt += 1 if (legend != []): leg.Draw() pad.GetListOfPrimitives().Add(leg) outfile.cd() bcode = reduce(lambda x, y: str(x) + str(y), indarr) cncode = reduce(lambda x, y: x + y, bnarr[-3]) c.Write("can_" + infix + "_" + str(cncode) + "_" + str(bcode), TObject.kOverwrite)
def train_and_apply(): np.random.seed(1) ROOT.gROOT.SetBatch() #Extract data from root file tree = uproot.open("out_all.root")["outA/Tevts"] branch_mc = [ "MC_B_P", "MC_B_eta", "MC_B_phi", "MC_B_pt", "MC_D0_P", "MC_D0_eta", "MC_D0_phi", "MC_D0_pt", "MC_Dst_P", "MC_Dst_eta", "MC_Dst_phi", "MC_Dst_pt", "MC_Est_mu", "MC_M2_miss", "MC_mu_P", "MC_mu_eta", "MC_mu_phi", "MC_mu_pt", "MC_pis_P", "MC_pis_eta", "MC_pis_phi", "MC_pis_pt", "MC_q2" ] branch_rec = [ "B_P", "B_eta", "B_phi", "B_pt", "D0_P", "D0_eta", "D0_phi", "D0_pt", "Dst_P", "Dst_eta", "Dst_phi", "Dst_pt", "Est_mu", "M2_miss", "mu_P", "mu_eta", "mu_phi", "mu_pt", "pis_P", "pis_eta", "pis_phi", "pis_pt", "q2" ] nvariable = len(branch_mc) x_train = tree.array(branch_mc[0], entrystop=options.maxevents) for i in range(1, nvariable): x_train = np.vstack( (x_train, tree.array(branch_mc[i], entrystop=options.maxevents))) x_test = tree.array(branch_rec[0], entrystop=options.maxevents) for i in range(1, nvariable): x_test = np.vstack( (x_test, tree.array(branch_rec[i], entrystop=options.maxevents))) x_train = x_train.T x_test = x_test.T x_test = array2D_float(x_test) #Different type of reconstruction variables #BN normalization gamma = 0 beta = 0.2 ar = np.array(x_train) a = K.constant(ar[:, 0]) mean = K.mean(a) var = K.var(a) x_train = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) for i in range(1, nvariable): a = K.constant(ar[:, i]) mean = K.mean(a) var = K.var(a) a = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) x_train = np.vstack((x_train, a)) x_train = x_train.T ar = np.array(x_test) a = K.constant(ar[:, 0]) mean = K.mean(a) var = K.var(a) x_test = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) for i in range(1, nvariable): a = K.constant(ar[:, i]) mean = K.mean(a) var = K.var(a) a = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) x_test = np.vstack((x_test, a)) x_test = x_test.T #Add noise, remain to be improved noise = np.random.normal(loc=0.0, scale=0.01, size=x_train.shape) x_train_noisy = x_train + noise noise = np.random.normal(loc=0.0, scale=0.01, size=x_test.shape) x_test_noisy = x_test + noise x_train = np.clip(x_train, -1., 1.) x_test = np.clip(x_test, -1., 1.) x_train_noisy = np.clip(x_train_noisy, -1., 1.) x_test_noisy = np.clip(x_test_noisy, -1., 1.) # Network parameters input_shape = (x_train.shape[1], ) batch_size = 128 latent_dim = 2 # Build the Autoencoder Model # First build the Encoder Model inputs = Input(shape=input_shape, name='encoder_input') x = inputs # Shape info needed to build Decoder Model shape = K.int_shape(x) # Generate the latent vector latent = Dense(latent_dim, name='latent_vector')(x) # Instantiate Encoder Model encoder = Model(inputs, latent, name='encoder') encoder.summary() # Build the Decoder Model latent_inputs = Input(shape=(latent_dim, ), name='decoder_input') x = Dense(shape[1])(latent_inputs) x = Reshape((shape[1], ))(x) outputs = Activation('tanh', name='decoder_output')(x) # Instantiate Decoder Model decoder = Model(latent_inputs, outputs, name='decoder') decoder.summary() # Autoencoder = Encoder + Decoder # Instantiate Autoencoder Model autoencoder = Model(inputs, decoder(encoder(inputs)), name='autoencoder') autoencoder.summary() autoencoder.compile(loss='mse', optimizer='adam') # Train the autoencoder autoencoder.fit(x_train_noisy, x_train, validation_data=(x_test_noisy, x_test), epochs=options.epochs, batch_size=batch_size) # Predict the Autoencoder output from corrupted test imformation x_decoded = autoencoder.predict(x_test_noisy) # Draw Comparision Plots c = TCanvas("c", "c", 700, 700) fPads1 = TPad("pad1", "Run2", 0.0, 0.29, 1.00, 1.00) fPads2 = TPad("pad2", "", 0.00, 0.00, 1.00, 0.29) fPads1.SetBottomMargin(0.007) fPads1.SetLeftMargin(0.10) fPads1.SetRightMargin(0.03) fPads2.SetLeftMargin(0.10) fPads2.SetRightMargin(0.03) fPads2.SetBottomMargin(0.25) fPads1.Draw() fPads2.Draw() fPads1.cd() nbin = 50 min = -1. max = 1. variable = "P^{B}" lbin = (max - min) / nbin lbin = str(float((max - min) / nbin)) xtitle = branch_rec[options.branch - 1] ytitle = "Events/" + lbin + "GeV" h_rec = TH1D("h_rec", "" + ";%s;%s" % (xtitle, ytitle), nbin, min, max) h_rec.Sumw2() h_pre = TH1D("h_pre", "" + ";%s;%s" % (xtitle, ytitle), nbin, min, max) h_pre.Sumw2() for i in range(x_test_noisy.shape[0]): h_rec.Fill(x_test_noisy[i][options.branch - 1]) h_pre.Fill(x_decoded[i][options.branch - 1]) h_rec = UnderOverFlow1D(h_rec) h_pre = UnderOverFlow1D(h_pre) maxY = TMath.Max(h_rec.GetMaximum(), h_pre.GetMaximum()) h_rec.SetLineColor(2) h_rec.SetFillStyle(0) h_rec.SetLineWidth(2) h_rec.SetLineStyle(1) h_pre.SetLineColor(3) h_pre.SetFillStyle(0) h_pre.SetLineWidth(2) h_pre.SetLineStyle(1) h_rec.SetStats(0) h_pre.SetStats(0) h_rec.GetYaxis().SetRangeUser(0, maxY * 1.1) h_rec.Draw("HIST") h_pre.Draw("same HIST") h_rec.GetYaxis().SetTitleSize(0.06) h_rec.GetYaxis().SetTitleOffset(0.78) theLeg = TLegend(0.5, 0.45, 0.95, 0.82, "", "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(.05) theLeg.AddEntry(h_rec, "Reconstruction", "L") theLeg.AddEntry(h_pre, "Prediction", "L") theLeg.SetY1NDC(0.9 - 0.05 * 6 - 0.005) theLeg.SetY1(theLeg.GetY1NDC()) fPads1.cd() theLeg.Draw() title = TLatex( 0.91, 0.93, "AE prediction compare with reconstruction, epochs=" + str(options.epochs)) title.SetNDC() title.SetTextSize(0.05) title.SetTextFont(42) title.SetTextAlign(31) title.SetLineWidth(2) title.Draw() fPads2.cd() h_Ratio = h_pre.Clone("h_Ratio") h_Ratio.Divide(h_rec) h_Ratio.SetLineColor(1) h_Ratio.SetLineWidth(2) h_Ratio.SetMarkerStyle(8) h_Ratio.SetMarkerSize(0.7) h_Ratio.GetYaxis().SetRangeUser(0, 2) h_Ratio.GetYaxis().SetNdivisions(504, 0) h_Ratio.GetYaxis().SetTitle("Pre/Rec") h_Ratio.GetYaxis().SetTitleOffset(0.35) h_Ratio.GetYaxis().SetTitleSize(0.13) h_Ratio.GetYaxis().SetTitleSize(0.13) h_Ratio.GetYaxis().SetLabelSize(0.11) h_Ratio.GetXaxis().SetLabelSize(0.1) h_Ratio.GetXaxis().SetTitleOffset(0.8) h_Ratio.GetXaxis().SetTitleSize(0.14) h_Ratio.SetStats(0) axis1 = TGaxis(min, 1, max, 1, 0, 0, 0, "L") axis1.SetLineColor(1) axis1.SetLineWidth(1) for i in range(1, h_Ratio.GetNbinsX() + 1, 1): D = h_rec.GetBinContent(i) eD = h_rec.GetBinError(i) if D == 0: eD = 0.92 B = h_pre.GetBinContent(i) eB = h_pre.GetBinError(i) if B < 0.1 and eB >= B: eB = 0.92 Err = 0. if B != 0.: Err = TMath.Sqrt((eD * eD) / (B * B) + (D * D * eB * eB) / (B * B * B * B)) h_Ratio.SetBinContent(i, D / B) h_Ratio.SetBinError(i, Err) if B == 0.: Err = TMath.Sqrt((eD * eD) / (eB * eB) + (D * D * eB * eB) / (eB * eB * eB * eB)) h_Ratio.SetBinContent(i, D / 0.92) h_Ratio.SetBinError(i, Err) if D == 0 and B == 0: h_Ratio.SetBinContent(i, -1) h_Ratio.SetBinError(i, 0) h_Ratio.Draw("e0") axis1.Draw() c.SaveAs(branch_rec[options.branch - 1] + "_comparision.png")
mg.GetYaxis().SetMoreLogLabels() mg.GetYaxis().SetTitleOffset(1.9) legend.SetBorderSize(0) legend.SetTextSize(0.03) legend.Draw("same") c.SetGrid() gStyle.SetGridStyle(2) gStyle.SetGridColor(ROOT.kGray) latex = Text(gPad, 0.88,0.65, "#scale[1.2]{#bf{CMS}} #font[50]{Preliminary}", align = 33) latex = Text(gPad, 0.88,0.60,"Run2 Data (13 TeV)", align = 33,size = 0.03) if args.glob: latex = Text(gPad, 0.88,0.55,"Z#rightarrow ee events, EB", align = 33,size = 0.03) if args.loc: latex = Text(gPad, 0.88,0.55,"Same cluster, EB", align = 33,size = 0.03) latex = Text(gPad, 0.88,0.48,"#sigma = #frac{N}{A_{eff}} #font[62]{#oplus} #sqrt{2}C", align = 33,size = 0.04) top_axis = TGaxis(xmin ,mg.GetHistogram().GetMaximum(),xmax,mg.GetHistogram().GetMaximum(),ADC2GEV_B*xmin,ADC2GEV_B*xmax,510,"G-"); top_axis.SetTitle("E [GeV]") top_axis.SetTitleSize(0.035) top_axis.SetLabelSize(0.035) top_axis.SetTitleFont(42) top_axis.SetLabelFont(42) top_axis.Draw() Frame(gPad) c.Update() c.Modified() input() c.SaveAs("plots/"+args.tag+"/allYears/sigma_"+name+".png") c.SaveAs("plots/"+args.tag+"/allYears/sigma_"+name+".pdf")
legend.AddEntry(bgFreeFunc, "Background free", "L") legend.AddEntry(lowBGFunc, "0.1 counts/ROI/t/y", "L") legend.AddEntry(tonScaleFunc, "1.0 count/ROI/t/y", "L") legend.AddEntry(hiBGFunc, str(highBG) + " counts/ROI/t/y", "L") legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw() if drawMbb: tHalfLow_y = SensClass.GetTHalf(mbbMax_meV * 1.e-3 * CLHEP.eV, isotope, nmeModel, ga) / CLHEP.year tHalfHigh_y = SensClass.GetTHalf(mbbMin_meV * 1.e-3 * CLHEP.eV, isotope, nmeModel, ga) / CLHEP.year nLabels = 4 gAxis = TGaxis(expMax_ty * 1.01, mbbMax_meV, expMax_ty - (expMax_ty - expMin_ty) / 10000., mbbMin_meV, tHalfLow_y, tHalfHigh_y, nLabels, "-G") if (options.xenon136): gAxis.SetTitle("^{136}Xe T^{0#nu}_{1/2} sensitivity (90% CL) [years]") else: gAxis.SetTitle("^{76}Ge T^{0#nu}_{1/2} sensitivity (90% CL) [years]") gAxis.SetTitleOffset(1.4) gAxis.SetBit(TAxis.kRotateTitle) gAxis.SetBit(TAxis.kCenterTitle) gAxis.Draw() else: mbbHi_meV = SensClass.GetMbb(tHalfMin_y * CLHEP.year, isotope, nmeModel, ga) / CLHEP.meV mbbLow_meV = SensClass.GetMbb(tHalfMax_y * CLHEP.year, isotope, nmeModel, ga) / CLHEP.meV nLabels = 4
leg_2d_exclusion_v1_v2.SetFillStyle(1001) leg_2d_exclusion_v1_v2.AddEntry(graph_exclusion_exp_v1, v1_label + " Exp", "L") leg_2d_exclusion_v1_v2.AddEntry(graph_exclusion_exp_v2, v2_label + " Exp", "L") if drawObs: leg_2d_exclusion_v1_v2.AddEntry(graph_exclusion_obs_v1, v1_label + " Obs", "L") leg_2d_exclusion_v1_v2.AddEntry(graph_exclusion_obs_v2, v2_label + " Obs", "L") leg_2d_exclusion_v1_v2.Draw() drawCMS2(myC2D, 13, lumi) f1_lambda = TF1("f1", "(x+6.00)/1.454", 72.902, 416.78) A1_lambda = TGaxis(100.0, 0.02, 600.0, 0.02, "f1", 1010, "NI") A1_lambda.SetLabelFont(42) A1_lambda.SetLabelSize(0.035) A1_lambda.SetTextFont(42) A1_lambda.SetTextSize(1.2) A1_lambda.SetTitle("#Lambda [TeV]") A1_lambda.SetTitleSize(0.04) A1_lambda.SetTitleOffset(0.9) A1_lambda.Draw() myC2D.SaveAs(outputDir + "/limits" + "/limit_exclusion_region_2D_" + year_to_plot + "_" + v1_tag + "_vs_" + v2_tag + ".pdf") myC2D.SaveAs(outputDir + "/limits" + "/limit_exclusion_region_2D_" + year_to_plot + "_" + v1_tag + "_vs_" + v2_tag + ".png") myC2D.SaveAs(outputDir + "/limits" + "/limit_exclusion_region_2D_" + year_to_plot + "_" + v1_tag + "_vs_" + v2_tag + ".C")
def pdf_logPt2_incoh(): #PDF fit to log_10(pT^2) #tree_in = tree_incoh tree_in = tree #ptbin = 0.04 ptbin = 0.12 ptmin = -5. ptmax = 1. mmin = 2.8 mmax = 3.2 #fitran = [-5., 1.] fitran = [-0.9, 0.1] binned = False #gamma-gamma 131 evt for pT<0.18 #output log file out = open("out.txt", "w") ut.log_results( out, "in " + infile + " in_coh " + infile_coh + " in_gg " + infile_gg) loglist = [(x, eval(x)) for x in ["ptbin", "ptmin", "ptmax", "mmin", "mmax", "fitran", "binned"]] strlog = ut.make_log_string(loglist) ut.log_results(out, strlog + "\n") #input data pT = RooRealVar("jRecPt", "pT", 0, 10) m = RooRealVar("jRecM", "mass", 0, 10) dataIN = RooDataSet("data", "data", tree_in, RooArgSet(pT, m)) strsel = "jRecM>{0:.3f} && jRecM<{1:.3f}".format(mmin, mmax) data = dataIN.reduce(strsel) #x is RooRealVar for log(Pt2) draw = "TMath::Log10(jRecPt*jRecPt)" draw_func = RooFormulaVar("x", "log_{10}( #it{p}_{T}^{2} ) (GeV^{2})", draw, RooArgList(pT)) x = data.addColumn(draw_func) x.setRange("fitran", fitran[0], fitran[1]) #binned data nbins, ptmax = ut.get_nbins(ptbin, ptmin, ptmax) hPt = TH1D("hPt", "hPt", nbins, ptmin, ptmax) tree_in.Draw(draw + " >> hPt", strsel) dataH = RooDataHist("dataH", "dataH", RooArgList(x), hPt) #range for plot x.setMin(ptmin) x.setMax(ptmax) x.setRange("plotran", ptmin, ptmax) #create the pdf b = RooRealVar("b", "b", 5., 0., 10.) pdf_func = "log(10.)*pow(10.,x)*exp(-b*pow(10.,x))" pdf_logPt2 = RooGenericPdf("pdf_logPt2", pdf_func, RooArgList(x, b)) #make the fit if binned == True: r1 = pdf_logPt2.fitTo(dataH, rf.Range("fitran"), rf.Save()) else: r1 = pdf_logPt2.fitTo(data, rf.Range("fitran"), rf.Save()) ut.log_results(out, ut.log_fit_result(r1)) #calculate norm to number of events xset = RooArgSet(x) ipdf = pdf_logPt2.createIntegral(xset, rf.NormSet(xset), rf.Range("fitran")) print "PDF integral:", ipdf.getVal() if binned == True: nevt = tree_incoh.Draw( "", strsel + " && " + draw + ">{0:.3f}".format(fitran[0]) + " && " + draw + "<{1:.3f}".format(fitran[0], fitran[1])) else: nevt = data.sumEntries("x", "fitran") print "nevt:", nevt pdf_logPt2.setNormRange("fitran") print "PDF norm:", pdf_logPt2.getNorm(RooArgSet(x)) #a = nevt/ipdf.getVal() a = nevt / pdf_logPt2.getNorm(RooArgSet(x)) ut.log_results(out, "log_10(pT^2) parametrization:") ut.log_results(out, "A = {0:.2f}".format(a)) ut.log_results(out, ut.log_fit_parameters(r1, 0, 2)) print "a =", a #Coherent contribution hPtCoh = ut.prepare_TH1D("hPtCoh", ptbin, ptmin, ptmax) hPtCoh.Sumw2() #tree_coh.Draw(draw + " >> hPtCoh", strsel) tree_coh.Draw("TMath::Log10(jGenPt*jGenPt) >> hPtCoh", strsel) ut.norm_to_data(hPtCoh, hPt, rt.kBlue, -5., -2.2) # norm for coh #ut.norm_to_data(hPtCoh, hPt, rt.kBlue, -5, -2.1) #ut.norm_to_num(hPtCoh, 405, rt.kBlue) print "Coherent integral:", hPtCoh.Integral() #TMath::Log10(jRecPt*jRecPt) #Sartre generated coherent shape sartre = TFile.Open( "/home/jaroslav/sim/sartre_tx/sartre_AuAu_200GeV_Jpsi_coh_2p7Mevt.root" ) sartre_tree = sartre.Get("sartre_tree") hSartre = ut.prepare_TH1D("hSartre", ptbin, ptmin, ptmax) sartre_tree.Draw("TMath::Log10(pT*pT) >> hSartre", "rapidity>-1 && rapidity<1") ut.norm_to_data(hSartre, hPt, rt.kViolet, -5, -2) # norm for Sartre #gamma-gamma contribution hPtGG = ut.prepare_TH1D("hPtGG", ptbin, ptmin, ptmax) tree_gg.Draw(draw + " >> hPtGG", strsel) #ut.norm_to_data(hPtGG, hPt, rt.kGreen, -5., -2.9) ut.norm_to_num(hPtGG, 131., rt.kGreen) print "Int GG:", hPtGG.Integral() #psi' contribution psiP = TFile.Open(basedir_mc + "/ana_slight14e4x1_s6_sel5z.root") psiP_tree = psiP.Get("jRecTree") hPtPsiP = ut.prepare_TH1D("hPtPsiP", ptbin, ptmin, ptmax) psiP_tree.Draw(draw + " >> hPtPsiP", strsel) ut.norm_to_num(hPtPsiP, 12, rt.kViolet) #sum of all contributions hSum = ut.prepare_TH1D("hSum", ptbin, ptmin, ptmax) hSum.SetLineWidth(3) #add ggel to the sum hSum.Add(hPtGG) #add incoherent contribution func_logPt2 = TF1("pdf_logPt2", "[0]*log(10.)*pow(10.,x)*exp(-[1]*pow(10.,x))", -10., 10.) func_logPt2.SetParameters(a, b.getVal()) hInc = ut.prepare_TH1D("hInc", ptbin, ptmin, ptmax) ut.fill_h1_tf(hInc, func_logPt2) hSum.Add(hInc) #add coherent contribution hSum.Add(hPtCoh) #add psi(2S) contribution #hSum.Add(hPtPsiP) #set to draw as a lines ut.line_h1(hSum, rt.kBlack) #create canvas frame can = ut.box_canvas() ut.set_margin_lbtr(gPad, 0.11, 0.09, 0.01, 0.01) frame = x.frame(rf.Bins(nbins), rf.Title("")) frame.SetTitle("") frame.SetMaximum(75) frame.SetYTitle("Events / ({0:.3f}".format(ptbin) + " GeV^{2})") print "Int data:", hPt.Integral() #plot the data if binned == True: dataH.plotOn(frame, rf.Name("data")) else: data.plotOn(frame, rf.Name("data")) pdf_logPt2.plotOn(frame, rf.Range("fitran"), rf.LineColor(rt.kRed), rf.Name("pdf_logPt2")) pdf_logPt2.plotOn(frame, rf.Range("plotran"), rf.LineColor(rt.kRed), rf.Name("pdf_logPt2_full"), rf.LineStyle(rt.kDashed)) frame.Draw() amin = TMath.Power(10, ptmin) amax = TMath.Power(10, ptmax) - 1 print amin, amax pt2func = TF1("f1", "TMath::Power(10, x)", amin, amax) #TMath::Power(x, 10) aPt2 = TGaxis(-5, 75, 1, 75, "f1", 510, "-") ut.set_axis(aPt2) aPt2.SetTitle("pt2") #aPt2.Draw(); leg = ut.prepare_leg(0.57, 0.78, 0.14, 0.19, 0.03) ut.add_leg_mass(leg, mmin, mmax) hx = ut.prepare_TH1D("hx", 1, 0, 1) hx.Draw("same") ln = ut.col_lin(rt.kRed) leg.AddEntry(hx, "Data") leg.AddEntry(hPtCoh, "Sartre MC", "l") leg.AddEntry(hPtGG, "#gamma#gamma#rightarrow e^{+}e^{-} MC", "l") #leg.AddEntry(ln, "ln(10)*#it{A}*10^{log_{10}#it{p}_{T}^{2}}exp(-#it{b}10^{log_{10}#it{p}_{T}^{2}})", "l") #leg.AddEntry(ln, "Incoherent fit", "l") leg.Draw("same") l0 = ut.cut_line(fitran[0], 0.9, frame) l1 = ut.cut_line(fitran[1], 0.9, frame) #l0.Draw() #l1.Draw() desc = pdesc(frame, 0.14, 0.8, 0.054) desc.set_text_size(0.03) desc.itemD("#chi^{2}/ndf", frame.chiSquare("pdf_logPt2", "data", 2), -1, rt.kRed) desc.itemD("#it{A}", a, -1, rt.kRed) desc.itemR("#it{b}", b, rt.kRed) desc.draw() #put the sum #hSum.Draw("same") #gPad.SetLogy() frame.Draw("same") #put gamma-gamma hPtGG.Draw("same") #put coherent J/psi hPtCoh.Draw("same") #put Sartre generated coherent shape #hSartre.Draw("same") #put psi(2S) contribution #hPtPsiP.Draw("same") leg2 = ut.prepare_leg(0.14, 0.9, 0.14, 0.08, 0.03) leg2.AddEntry( ln, "ln(10)*#it{A}*10^{log_{10}#it{p}_{T}^{2}}exp(-#it{b}10^{log_{10}#it{p}_{T}^{2}})", "l") #leg2.AddEntry(hPtCoh, "Sartre MC reconstructed", "l") #leg2.AddEntry(hSartre, "Sartre MC generated", "l") leg2.Draw("same") ut.invert_col(rt.gPad) can.SaveAs("01fig.pdf")
def fit(): #fit to log_10(pT^2) with components and plot of plain pT^2 #range in log_10(pT^2) ptbin = 0.12 ptmin = -5. ptmax = 0.99 # 1.01 #range in pT^2 ptsq_bin = 0.03 ptsq_min = 1e-5 ptsq_max = 1 mmin = 2.8 mmax = 3.2 #range for incoherent fit fitran = [-0.9, 0.1] #number of gamma-gamma events ngg = 131 #number of psi' events npsiP = 20 #input data pT = RooRealVar("jRecPt", "pT", 0, 10) m = RooRealVar("jRecM", "mass", 0, 10) data_all = RooDataSet("data", "data", tree, RooArgSet(pT, m)) #select for mass range strsel = "jRecM>{0:.3f} && jRecM<{1:.3f}".format(mmin, mmax) data = data_all.reduce(strsel) #create log(pT^2) from pT ptsq_draw = "jRecPt*jRecPt" # will be used for pT^2 logPtSq_draw = "TMath::Log10(" + ptsq_draw + ")" logPtSq_form = RooFormulaVar("logPtSq", "logPtSq", logPtSq_draw, RooArgList(pT)) logPtSq = data.addColumn(logPtSq_form) logPtSq.setRange("fitran", fitran[0], fitran[1]) #bins and range for the plot nbins, ptmax = ut.get_nbins(ptbin, ptmin, ptmax) logPtSq.setMin(ptmin) logPtSq.setMax(ptmax) logPtSq.setRange("plotran", ptmin, ptmax) #range for pT^2 ptsq_nbins, ptsq_max = ut.get_nbins(ptsq_bin, ptsq_min, ptsq_max) #incoherent parametrization bval = RooRealVar("bval", "bval", 3.3, 0, 10) inc_form = "log(10.)*pow(10.,logPtSq)*exp(-bval*pow(10.,logPtSq))" incpdf = RooGenericPdf("incpdf", inc_form, RooArgList(logPtSq, bval)) #make the incoherent fit res = incpdf.fitTo(data, rf.Range("fitran"), rf.Save()) #get incoherent norm to the number of events lset = RooArgSet(logPtSq) iinc = incpdf.createIntegral(lset, rf.NormSet(lset), rf.Range("fitran")) inc_nevt = data.sumEntries("logPtSq", "fitran") incpdf.setNormRange("fitran") aval = RooRealVar("aval", "aval", inc_nevt / incpdf.getNorm(lset)) #print "A =", aval.getVal() #print "b =", bval.getVal() #incoherent distribution from log_10(pT^2) function for the sum with gamma-gamma hIncPdf = ut.prepare_TH1D_n("hGG", nbins, ptmin, ptmax) func_incoh_logPt2 = TF1("func_incoh_logPt2", "[0]*log(10.)*pow(10.,x)*exp(-[1]*pow(10.,x))", -10., 10.) func_incoh_logPt2.SetNpx(1000) func_incoh_logPt2.SetLineColor(rt.kMagenta) func_incoh_logPt2.SetParameters( aval.getVal(), bval.getVal()) # 4.9 from incoherent mc, 3.3 from data fit ut.fill_h1_tf(hIncPdf, func_incoh_logPt2, rt.kMagenta) #gamma-gamma contribution hGG = ut.prepare_TH1D_n("hGG", nbins, ptmin, ptmax) tree_gg.Draw(logPtSq_draw + " >> hGG", strsel) ut.norm_to_num(hGG, ngg, rt.kGreen + 1) #sum of incoherent distribution and gamma-gamma hSumIncGG = ut.prepare_TH1D_n("hSumIncGG", nbins, ptmin, ptmax) hSumIncGG.Add(hIncPdf) hSumIncGG.Add(hGG) ut.line_h1(hSumIncGG, rt.kMagenta) #gamma-gamma in pT^2 hGG_ptsq = ut.prepare_TH1D_n("hGG_ptsq", ptsq_nbins, ptsq_min, ptsq_max) tree_gg.Draw(ptsq_draw + " >> hGG_ptsq", strsel) ut.norm_to_num(hGG_ptsq, ngg, rt.kGreen + 1) #psi' contribution psiP_file = TFile.Open(basedir_mc + "/ana_slight14e4x1_s6_sel5z.root") psiP_tree = psiP_file.Get("jRecTree") hPsiP = ut.prepare_TH1D_n("hPsiP", nbins, ptmin, ptmax) psiP_tree.Draw(logPtSq_draw + " >> hPsiP", strsel) ut.norm_to_num(hPsiP, npsiP, rt.kViolet) #psi' in pT^2 hPsiP_ptsq = ut.prepare_TH1D_n("hPsiP_ptsq", ptsq_nbins, ptsq_min, ptsq_max) psiP_tree.Draw(ptsq_draw + " >> hPsiP_ptsq", strsel) ut.norm_to_num(hPsiP_ptsq, npsiP, rt.kViolet) #create canvas frame gStyle.SetPadTickY(1) can = ut.box_canvas(1086, 543) # square area is still 768^2 can.SetMargin(0, 0, 0, 0) can.Divide(2, 1, 0, 0) gStyle.SetLineWidth(1) can.cd(1) ut.set_margin_lbtr(gPad, 0.11, 0.1, 0.01, 0) frame = logPtSq.frame(rf.Bins(nbins)) frame.SetTitle("") frame.SetMaximum(80) frame.SetYTitle("Events / ({0:.3f}".format(ptbin) + " GeV^{2})") frame.SetXTitle("log_{10}( #it{p}_{T}^{2} ) (GeV^{2})") frame.GetXaxis().SetTitleOffset(1.2) frame.GetYaxis().SetTitleOffset(1.6) #plot the data data.plotOn(frame, rf.Name("data"), rf.LineWidth(2)) #incoherent parametrization incpdf.plotOn(frame, rf.Range("fitran"), rf.LineColor(rt.kRed), rf.Name("incpdf"), rf.LineWidth(2)) incpdf.plotOn(frame, rf.Range("plotran"), rf.LineColor(rt.kRed), rf.Name("incpdf_full"), rf.LineStyle(rt.kDashed), rf.LineWidth(2)) frame.Draw() #add gamma-gamma contribution hGG.Draw("same") #sum of incoherent distribution and gamma-gamma #hSumIncGG.Draw("same") #add psi' #hPsiP.Draw("same") #legend for log_10(pT^2) leg = ut.prepare_leg(0.15, 0.77, 0.28, 0.19, 0.035) hxl = ut.prepare_TH1D("hxl", 1, 0, 1) hxl.Draw("same") ilin = ut.col_lin(rt.kRed, 2) ilin2 = ut.col_lin(rt.kRed, 2) ilin2.SetLineStyle(rt.kDashed) leg.AddEntry(ilin, "Incoherent parametrization, fit region", "l") leg.AddEntry(ilin2, "Incoherent parametrization, extrapolation region", "l") leg.AddEntry(hGG, "#gamma#gamma#rightarrow e^{+}e^{-}", "l") #leg.AddEntry(hxl, "Data", "lp") leg.AddEntry(hxl, "Data, log_{10}( #it{p}_{T}^{2} )", "lp") leg.Draw("same") #----- plot pT^2 on the right ----- #pT^2 variable from pT ptsq_form = RooFormulaVar("ptsq", "ptsq", ptsq_draw, RooArgList(pT)) ptsq = data.addColumn(ptsq_form) #range for pT^2 plot ptsq.setMin(ptsq_min) ptsq.setMax(ptsq_max) #make the pT^2 plot can.cd(2) gPad.SetLogy() #gPad.SetLineWidth(3) #gPad.SetFrameLineWidth(1) ut.set_margin_lbtr(gPad, 0, 0.1, 0.01, 0.15) ptsq_frame = ptsq.frame(rf.Bins(ptsq_nbins), rf.Title("")) #print type(ptsq_frame), type(ptsq) ptsq_frame.SetTitle("") ptsq_frame.SetXTitle("#it{p}_{T}^{2} (GeV^{2})") ptsq_frame.GetXaxis().SetTitleOffset(1.2) data.plotOn(ptsq_frame, rf.Name("data"), rf.LineWidth(2)) ptsq_frame.SetMaximum(9e2) ptsq_frame.SetMinimum(0.8) # 0.101 ptsq_frame.Draw() #incoherent parametrization in pT^2 over the fit region, scaled to the plot inc_ptsq = TF1("inc_ptsq", "[0]*exp(-[1]*x)", 10**fitran[0], 10**fitran[1]) inc_ptsq.SetParameters(aval.getVal() * ptsq_bin, bval.getVal()) #incoherent parametrization in the extrapolation region, below and above the fit region inc_ptsq_ext1 = TF1("inc_ptsq_ext1", "[0]*exp(-[1]*x)", 0., 10**fitran[0]) inc_ptsq_ext2 = TF1("inc_ptsq_ext2", "[0]*exp(-[1]*x)", 10**fitran[1], 10) inc_ptsq_ext1.SetParameters(aval.getVal() * ptsq_bin, bval.getVal()) inc_ptsq_ext1.SetLineStyle(rt.kDashed) inc_ptsq_ext2.SetParameters(aval.getVal() * ptsq_bin, bval.getVal()) inc_ptsq_ext2.SetLineStyle(rt.kDashed) inc_ptsq.Draw("same") inc_ptsq_ext1.Draw("same") inc_ptsq_ext2.Draw("same") #add gamma-gamma in pT^2 hGG_ptsq.Draw("same") #add psi' in pT^2 #hPsiP_ptsq.Draw("same") #redraw the frame #ptsq_frame.Draw("same") ptsq_frame.GetXaxis().SetLimits(-9e-3, ptsq_frame.GetXaxis().GetXmax()) #vertical axis for pT^2 plot xpos = ptsq_frame.GetXaxis().GetXmax() ypos = ptsq_frame.GetMaximum() ymin = ptsq_frame.GetMinimum() ptsq_axis = TGaxis(xpos, 0, xpos, ypos, ymin, ypos, 510, "+GL") ut.set_axis(ptsq_axis) ptsq_axis.SetMoreLogLabels() ptsq_axis.SetTitle("Events / ({0:.3f}".format(ptsq_bin) + " GeV^{2})") ptsq_axis.SetTitleOffset(2.2) ptsq_axis.Draw() #legend for input data #dleg = ut.prepare_leg(0.4, 0.77, 0.14, 0.18, 0.035) dleg = ut.prepare_leg(0.4, 0.71, 0.16, 0.24, 0.035) dleg.AddEntry(None, "#bf{|#kern[0.3]{#it{y}}| < 1}", "") ut.add_leg_mass(dleg, mmin, mmax) dleg.AddEntry(None, "AuAu@200 GeV", "") dleg.AddEntry(None, "UPC sample", "") dleg.AddEntry(hxl, "Data, #it{p}_{T}^{2}", "lp") dleg.Draw("same") #ut.invert_col_can(can) can.SaveAs("01fig.pdf")
def plot_hist(histlist, labellist, norm, log, overflow, filename, options, scaling=[]): canv = TCanvas("c1", "c1", 800, 600) canv.SetTopMargin(10) canv.SetRightMargin(100) if log: gPad.SetLogy() histstack = THStack("stack", histlist[0].GetTitle()) legend = TLegend(0.76, 0.88 - 0.08 * len(histlist), 0.91, 0.88, '', 'NDC') colorlist = [4, 8, 2, 6, 1] if len(scaling) > 1 and scaling[1] == 0: scaling = [] if options: options += " NOSTACK" else: options = "NOSTACK" maximum = 0 for i in range(len(histlist)): entries = histlist[i].GetEntries() mean = histlist[i].GetMean() histlist[i].SetLineColorAlpha(colorlist[i], 0.65) histlist[i].SetLineWidth(3) nbins = histlist[i].GetNbinsX() legend.AddEntry( histlist[i], "#splitline{" + labellist[i] + "}{#splitline{%d entries}{mean=%.2f}}" % (entries, mean), "l") if overflow: histlist[i].SetBinContent( nbins, histlist[i].GetBinContent(nbins) + histlist[i].GetBinContent(nbins + 1)) #overflow histlist[i].SetBinContent(1, histlist[i].GetBinContent(0) + histlist[i].GetBinContent(1)) #underflow if entries and norm: histlist[i].Scale(1. / entries) if histlist[i].GetMaximum() > maximum: maximum = histlist[i].GetMaximum() histstack.Add(histlist[i]) histstack.SetMaximum(maximum * 1.4) histstack.Draw(options) histstack.GetXaxis().SetTitle(histlist[0].GetXaxis().GetTitle()) histstack.GetYaxis().SetTitle(histlist[0].GetYaxis().GetTitle()) xlimit = [ histlist[0].GetBinLowEdge(1), histlist[0].GetBinLowEdge(histlist[0].GetNbinsX()) + histlist[0].GetBinWidth(histlist[0].GetNbinsX()) ] if len(scaling) != 0: top_axis = TGaxis(xlimit[0], maximum * 1.4, xlimit[1], maximum * 1.4, (xlimit[0] - scaling[0]) / scaling[1], (xlimit[1] - scaling[0]) / scaling[1], 510, "-") top_axis.SetTitle("normalized scale") top_axis.SetTickSize(0) top_axis.Draw("SAME") legend.SetTextSize(0.02) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw("SAME") canv.SaveAs(filename) if log: gPad.Clear() canv.Clear() del canv
def __reweightCanvas(self, can, addLabels, addTopXNumbers): import numpy as np, ROOT from ROOT import TGaxis, TLatex, kBlack if can.GetPrimitive('pad_top'): self.__reweightCanvas(can.GetPrimitive('pad_top'), False, addTopXNumbers) if can.GetPrimitive('pad_bot'): self.__reweightCanvas(can.GetPrimitive('pad_bot'), self.addLabels, False) if can.GetPrimitive('pad_bot') or can.GetPrimitive('pad_bot'): return can.cd() # First we "remove" previous axis xaxis = GetXaxis(can) # Now create new axis #xaxis.SetName("__xaxis_ignored") # Now draw new canvas #xmin, xmax = GetXaxisRanges(can) #import os #c = ROOT.TCanvas(self.func.GetName(),self.func.GetName()) #self.func.Draw() #c.SaveAs( os.path.join( 'e26_RunByRun_noAdjustment', c.GetName() +'.pdf' ) ) #can.cd() #chopt = "+C" + ("U" if not addLabels else "") chopt = "+CU" axis = TGaxis(can.GetUxmin(), can.GetUymin(), can.GetUxmax(), can.GetUymin(), self.func.GetName(), 10000 * self.N3 + 100 * self.N2 + 1 * self.N1, chopt) axis.SetNoExponent(False) #axis.SetExponentOffset() if xaxis: axis.ImportAxisAttributes(xaxis) xaxis.SetTickLength(0) xaxis.SetLabelOffset(999.) if self.labelSize: axis.SetLabelSize(self.labelSize) #1 + 100*N2 + *N3N axis.Draw() from .PlotFunctions import tobject_collector if addTopXNumbers: _, ymax = GetYaxisRanges(can, check_all=True, ignorezeros=True, ignoreErrors=False) for xc in self.xcenters: text = TLatex(self.func.Eval(xc), ymax, str(xc)) text.SetTextFont(43) text.SetTextSize(2) text.SetTextAlign(12) text.SetTextAngle(90) text.SetTextColor(ROOT.kBlack) text.Draw() tobject_collector.append(text) if addLabels: binLow, binHigh, nBins = self.__getXEdges(chopt) #labelPos = map( lambda x: (x,self.func.GetX(x),(self.func.GetX(x)-self.xedges[0])/(self.xedges[-1]-self.xedges[0])) # , np.linspace(binLow,binHigh, nBins) ) labelPos = map( lambda x: (x, self.func.Eval(x), (self.func.Eval(x) - self.xedges[0]) / (self.xedges[-1] - self.xedges[0])), np.linspace(binLow, binHigh, nBins)) ypos = can.GetUymin() - 0.04 * (can.GetUymax() - can.GetUymin()) #labels = [] for x, mx, pmx in labelPos: text = TLatex(mx, ypos, str(x)) text.SetTextFont(43) #text.SetTextSizePixels(textPerc) text.SetTextAlign(23) text.SetTextColor(ROOT.kBlack) text.SetTextSize(14) text.Draw() tobject_collector.append(text) #labels.append(text) #gxc = (self.xedges[-1]-self.xedges[0] )/2 #lLabels = len(labels) #for i, text in enumerate(labels): # xc = text.GetBBoxCenter() # if xc < gxc: # if i+1 < lLabels: # text2 = labels[i+1] # while conflict(text.GetBBox(),text2.GetBBox()): # sizes[i] = possible_sizes[sizes[i]+1] # text.SetTextSize( getNewSize ##AdjustBinSize (Double_t A1, Double_t A2, Int_t nold, Double_t &BinLow, Double_t &BinHigh, Int_t &nbins, Double_t &BinWidth) #lLabels = [labels.At(i) for i in range(labels.GetEntries())] tobject_collector.append(axis) #can.Modified() #can.Update() return axis
def main(): # pylint: disable=too-many-locals, too-many-statements, too-many-branches """ Main plotting function """ gROOT.SetBatch(True) # pylint: disable=unused-variable parser = argparse.ArgumentParser() parser.add_argument("--database-analysis", "-d", dest="database_analysis", help="analysis database to be used", required=True) parser.add_argument("--analysis", "-a", dest="type_ana", help="choose type of analysis", required=True) parser.add_argument("--input", "-i", dest="input_file", help="results input file", required=True) args = parser.parse_args() typean = args.type_ana shape = typean[len("jet_"):] print("Shape:", shape) file_in = args.input_file with open(args.database_analysis, "r") as file_db: data_param = yaml.safe_load(file_db) case = list(data_param.keys())[0] datap = data_param[case] logger = get_logger() i_cut = file_in.rfind("/") rootpath = file_in[:i_cut] # plotting # LaTeX string p_latexnhadron = datap["analysis"][typean]["latexnamehadron"] p_latexbin2var = datap["analysis"][typean]["latexbin2var"] v_varshape_latex = datap["analysis"][typean]["var_shape_latex"] # first variable (hadron pt) lpt_finbinmin = datap["analysis"][typean]["sel_an_binmin"] lpt_finbinmax = datap["analysis"][typean]["sel_an_binmax"] var1ranges = lpt_finbinmin.copy() var1ranges.append(lpt_finbinmax[-1]) # second variable (jet pt) v_var2_binning = datap["analysis"][typean]["var_binning2"] # name lvar2_binmin_reco = datap["analysis"][typean].get("sel_binmin2_reco", None) lvar2_binmax_reco = datap["analysis"][typean].get("sel_binmax2_reco", None) p_nbin2_reco = len(lvar2_binmin_reco) # number of reco bins lvar2_binmin_gen = datap["analysis"][typean].get("sel_binmin2_gen", None) lvar2_binmax_gen = datap["analysis"][typean].get("sel_binmax2_gen", None) p_nbin2_gen = len(lvar2_binmin_gen) # number of gen bins var2ranges_reco = lvar2_binmin_reco.copy() var2ranges_reco.append(lvar2_binmax_reco[-1]) var2binarray_reco = array( "d", var2ranges_reco) # array of bin edges to use in histogram constructors var2ranges_gen = lvar2_binmin_gen.copy() var2ranges_gen.append(lvar2_binmax_gen[-1]) var2binarray_gen = array( "d", var2ranges_gen) # array of bin edges to use in histogram constructors # observable (z, shape,...) v_varshape_binning = datap["analysis"][typean][ "var_binningshape"] # name (reco) v_varshape_binning_gen = datap["analysis"][typean][ "var_binningshape_gen"] # name (gen) lvarshape_binmin_reco = \ datap["analysis"][typean].get("sel_binminshape_reco", None) lvarshape_binmax_reco = \ datap["analysis"][typean].get("sel_binmaxshape_reco", None) p_nbinshape_reco = len(lvarshape_binmin_reco) # number of reco bins lvarshape_binmin_gen = \ datap["analysis"][typean].get("sel_binminshape_gen", None) lvarshape_binmax_gen = \ datap["analysis"][typean].get("sel_binmaxshape_gen", None) p_nbinshape_gen = len(lvarshape_binmin_gen) # number of gen bins varshaperanges_reco = lvarshape_binmin_reco.copy() varshaperanges_reco.append(lvarshape_binmax_reco[-1]) varshapebinarray_reco = array( "d", varshaperanges_reco ) # array of bin edges to use in histogram constructors varshaperanges_gen = lvarshape_binmin_gen.copy() varshaperanges_gen.append(lvarshape_binmax_gen[-1]) varshapebinarray_gen = array( "d", varshaperanges_gen ) # array of bin edges to use in histogram constructors file_results = TFile.Open(file_in) if not file_results: logger.fatal(make_message_notfound(file_in)) ibin2 = 1 suffix = "%s_%g_%g" % (v_var2_binning, lvar2_binmin_gen[ibin2], lvar2_binmax_gen[ibin2]) # HF data nameobj = "%s_hf_data_%d_stat" % (shape, ibin2) hf_data_stat = file_results.Get(nameobj) if not hf_data_stat: logger.fatal(make_message_notfound(nameobj, file_in)) nameobj = "%s_hf_data_%d_syst" % (shape, ibin2) hf_data_syst = file_results.Get(nameobj) if not hf_data_syst: logger.fatal(make_message_notfound(nameobj, file_in)) # HF PYTHIA nameobj = "%s_hf_pythia_%d_stat" % (shape, ibin2) hf_pythia_stat = file_results.Get(nameobj) if not hf_pythia_stat: logger.fatal(make_message_notfound(nameobj, file_in)) # HF ratio nameobj = "%s_hf_ratio_%d_stat" % (shape, ibin2) hf_ratio_stat = file_results.Get(nameobj) if not hf_ratio_stat: logger.fatal(make_message_notfound(nameobj, file_in)) nameobj = "%s_hf_ratio_%d_syst" % (shape, ibin2) hf_ratio_syst = file_results.Get(nameobj) if not hf_ratio_syst: logger.fatal(make_message_notfound(nameobj, file_in)) # inclusive data nameobj = "%s_incl_data_%d_stat" % (shape, ibin2) incl_data_stat = file_results.Get(nameobj) if not incl_data_stat: logger.fatal(make_message_notfound(nameobj, file_in)) nameobj = "%s_incl_data_%d_syst" % (shape, ibin2) incl_data_syst = file_results.Get(nameobj) if not incl_data_syst: logger.fatal(make_message_notfound(nameobj, file_in)) # inclusive PYTHIA nameobj = "%s_incl_pythia_%d_stat" % (shape, ibin2) incl_pythia_stat = file_results.Get(nameobj) if not incl_pythia_stat: logger.fatal(make_message_notfound(nameobj, file_in)) nameobj = "%s_incl_pythia_%d_syst" % (shape, ibin2) incl_pythia_syst = file_results.Get(nameobj) if not incl_pythia_syst: logger.fatal(make_message_notfound(nameobj, file_in)) # inclusive ratio nameobj = "%s_incl_ratio_%d_stat" % (shape, ibin2) incl_ratio_stat = file_results.Get(nameobj) if not incl_ratio_stat: logger.fatal(make_message_notfound(nameobj, file_in)) nameobj = "%s_incl_ratio_%d_syst" % (shape, ibin2) incl_ratio_syst = file_results.Get(nameobj) if not incl_ratio_syst: logger.fatal(make_message_notfound(nameobj, file_in)) # quark PYTHIA nameobj = "%s_quark_pythia_%d_stat" % (shape, ibin2) quark_pythia_stat = file_results.Get(nameobj) if not quark_pythia_stat: logger.fatal(make_message_notfound(nameobj, file_in)) nameobj = "%s_quark_pythia_%d_syst" % (shape, ibin2) quark_pythia_syst = file_results.Get(nameobj) if not quark_pythia_syst: logger.fatal(make_message_notfound(nameobj, file_in)) # gluon PYTHIA nameobj = "%s_gluon_pythia_%d_stat" % (shape, ibin2) gluon_pythia_stat = file_results.Get(nameobj) if not gluon_pythia_stat: logger.fatal(make_message_notfound(nameobj, file_in)) nameobj = "%s_gluon_pythia_%d_syst" % (shape, ibin2) gluon_pythia_syst = file_results.Get(nameobj) if not gluon_pythia_syst: logger.fatal(make_message_notfound(nameobj, file_in)) # plot the results with systematic uncertainties and models size_can = [800, 800] offsets_axes = [0.8, 1.1] margins_can = [0.1, 0.13, 0.1, 0.03] size_thg = 0.05 offset_thg = 0.85 gStyle.SetErrorX(0) # do not plot horizontal error bars of histograms fontsize = 0.035 opt_leg_g = "FP" opt_plot_g = "2" list_new = [] # list to avoid loosing objects created in loops # labels x_latex = 0.16 y_latex_top = 0.83 y_step = 0.055 title_x = v_varshape_latex title_y = "(1/#it{N}_{jet}) d#it{N}/d%s" % v_varshape_latex title_full = ";%s;%s" % (title_x, title_y) title_full_ratio = ";%s;data/MC: ratio of %s" % (title_x, title_y) text_alice = "#bf{ALICE} Preliminary, pp, #sqrt{#it{s}} = 13 TeV" text_alice_sim = "#bf{ALICE} Simulation, pp, #sqrt{#it{s}} = 13 TeV" text_pythia = "PYTHIA 8 (Monash)" text_pythia_split = "#splitline{PYTHIA 8}{(Monash)}" text_jets = "charged jets, anti-#it{k}_{T}, #it{R} = 0.4" text_ptjet = "%g #leq %s < %g GeV/#it{c}, #left|#it{#eta}_{jet}#right| #leq 0.5" % ( lvar2_binmin_reco[ibin2], p_latexbin2var, lvar2_binmax_reco[ibin2]) text_pth = "%g #leq #it{p}_{T}^{%s} < %g GeV/#it{c}, #left|#it{y}_{%s}#right| #leq 0.8" % ( lpt_finbinmin[0], p_latexnhadron, min(lpt_finbinmax[-1], lvar2_binmax_reco[ibin2]), p_latexnhadron) text_ptcut = "#it{p}_{T, incl. ch. jet}^{leading track} #geq 5.33 GeV/#it{c}" text_ptcut_sim = "#it{p}_{T, incl. ch. jet}^{leading h^{#pm}} #geq 5.33 GeV/#it{c} (varied)" text_sd = "Soft Drop (#it{z}_{cut} = 0.1, #it{#beta} = 0)" title_thetag = "#it{#theta}_{g} = #it{R}_{g}/#it{R}" radius_jet = 0.4 # colour and marker indeces c_hf_data = 0 c_incl_data = 1 c_hf_mc = 2 c_incl_mc = 6 c_quark_mc = 5 c_gluon_mc = 0 # markers m_hf_data = get_marker(0) m_incl_data = get_marker(1) m_hf_mc = get_marker(0, 2) m_incl_mc = get_marker(1, 2) m_quark_mc = get_marker(2) m_gluon_mc = get_marker(3) # make the horizontal error bars smaller if shape == "nsd": for gr in [ hf_data_syst, incl_data_syst, hf_ratio_syst, incl_ratio_syst, incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst ]: for i in range(gr.GetN()): gr.SetPointEXlow(i, 0.1) gr.SetPointEXhigh(i, 0.1) # data, HF and inclusive hf_data_syst_cl = hf_data_syst.Clone() leg_pos = [.72, .75, .85, .85] list_obj = [hf_data_syst, incl_data_syst, hf_data_stat, incl_data_stat] labels_obj = ["%s-tagged" % p_latexnhadron, "inclusive", "", ""] colours = [ get_colour(i, j) for i, j in zip((c_hf_data, c_incl_data, c_hf_data, c_incl_data), (2, 2, 1, 1)) ] markers = [m_hf_data, m_incl_data, m_hf_data, m_incl_data] y_margin_up = 0.46 y_margin_down = 0.05 cshape_data, list_obj_data_new = make_plot("cshape_data_" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \ title=title_full) for gr, c in zip((hf_data_syst, incl_data_syst), (c_hf_data, c_incl_data)): gr.SetMarkerColor(get_colour(c)) list_obj_data_new[0].SetTextSize(fontsize) if shape == "nsd": hf_data_syst.GetXaxis().SetNdivisions(5) # Draw a line through the points. if shape == "nsd": for h in (hf_data_stat, incl_data_stat): h_line = h.Clone(h.GetName() + "_line") h_line.SetLineStyle(2) h_line.Draw("l hist same") list_new.append(h_line) cshape_data.Update() if shape == "rg": # plot the theta_g axis gr_frame = hf_data_syst axis_rg = gr_frame.GetXaxis() rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst()) rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast()) thetag_min = rg_min / radius_jet thetag_max = rg_max / radius_jet y_axis = cshape_data.GetUymax() axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min, thetag_max, 510, "-") axis_thetag.SetTitle(title_thetag) axis_thetag.SetTitleSize(size_thg) axis_thetag.SetLabelSize(0.036) axis_thetag.SetTitleFont(42) axis_thetag.SetLabelFont(42) axis_thetag.SetLabelOffset(0) axis_thetag.SetTitleOffset(offset_thg) cshape_data.SetTickx(0) axis_thetag.Draw("same") # Draw LaTeX y_latex = y_latex_top list_latex_data = [] for text_latex in [ text_alice, text_jets, text_ptjet, text_pth, text_ptcut, text_sd ]: latex = TLatex(x_latex, y_latex, text_latex) list_latex_data.append(latex) draw_latex(latex, textsize=fontsize) y_latex -= y_step cshape_data.Update() cshape_data.SaveAs("%s/%s_data_%s.pdf" % (rootpath, shape, suffix)) # data and PYTHIA, HF leg_pos = [.72, .65, .85, .85] list_obj = [hf_data_syst_cl, hf_data_stat, hf_pythia_stat] labels_obj = ["data", "", text_pythia_split] colours = [ get_colour(i, j) for i, j in zip((c_hf_data, c_hf_data, c_hf_mc), (2, 1, 1)) ] markers = [m_hf_data, m_hf_data, m_hf_mc] y_margin_up = 0.4 y_margin_down = 0.05 cshape_data_mc_hf, list_obj_data_mc_hf_new = make_plot("cshape_data_mc_hf_" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \ title=title_full) for gr, c in zip([hf_data_syst_cl], [c_hf_data]): gr.SetMarkerColor(get_colour(c)) leg_data_mc_hf = list_obj_data_mc_hf_new[0] leg_data_mc_hf.SetHeader("%s-tagged" % p_latexnhadron) leg_data_mc_hf.SetTextSize(fontsize) if shape == "nsd": hf_data_syst_cl.GetXaxis().SetNdivisions(5) #axis_nsd = hf_data_syst_cl.GetHistogram().GetXaxis() #x1 = axis_nsd.GetBinLowEdge(1) #x2 = axis_nsd.GetBinUpEdge(axis_nsd.GetNbins()) #axis_nsd.Set(5, x1, x2) #for ibin in range(axis_nsd.GetNbins()): # axis_nsd.SetBinLabel(ibin + 1, "%d" % ibin) #axis_nsd.SetNdivisions(5) cshape_data_mc_hf.Update() if shape == "rg": # plot the theta_g axis axis_rg = hf_data_stat.GetXaxis() rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst()) rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast()) thetag_min = rg_min / radius_jet thetag_max = rg_max / radius_jet y_axis = cshape_data_mc_hf.GetUymax() axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min, thetag_max, 510, "-") axis_thetag.SetTitle(title_thetag) axis_thetag.SetTitleSize(size_thg) axis_thetag.SetLabelSize(0.036) axis_thetag.SetTitleFont(42) axis_thetag.SetLabelFont(42) axis_thetag.SetLabelOffset(0) axis_thetag.SetTitleOffset(offset_thg) cshape_data_mc_hf.SetTickx(0) axis_thetag.Draw("same") # Draw LaTeX y_latex = y_latex_top list_latex_data_mc_hf = [] for text_latex in [text_alice, text_jets, text_ptjet, text_pth, text_sd]: latex = TLatex(x_latex, y_latex, text_latex) list_latex_data_mc_hf.append(latex) draw_latex(latex, textsize=fontsize) y_latex -= y_step cshape_data_mc_hf.Update() cshape_data_mc_hf.SaveAs("%s/%s_data_mc_hf_%s.pdf" % (rootpath, shape, suffix)) # data and PYTHIA, inclusive #leg_pos = [.68, .65, .85, .85] list_obj = [ incl_data_syst, incl_pythia_syst, incl_data_stat, incl_pythia_stat ] labels_obj = ["data", text_pythia_split] colours = [ get_colour(i, j) for i, j in zip((c_incl_data, c_incl_mc, c_incl_data, c_incl_mc), (2, 2, 1, 1)) ] markers = [m_incl_data, m_incl_mc, m_incl_data, m_incl_mc] y_margin_up = 0.4 y_margin_down = 0.05 cshape_data_mc_incl, list_obj_data_mc_incl_new = make_plot("cshape_data_mc_incl_" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \ title=title_full) for gr, c in zip([incl_data_syst, incl_pythia_syst], [c_incl_data, c_incl_mc]): gr.SetMarkerColor(get_colour(c)) leg_data_mc_incl = list_obj_data_mc_incl_new[0] leg_data_mc_incl.SetHeader("inclusive") leg_data_mc_incl.SetTextSize(fontsize) if shape == "nsd": incl_data_syst.GetXaxis().SetNdivisions(5) cshape_data_mc_incl.Update() if shape == "rg": # plot the theta_g axis axis_rg = incl_data_stat.GetXaxis() rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst()) rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast()) thetag_min = rg_min / radius_jet thetag_max = rg_max / radius_jet y_axis = cshape_data_mc_incl.GetUymax() axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min, thetag_max, 510, "-") axis_thetag.SetTitle(title_thetag) axis_thetag.SetTitleSize(size_thg) axis_thetag.SetLabelSize(0.036) axis_thetag.SetTitleFont(42) axis_thetag.SetLabelFont(42) axis_thetag.SetLabelOffset(0) axis_thetag.SetTitleOffset(offset_thg) cshape_data_mc_incl.SetTickx(0) axis_thetag.Draw("same") # Draw LaTeX y_latex = y_latex_top list_latex_data_mc_incl = [] for text_latex in [text_alice, text_jets, text_ptjet, text_ptcut, text_sd]: latex = TLatex(x_latex, y_latex, text_latex) list_latex_data_mc_incl.append(latex) draw_latex(latex, textsize=fontsize) y_latex -= y_step cshape_data_mc_incl.Update() cshape_data_mc_incl.SaveAs("%s/%s_data_mc_incl_%s.pdf" % (rootpath, shape, suffix)) # Ratios data/MC, HF and inclusive line_1 = TLine(lvarshape_binmin_reco[0], 1, lvarshape_binmax_reco[-1], 1) line_1.SetLineStyle(9) line_1.SetLineColor(1) line_1.SetLineWidth(3) #leg_pos = [.72, .7, .85, .85] # with header leg_pos = [.72, .75, .85, .85] # without header list_obj = [ hf_ratio_syst, line_1, incl_ratio_syst, hf_ratio_stat, incl_ratio_stat ] labels_obj = ["%s-tagged" % p_latexnhadron, "inclusive"] colours = [ get_colour(i, j) for i, j in zip((c_hf_data, c_incl_data, c_hf_data, c_incl_data), (2, 2, 1, 1)) ] markers = [m_hf_data, m_incl_data, m_hf_data, m_incl_data] y_margin_up = 0.52 y_margin_down = 0.05 if shape == "nsd": y_margin_up = 0.22 cshape_ratio, list_obj_ratio_new = make_plot("cshape_ratio_" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \ title=title_full_ratio) cshape_ratio.Update() for gr, c in zip((hf_ratio_syst, incl_ratio_syst), (c_hf_data, c_incl_data)): gr.SetMarkerColor(get_colour(c)) leg_ratio = list_obj_ratio_new[0] leg_ratio.SetTextSize(fontsize) #leg_ratio.SetHeader("data/MC") if shape == "nsd": hf_ratio_syst.GetXaxis().SetNdivisions(5) cshape_ratio.Update() if shape == "rg": # plot the theta_g axis gr_frame = hf_ratio_syst axis_rg = gr_frame.GetXaxis() rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst()) rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast()) thetag_min = rg_min / radius_jet thetag_max = rg_max / radius_jet y_axis = cshape_ratio.GetUymax() axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min, thetag_max, 510, "-") axis_thetag.SetTitle(title_thetag) axis_thetag.SetTitleSize(size_thg) axis_thetag.SetLabelSize(0.036) axis_thetag.SetTitleFont(42) axis_thetag.SetLabelFont(42) axis_thetag.SetLabelOffset(0) axis_thetag.SetTitleOffset(offset_thg) cshape_ratio.SetTickx(0) axis_thetag.Draw("same") # Draw LaTeX y_latex = y_latex_top list_latex_ratio = [] for text_latex in [ text_alice, text_jets, text_ptjet, text_pth, text_ptcut, text_sd, text_pythia ]: latex = TLatex(x_latex, y_latex, text_latex) list_latex_ratio.append(latex) draw_latex(latex, textsize=fontsize) y_latex -= y_step cshape_ratio.Update() cshape_ratio.SaveAs("%s/%s_ratio_%s.pdf" % (rootpath, shape, suffix)) # PYTHIA, HF, inclusive, quark, gluon incl_pythia_syst_cl = incl_pythia_syst.Clone() y_min_h, y_max_h = get_y_window_his([ hf_pythia_stat, incl_pythia_stat, quark_pythia_stat, gluon_pythia_stat ]) y_min_g, y_max_g = get_y_window_gr( [incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst]) y_min = min(y_min_h, y_min_g) y_max = max(y_max_h, y_max_g) y_margin_up = 0.46 y_margin_down = 0.05 y_min_plot, y_max_plot = get_plot_range(y_min, y_max, y_margin_down, y_margin_up) #leg_pos = [.6, .65, .75, .85] leg_pos = [.72, .55, .85, .85] list_obj = [ incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst, hf_pythia_stat, incl_pythia_stat, quark_pythia_stat, gluon_pythia_stat ] labels_obj = ["inclusive", "quark", "gluon", "%s-tagged" % p_latexnhadron] colours = [ get_colour(i, j) for i, j in zip((c_incl_mc, c_quark_mc, c_gluon_mc, c_hf_mc, c_incl_mc, c_quark_mc, c_gluon_mc), (2, 2, 2, 1, 1, 1, 1)) ] markers = [ m_incl_mc, m_quark_mc, m_gluon_mc, m_hf_mc, m_incl_mc, m_quark_mc, m_gluon_mc ] y_margin_up = 0.46 y_margin_down = 0.05 cshape_mc, list_obj_mc_new = make_plot("cshape_mc_" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, range_y=[y_min_plot, y_max_plot], margins_c=margins_can, \ title=title_full) cshape_mc.Update() for gr, c in zip((incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst), (c_incl_mc, c_quark_mc, c_gluon_mc)): gr.SetMarkerColor(get_colour(c)) leg_mc = list_obj_mc_new[0] leg_mc.SetTextSize(fontsize) leg_mc.SetHeader(text_pythia_split) if shape == "nsd": incl_pythia_syst.GetXaxis().SetNdivisions(5) cshape_mc.Update() if shape == "rg": # plot the theta_g axis axis_rg = hf_pythia_stat.GetXaxis() rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst()) rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast()) thetag_min = rg_min / radius_jet thetag_max = rg_max / radius_jet y_axis = cshape_mc.GetUymax() axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min, thetag_max, 510, "-") axis_thetag.SetTitle(title_thetag) axis_thetag.SetTitleSize(size_thg) axis_thetag.SetLabelSize(0.036) axis_thetag.SetTitleFont(42) axis_thetag.SetLabelFont(42) axis_thetag.SetLabelOffset(0) axis_thetag.SetTitleOffset(offset_thg) cshape_mc.SetTickx(0) axis_thetag.Draw("same") # Draw LaTeX y_latex = y_latex_top list_latex_mc = [] for text_latex in [ text_alice_sim, text_jets, text_ptjet, text_pth, text_ptcut_sim, text_sd ]: latex = TLatex(x_latex, y_latex, text_latex) list_latex_mc.append(latex) draw_latex(latex, textsize=fontsize) y_latex -= y_step cshape_mc.Update() cshape_mc.SaveAs("%s/%s_mc_%s.pdf" % (rootpath, shape, suffix)) # PYTHIA, HF, quark, gluon #leg_pos = [.6, .65, .75, .85] leg_pos = [.72, .61, .85, .85] list_obj = [ quark_pythia_syst, gluon_pythia_syst, hf_pythia_stat, quark_pythia_stat, gluon_pythia_stat ] labels_obj = ["quark", "gluon", "%s-tagged" % p_latexnhadron] colours = [ get_colour(i, j) for i, j in zip((c_quark_mc, c_gluon_mc, c_hf_mc, c_quark_mc, c_gluon_mc), (2, 2, 1, 1, 1)) ] markers = [m_quark_mc, m_gluon_mc, m_hf_mc, m_quark_mc, m_gluon_mc] y_margin_up = 0.46 y_margin_down = 0.05 cshape_mc, list_obj_mc_new = make_plot("cshape_mc_qgd_" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, range_y=[y_min_plot, y_max_plot], margins_c=margins_can, \ title=title_full) cshape_mc.Update() for gr, c in zip((quark_pythia_syst, gluon_pythia_syst), (c_quark_mc, c_gluon_mc)): gr.SetMarkerColor(get_colour(c)) leg_mc = list_obj_mc_new[0] leg_mc.SetTextSize(fontsize) leg_mc.SetHeader(text_pythia_split) if shape == "nsd": quark_pythia_syst.GetXaxis().SetNdivisions(5) cshape_mc.Update() if shape == "rg": # plot the theta_g axis axis_rg = hf_pythia_stat.GetXaxis() rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst()) rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast()) thetag_min = rg_min / radius_jet thetag_max = rg_max / radius_jet y_axis = cshape_mc.GetUymax() axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min, thetag_max, 510, "-") axis_thetag.SetTitle(title_thetag) axis_thetag.SetTitleSize(size_thg) axis_thetag.SetLabelSize(0.036) axis_thetag.SetTitleFont(42) axis_thetag.SetLabelFont(42) axis_thetag.SetLabelOffset(0) axis_thetag.SetTitleOffset(offset_thg) cshape_mc.SetTickx(0) axis_thetag.Draw("same") # Draw LaTeX y_latex = y_latex_top list_latex_mc = [] for text_latex in [ text_alice_sim, text_jets, text_ptjet, text_pth, text_ptcut_sim, text_sd ]: latex = TLatex(x_latex, y_latex, text_latex) list_latex_mc.append(latex) draw_latex(latex, textsize=fontsize) y_latex -= y_step cshape_mc.Update() cshape_mc.SaveAs("%s/%s_mc_qgd_%s.pdf" % (rootpath, shape, suffix)) # PYTHIA, HF, inclusive #leg_pos = [.6, .65, .75, .85] leg_pos = [.72, .67, .85, .85] list_obj = [incl_pythia_syst_cl, incl_pythia_stat, hf_pythia_stat] labels_obj = ["inclusive", "", "%s-tagged" % p_latexnhadron] colours = [ get_colour(i, j) for i, j in zip((c_incl_mc, c_incl_mc, c_hf_mc), (2, 1, 1)) ] markers = [m_incl_mc, m_incl_mc, m_hf_mc] y_margin_up = 0.46 y_margin_down = 0.05 cshape_mc, list_obj_mc_new = make_plot("cshape_mc_id_" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, range_y=[y_min_plot, y_max_plot], margins_c=margins_can, \ title=title_full) # Draw a line through the points. if shape == "nsd": for h in (incl_pythia_stat, hf_pythia_stat): h_line = h.Clone(h.GetName() + "_line") h_line.SetLineStyle(2) h_line.Draw("l hist same") list_new.append(h_line) cshape_mc.Update() incl_pythia_syst_cl.SetMarkerColor(get_colour(c_incl_mc)) leg_mc = list_obj_mc_new[0] leg_mc.SetTextSize(fontsize) leg_mc.SetHeader(text_pythia_split) if shape == "nsd": incl_pythia_syst_cl.GetXaxis().SetNdivisions(5) cshape_mc.Update() if shape == "rg": # plot the theta_g axis axis_rg = hf_pythia_stat.GetXaxis() rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst()) rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast()) thetag_min = rg_min / radius_jet thetag_max = rg_max / radius_jet y_axis = cshape_mc.GetUymax() axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min, thetag_max, 510, "-") axis_thetag.SetTitle(title_thetag) axis_thetag.SetTitleSize(size_thg) axis_thetag.SetLabelSize(0.036) axis_thetag.SetTitleFont(42) axis_thetag.SetLabelFont(42) axis_thetag.SetLabelOffset(0) axis_thetag.SetTitleOffset(offset_thg) cshape_mc.SetTickx(0) axis_thetag.Draw("same") # Draw LaTeX y_latex = y_latex_top list_latex_mc = [] for text_latex in [ text_alice_sim, text_jets, text_ptjet, text_pth, text_ptcut_sim, text_sd ]: latex = TLatex(x_latex, y_latex, text_latex) list_latex_mc.append(latex) draw_latex(latex, textsize=fontsize) y_latex -= y_step cshape_mc.Update() cshape_mc.SaveAs("%s/%s_mc_id_%s.pdf" % (rootpath, shape, suffix)) # data inclusive vs PYTHIA, quark, gluon #leg_pos = [.6, .65, .75, .85] #leg_pos = [.72, .55, .85, .85] leg_pos = [.6, .7, .85, .85] list_obj = [ incl_data_syst, quark_pythia_syst, gluon_pythia_syst, incl_data_stat, quark_pythia_stat, gluon_pythia_stat ] labels_obj = ["inclusive (data)", "quark (PYTHIA 8)", "gluon (PYTHIA 8)"] colours = [ get_colour(i, j) for i, j in zip((c_incl_data, c_quark_mc, c_gluon_mc, c_incl_data, c_quark_mc, c_gluon_mc), (2, 2, 2, 1, 1, 1)) ] markers = [ m_incl_data, m_quark_mc, m_gluon_mc, m_incl_data, m_quark_mc, m_gluon_mc ] y_margin_up = 0.3 y_margin_down = 0.05 cshape_mc, list_obj_mc_new = make_plot("cshape_mc_data_iqg" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \ title=title_full) for gr, c in zip((incl_data_syst, quark_pythia_syst, gluon_pythia_syst), (c_incl_data, c_quark_mc, c_gluon_mc)): gr.SetMarkerColor(get_colour(c)) leg_mc = list_obj_mc_new[0] leg_mc.SetTextSize(fontsize) cshape_mc.Update() cshape_mc.SaveAs("%s/%s_data_i_mc_qg_%s.pdf" % (rootpath, shape, suffix))
all_graphs[0].SetMinimum(calo_init.args.axisMin) canv.Update() lines = [] for iLine, line in enumerate(avgSF): lines.append(TLine(0, avgSF[iLine], Nslices * sliceWidth, avgSF[iLine])) lines[iLine].SetLineColor(iLine + 1) lines[iLine].Draw('same') # add second axis canv.SetRightMargin(0.1) all_graphs[0].GetXaxis().SetRangeUser(0, 68) all_graphs[0].GetXaxis().SetLabelOffset(0.02) gPad.RangeAxis(0, gPad.GetUymin(), 68, gPad.GetUxmax()) axis = TGaxis(gPad.GetUxmin(), gPad.GetUymin(), gPad.GetUxmax(), gPad.GetUymin(), gPad.GetUxmin() * calo_init.args.X0density, gPad.GetUxmax() * calo_init.args.X0density, 506, "-") axis.SetLabelSize(0.05) axis.SetTitleSize(0.07) axis.SetTitleOffset(0.9) axis.SetLabelOffset(0.02) axis.Draw() axis.SetLabelFont(42) unit1 = draw_text(['(cm)'], [0.91, 0.09, 1, 0.14], 1, 0) unit1.SetTextSize(0.05) unit1.SetTextFont(42) unit2 = draw_text(['(X_{0})'], [0.91, 0.16, 1, 0.21], 1, 0) unit2.SetTextSize(0.05) unit2.SetTextFont(42) canv.Update()
def plot_proj_both(frame2, frame_east, frame_west, adc_bin, adc_min, adc_max, ptmax, mmin, mmax): can = ut.box_canvas(800, 700) #900, 700 xp = Double(0) yp = Double(0) #east data on the left hEast = frame_east.getHist("data") plot_east = frame2.Clone("plot_east") plot_east.SetMarkerStyle(22) plot_east.SetMarkerSize(1.4) ut.set_H1D_col(plot_east, rt.kBlue) for ibin in xrange(hEast.GetN()): hEast.GetPoint(ibin, xp, yp) plot_east.SetBinContent(ibin + 1, yp) plot_east.SetBinError(ibin + 1, hEast.GetErrorY(ibin)) frame2.SetMaximum(1.2 * plot_east.GetMaximum()) # 1.15 #west data on the right hWest = frame_west.getHist("data") plot_west = frame2.Clone("plot_west") plot_west.SetMarkerStyle(21) ut.set_H1D_col(plot_west, rt.kRed) for i in xrange(hWest.GetN()): hWest.GetPoint(i, xp, yp) ibin = frame2.GetNbinsX() - i plot_west.SetBinContent(ibin, yp) plot_west.SetBinError(ibin, hWest.GetErrorY(i)) #east fit cEast = frame_east.getCurve("model") gEast = TGraph(cEast.GetN() - 1) for i in xrange(cEast.GetN() - 1): cEast.GetPoint(i, xp, yp) gEast.SetPoint(i, xp, yp) gEast.SetLineColor(rt.kBlue) gEast.SetLineWidth(3) gEast.SetLineStyle(rt.kDashed) #gEast.SetLineStyle(rt.kDashDotted) #west fit on the left cWest = frame_west.getCurve("model") gWest = TGraph(cWest.GetN() - 1) xmax = frame2.GetBinCenter( frame2.GetNbinsX()) + frame2.GetBinWidth(frame2.GetNbinsX()) / 2. for i in xrange(cWest.GetN() - 1): cWest.GetPoint(i, xp, yp) xplot = xmax - xp gWest.SetPoint(i, xplot, yp) gWest.SetLineColor(rt.kRed) gWest.SetLineWidth(3) #gWest.SetLineStyle(rt.kDashDotted) #gWest.SetLineStyle(rt.kDashed) #horizontal axis frame2.SetMinimum(0) #frame2.SetMinimum(0.98) frame2.GetXaxis().SetNdivisions(0, rt.kFALSE) #east axis ypos = frame2.GetYaxis().GetXmin() axisE = TGaxis(adc_min, ypos, adc_max, ypos, adc_min, adc_max) ut.set_axis(axisE) axisE.SetWmin(axisE.GetWmin() * 0.01) axisE.SetWmax(axisE.GetWmax() * 0.01) axisE.SetTitle("ZDC East #times100") axisE.SetTitleOffset(1.1) #west axis xpos = frame2.GetXaxis().GetXmax() axisW = TGaxis(xpos, ypos, xpos - adc_max, ypos, adc_min, adc_max, 510, "-") ut.set_axis(axisW) axisW.SetWmin(axisW.GetWmin() * 0.01) axisW.SetWmax(axisW.GetWmax() * 0.01) axisW.SetLabelOffset(-0.024) axisW.SetTitle("ZDC West #times100") axisW.SetTitleOffset(1.1) #vertical axis yvpos = 1. * frame2.GetMaximum() axisV = TGaxis(xpos, 0, xpos, yvpos, 0, yvpos, 510, "+L") #axisV = TGaxis(xpos, 0, xpos, yvpos, 0.98, yvpos, 510, "+G") ut.set_axis(axisV) frame2.SetYTitle("ZDC East / ({0:.0f} ADC units)".format(adc_bin)) axisV.SetTitle("ZDC West / ({0:.0f} ADC units)".format(adc_bin)) frame2.GetYaxis().SetTitleOffset(1.5) axisV.SetTitleOffset(1.5) gPad.SetTopMargin(0.05) # 0.01 gPad.SetRightMargin(0.1) gPad.SetBottomMargin(0.08) gPad.SetLeftMargin(0.1) frame2.Draw() plot_east.Draw("e1same") plot_west.Draw("e1same") gEast.Draw("lsame") gWest.Draw("lsame") axisE.Draw() axisW.Draw() axisV.Draw() #kinematics legend #kleg = ut.prepare_leg(0.16, 0.78, 0.32, 0.2, 0.035) kleg = ut.prepare_leg(0.16, 0.73, 0.32, 0.2, 0.035) kleg.AddEntry(None, "AuAu@200 GeV", "") kleg.AddEntry(None, "UPC sample", "") ut.add_leg_pt_mass(kleg, ptmax, mmin, mmax) kleg.Draw("same") #data legend dleg = ut.prepare_leg(0.6, 0.8, 0.15, 0.08, 0.03) dleg.AddEntry(plot_east, "ZDC East", "p") dleg.AddEntry(plot_west, "ZDC West", "p") #dleg.Draw("same") #projections legend #pleg = ut.prepare_leg(0.24, 0.56, 0.25, 0.2, 0.035) pleg = ut.prepare_leg(0.24, 0.51, 0.25, 0.2, 0.035) pleg.AddEntry(plot_east, "ZDC East", "p") pleg.AddEntry(plot_west, "ZDC West", "p") pleg.AddEntry(gEast, "Fit projection to east", "l") pleg.AddEntry(gWest, "Fit projection to west", "l") pleg.Draw("same") #gPad.SetLogy() #gPad.SetGrid() #ut.invert_col(gPad) can.SaveAs("01fig.pdf")
def PlotOnCanvas(self, pdf_name): #gROOT.SetBatch(False) tdrstyle.setTDRStyle() canvas = TCanvas("c1", "c1", 600, 600) pad1 = TPad("pad1", "pad1", 0, 0.0, 1, 1.0) pad1.SetBottomMargin(0.32) pad1.SetGridx() pad1.Draw() pad1.cd() self.histo1.SetStats(0) self.histo1.Draw(self.option) self.histo2.Draw(self.option + " same") if self.logx: pad1.SetLogx() if self.logy: pad1.SetLogy() legend = TLegend(0.65, 0.7, 0.85, 0.83) legend.SetHeader("Legend", "C") legend.AddEntry(self.histo1, self.legend1, "l") legend.AddEntry(self.histo2, self.legend2, "l") legend.Draw() # Redraw axis to avoid clipping 0 self.histo1.GetXaxis().SetLabelSize(0.) self.histo1.GetXaxis().SetTitle('') axis = TGaxis(-9, -2.8, -9, 2.8, 0, 10000, 50510, "") axis.SetLabelFont(43) axis.SetLabelSize(15) axis.Draw("same") pad2 = TPad("pad2", "pad2", 0, 0.0, 1, 0.3) pad2.SetTopMargin(0) pad2.SetBottomMargin(0.4) pad2.SetGridx() pad2.Draw() pad2.cd() if self.logx: pad2.SetLogx() self.ratio.SetLineColor(ROOT.kBlack) self.ratio.SetMinimum(0.5) self.ratio.SetMaximum(1.5) self.ratio.SetStats(0) self.ratio.SetMarkerStyle(21) self.ratio.Draw("ep") self.histo1.SetLineColor(ROOT.kBlue + 1) self.histo1.SetLineWidth(2) max_y = max(self.histo1.GetMaximum(), self.histo2.GetMaximum()) self.histo1.SetMaximum(max_y * 1.1) self.histo1.GetYaxis().SetNdivisions(505) self.histo1.GetYaxis().SetTitleSize(20) self.histo1.GetYaxis().SetTitleFont(43) self.histo1.GetYaxis().SetTitleOffset(1.8) self.histo2.SetLineColor(ROOT.kRed) self.histo2.SetLineWidth(2) self.ratio.SetTitle("") self.ratio.GetYaxis().SetTitle("Ratio") self.ratio.GetYaxis().SetNdivisions(505) self.ratio.GetYaxis().SetTitleSize(20) self.ratio.GetYaxis().SetTitleFont(43) self.ratio.GetYaxis().SetTitleOffset(1.8) self.ratio.GetYaxis().SetLabelFont(43) self.ratio.GetYaxis().SetLabelSize(15) self.ratio.GetXaxis().SetNdivisions(510) self.ratio.GetXaxis().SetTitleSize(20) self.ratio.GetXaxis().SetTitleFont(43) self.ratio.GetXaxis().SetTitleOffset(4.) self.ratio.GetXaxis().SetLabelFont(43) self.ratio.GetXaxis().SetLabelSize(15) ROOT.SetOwnership(canvas, False) ROOT.SetOwnership(pad1, False) ROOT.SetOwnership(pad2, False) canvas.Print(pdf_name, 'Title:' + self.title) canvas.Close()