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 SaveRatio(hSS, hOS, process, output): idata = process.split('_')[0] suffix = process.split('_ss_')[-1] #print "hSS : " , hSS #print "hOS : " , hOS name = '%s_%s' % (idata, suffix) hratio = hSS.Clone('hratio_%s' % name) hratio.Divide(hOS) hratio.SetMarkerStyle(20) hratio.SetMarkerSize(1.25) hratio.SetFillColor(418) hratio.SetFillStyle(1001) hratio.SetLineColor(1) hratio.SetLineStyle(1) hratio.SetLineWidth(2) c1 = TCanvas('hratio_%s' % name, 'hratio_%s' % name, 800, 600) if suffix.split('_')[-1] == '2d': TGaxis.SetMaxDigits(2) #fout = TFile.Open( 'plots/%s/Object_studies/Ratio_%s_%s_%s.root' %(_token,_token,_isample,_ivar), 'RECREATE' ) c1.SetRightMargin(0.2) hratio.SetAxisRange(0.00001, 0.01, "Z") hratio.SetTitle('') hratio.GetZaxis().SetTitle('N_SS/N_OS (%s)' % idata) hratio.GetXaxis().SetTitle('Lepton1 eta') hratio.GetYaxis().SetTitle('Lepton2 eta') hratio.Draw('colztextE') else: hratio.SetTitle('') hratio.GetYaxis().SetTitle('N_SS/N_OS Ratio (%s)' % idata) hratio.Draw('PE') c1.cd() if '2016' in output: CMS_lumi.lumi_13TeV = "35.87 fb^{-1}" elif '2017' in output: CMS_lumi.lumi_13TeV = "41.53 fb^{-1}" elif '2018' in output: CMS_lumi.lumi_13TeV = "59.74 fb^{-1}" CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Preliminary" CMS_lumi.CMS_lumi(c1, 4, 0) gPad.RedrawAxis() #c1.cd() #if '2016' in _token: # drawCMS("35.87", "Object Study") #elif '2017' in _token: # drawCMS("41.53", "Object Study") #elif '2018' in _token: # drawCMS("59.74", "Object Study") c1.Print('%s/Ratio_%s.png' % (output, name)) #c1.Print( '%s/Ratio_%s.pdf' %(output,name) ) TGaxis.SetMaxDigits(5)
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 SetStyle(): gROOT.SetStyle('Plain') gROOT.ForceStyle() gStyle.SetTextFont(42) gStyle.SetOptTitle(0) gStyle.SetOptFit(1112) gStyle.SetOptStat(1110) gStyle.SetPadRightMargin(0.08) gStyle.SetPadTopMargin(0.11) gStyle.SetPadBottomMargin(0.12) gStyle.SetTitleFont(42, 'x') gStyle.SetTitleFont(42, 'y') gStyle.SetTitleFont(42, 'z') gStyle.SetTitleOffset(1.05, 'x') gStyle.SetTitleOffset(1.00, 'y') gStyle.SetTitleSize(0.05, 'x') gStyle.SetTitleSize(0.05, 'y') gStyle.SetTitleSize(0.05, 'z') gStyle.SetLabelFont(42, 'x') gStyle.SetLabelFont(42, 'y') gStyle.SetLabelFont(42, 'z') gStyle.SetLabelSize(0.05, 'x') gStyle.SetLabelSize(0.05, 'y') gStyle.SetLabelSize(0.05, 'z') TGaxis.SetMaxDigits(3) gStyle.SetStatY(0.9)
def secondary_vertex_reco_MC(file): gStyle.SetOptStat(0) TGaxis.SetMaxDigits(3) components_list = ["x", "y", "z"] color_list = [1, 2, 4] csecvertex = TCanvas("c1", "Secondary Vertex Difference") csecvertex.SetCanvasSize(1000, 700) csecvertex.cd() secvertex_list = [] leg = TLegend(0.1, 0.7, 0.4, 0.9, "Sec. Vertex:") leg.SetFillColor(0) for i, comp in enumerate(components_list): hsecvertex = file.Get("hf-mc-validation-rec/histSecV%s" % comp) hsecvertex.Rebin(1) hsecvertex.SetLineColor(color_list[i]) hsecvertex.SetLineWidth(2) secvertex_list.append(hsecvertex) if i != 0: hsecvertex.Draw("same") else: hsecvertex.SetTitle("Secondary Vertex difference Rec-Gen") hsecvertex.GetXaxis().SetTitle("V_{i}^{reco}-V_{i}^{gen} (cm)") hsecvertex.Draw() leg.AddEntry(secvertex_list[i], "%s component" % comp) leg.Draw() printCanvas(csecvertex, "SecVertex_recoMC_diff")
def __init__(self): super(StyleClass, self).__init__("CRRootStyle", "CRRootStyle") self.root_style_settings() self.cd() gROOT.SetStyle("CRRootStyle") gROOT.ForceStyle() TGaxis.SetMaxDigits(3)
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 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 Styling(): # Center title gStyle.SetTitleAlign(22) gStyle.SetTitleX(.5) gStyle.SetTitleY(.95) gStyle.SetTitleBorderSize(0) # Remove stats box gStyle.SetOptStat(0) # Set background color to white gStyle.SetFillColor(10) gStyle.SetFrameFillColor(10) gStyle.SetCanvasColor(10) gStyle.SetPadColor(10) gStyle.SetTitleFillColor(0) gStyle.SetStatColor(10) # No colored frames around plots gStyle.SetFrameBorderMode(0) gStyle.SetCanvasBorderMode(0) gStyle.SetPadBorderMode(0) # Set the default line color for a fit function to be red gStyle.SetFuncColor(2) # Marker settings gStyle.SetMarkerStyle(20) # No border on legends gStyle.SetLegendBorderSize(0) # Disabled for violating NOvA style guidelines # Scientific notation on axes TGaxis.SetMaxDigits(3) # Axis titles gStyle.SetTitleSize(.055, "xyz") gStyle.SetTitleOffset(2.2, "xyz") gStyle.SetTitleOffset(2.2, "y") gStyle.SetTitleSize(.05, "") gStyle.SetTitleOffset(2.2, "") # Axis labels (numbering) gStyle.SetLabelSize(.05, "xyz") gStyle.SetLabelOffset(.005, "xyz") # Thicker lines gStyle.SetHistLineWidth(2) gStyle.SetFrameLineWidth(2) gStyle.SetFuncWidth(2) # Set the number of tick marks gStyle.SetNdivisions(506, "xyz") # Set tick marks on all sides gStyle.SetPadTickX(1) gStyle.SetPadTickY(1) # Fonts kNovaFont = 42 gStyle.SetStatFont(kNovaFont) gStyle.SetLabelFont(kNovaFont, "xyz") gStyle.SetTitleFont(kNovaFont, "xyz") gStyle.SetTitleFont(kNovaFont, "") # Apply same settings to titles gStyle.SetTextFont(kNovaFont) gStyle.SetLegendFont(kNovaFont)
def __init__(self): ''' Set up PlotStyle, set gStyle for things we always want no matter what. ''' # CMS-approved everything tdrstyle.setTDRStyle() ### Differences from TDR standard: # Big canvas (can always shrink later) gStyle.SetCanvasDefH(1200) gStyle.SetCanvasDefW(1200) # Tick marks on all sides gStyle.SetPadTickX(1) gStyle.SetPadTickY(1) # Everything has white backgrounds gStyle.SetLegendFillColor(0) # Colors that don't suck gStyle.SetPalette(1) # Make axis title and labels just a little smaller and (for Y) closer to the axis gStyle.SetTitleSize(0.044, "XYZ") gStyle.SetLabelSize(0.033, "XYZ") gStyle.SetTitleYOffset(1.15) gStyle.SetTitleXOffset(0.95) gStyle.SetPadLeftMargin(0.1) gStyle.SetPadRightMargin(0.025) gStyle.SetPadBottomMargin(0.095) gStyle.SetTitleAlign(12) # Apply changes gROOT.ForceStyle() # Force exponentials when axes are over 3 digits TGaxis.SetMaxDigits(3) TGaxis.SetExponentOffset(-0.060, 0.008, "y") TGaxis.SetExponentOffset( -0.055, -0.062, "x") # will overlap with title unless title is centered
def SetCanvas(self): self.canvas = None self.plot = None self.ratio = None c = TCanvas('c', 'c', 10, 10, 1600, 1200) if self.doRatio: c.Divide(1, 2) plot = c.GetPad(1) ratio = c.GetPad(2) else: plot = c.GetPad(0) #if self.doRatio: plot.SetPad(self.hpadx0, self.hpady0, self.hpadx1, self.hpady1) plot.SetMargin(self.hpadMleft, self.hpadMright, self.hpadMbottom, self.hpadMtop) #else: plot = c.GetPad(0) if self.doRatio: ratio.SetPad(self.rpadx0, self.rpady0, self.rpadx1, self.rpady1) ratio.SetMargin(self.rpadMleft, self.rpadMright, self.rpadMbottom, self.rpadMtop) else: #ratio.SetPad(0,0,0,0) plot.SetPad(0, 0, 1, 1) # Draw the text texcms = self.DrawTextCMS() texmod = self.DrawTextCMSmode() texlum = self.DrawTextLumi() self.Tex.append(texcms) self.Tex.append(texmod) self.Tex.append(texlum) if hasattr(self, 'texch') and self.texch != '': tch = TLatex(-20, 50, self.texch) tch.SetNDC() tch.SetTextAlign(12) tch.SetX(self.texchX) tch.SetY(self.texchY) tch.SetTextFont(42) tch.SetTextSize(self.texchS) self.Tex.append(tch) for r in self.Tex: r.Draw() TGaxis.SetMaxDigits(3) if self.doSetLogY: plot.SetLogy() # Legend self.legend = self.SetLegend() self.legendRatio = self.SetLegendRatio() self.canvas = c self.plot = plot if self.doRatio: self.ratio = ratio
def chips_style(): print("\nLet's make it look cheap... \n") chips_style = TStyle("chips_style", "CHIPS Style") # Center title chips_style.SetTitleAlign(22) chips_style.SetTitleX(.5) chips_style.SetTitleY(.95) chips_style.SetTitleBorderSize(0) # Remove stats box chips_style.SetOptStat(0) # Set background color to white chips_style.SetFillColor(10) chips_style.SetFrameFillColor(10) chips_style.SetCanvasColor(10) chips_style.SetPadColor(10) chips_style.SetTitleFillColor(0) chips_style.SetStatColor(10) # No colored frames around plots chips_style.SetFrameBorderMode(0) chips_style.SetCanvasBorderMode(0) chips_style.SetPadBorderMode(0) # Set the default line color for a fit function to be red chips_style.SetFuncColor(2) # Marker settings chips_style.SetMarkerStyle(20) # No border on legends chips_style.SetLegendBorderSize(0) # Disabled for violating NOvA style guidelines # Scientific notation on axes TGaxis.SetMaxDigits(3) # Axis titles chips_style.SetTitleSize(.055, "xyz") chips_style.SetTitleOffset(.8, "xyz") chips_style.SetTitleOffset(.9, "y") chips_style.SetTitleSize(.055, "") chips_style.SetTitleOffset(.8, "") # Axis labels (numbering) chips_style.SetLabelSize(.04, "xyz") chips_style.SetLabelOffset(.005, "xyz") # Set histogram minimum to exactly zero chips_style.SetHistMinimumZero()
def SetAxis(plot): # Global settings from TGaxis TGaxis.SetMaxDigits(4) TGaxis.SetExponentOffset(-1000, -1000) # X-axis settings x = plot.GetXaxis() x.SetLabelFont(FONT_TYPE) x.SetTitleFont(FONT_TYPE) x.SetLabelSize(AXIS_LABEL_FONT_SIZE) x.SetTitleSize(AXIS_TITLE_FONT_SIZE) # Y-axis settings y = plot.GetYaxis() y.SetLabelFont(FONT_TYPE) y.SetTitleFont(FONT_TYPE) y.SetLabelSize(AXIS_LABEL_FONT_SIZE) y.SetTitleSize(AXIS_TITLE_FONT_SIZE) y.SetTitleOffset(1.2) if plot.GetMaximum() >= 10000: y.SetTitle(y.GetTitle() + " x 10^{3}")
def initStyle(config): from ROOT import gROOT, gStyle, TStyle, TGaxis gROOT.SetBatch(True) gROOT.SetStyle('Plain') gStyle.SetOptStat(0) gStyle.SetPalette(1) gStyle.SetPaintTextFormat(".2g") TGaxis.SetMaxDigits(3) pageSize = config.get("styleDefaults","pageSize") if pageSize.lower() == "a4": gStyle.SetPaperSize(TStyle.kA4) elif pageSize.lower() == "letter": gStyle.SetPaperSize(TStyle.kUSLetter) else: pageSize = [int(i) for i in pageSize.split("x")] gStyle.SetPaperSize(pageSize[0],pageSize[1])
def fixXExponent(self, canvas): ''' If there's an exponent on the Y axis, it will either be in a weird place or it will overlap with the axis title. We fix the placement in __init__(), but we still have to move the title if need be. Recursive, so we find histograms in pads in pads. ''' for obj in canvas.GetListOfPrimitives(): if obj.InheritsFrom(TH1.Class()) or obj.InheritsFrom( THStack.Class()): axis = obj.GetXaxis() if axis.GetXmax() >= 10**TGaxis.GetMaxDigits(): # has exponent axis.CenterTitle() if obj.InheritsFrom(TPad.Class()): self.fixXExponent(obj)
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
T = 0.08 * H B = 0.12 * H L = 0.12 * W R = 0.1 * W legendHeightPer = 0.04 legendStart = 0.6 legendEnd = 0.97 - (R / W) # legend = TLegend(0.7,0.7,0.88,0.88) legend = TLegend(legendStart, 1 - T / H - 0.01 - legendHeightPer * (6), legendEnd, 0.99 - (T / H) - 0.01) legend.SetBorderSize(0) legend.SetFillColor(0) legend.SetHeader(myDir[idir], "L") TGaxis.SetMaxDigits(3) c = TCanvas('c', '', W, H) c.SetFillColor(0) c.SetBorderMode(0) c.SetFrameFillStyle(0) c.SetFrameBorderMode(0) c.SetLeftMargin(L / W) c.SetRightMargin(R / W) c.SetTopMargin(T / H) c.SetBottomMargin(B / H) c.SetTickx(0) c.SetTicky(0) c.Draw() c.cd()
def setCMSLumiStyle(pad, iPosX, **kwargs): global outOfFrame, lumiTextSize, lumiText if iPosX / 10 == 0: outOfFrame = True lumiTextSize_ = lumiTextSize relPosX_ = kwargs.get('relPosX', relPosX) lumiText_ = kwargs.get('lumiText', lumiText) if outOfFrame: lumiTextSize_ *= 0.90 if 'era' in kwargs: # one era era = kwargs.get('era') setCMSEra(era, **kwargs) elif 'eras' in kwargs: # list of multiple eras eras = kwargs.get('eras') setCMSEra(*eras, **kwargs) #if lumiText=="": # if iPeriod==1: # lumiText += lumi_7TeV # lumiText += " (7 TeV)" # elif iPeriod==2: # lumiText += lumi_8TeV # lumiText += " (8 TeV)" # elif iPeriod==3: # lumiText = lumi_8TeV # lumiText += " (8 TeV)" # lumiText += " + " # lumiText += lumi_7TeV # lumiText += " (7 TeV)" # elif iPeriod==4: # lumiText += lumi_13TeV # lumiText += " (13 TeV)" # elif iPeriod==7: # if outOfFrame: lumiTextSize_ *= 0.85 # lumiText += lumi_13TeV # lumiText += " (13 TeV)" # lumiText += " + " # lumiText += lumi_8TeV # lumiText += " (8 TeV)" # lumiText += " + " # lumiText += lumi_7TeV # lumiText += " (7 TeV)" # elif iPeriod==12: # lumiText += "8 TeV" # else: # if outOfFrame: lumiTextSize_ *= 0.90 # if iPeriod==13: # lumiText += lumi_13TeV # lumiText += " (13 TeV)" # elif iPeriod==2016: # lumiText += lumi_2016 # lumiText += " (13 TeV)" # elif iPeriod==2017: # lumiText += lumi_2017 # lumiText += " (13 TeV)" # elif iPeriod==2018: # lumiText += lumi_2018 # lumiText += " (13 TeV)" # elif iPeriod==14: # lumiText += lumi_14TeV # lumiText += " (14 TeV, 200 PU)" ##print lumiText alignY_ = 3 alignX_ = 2 if iPosX == 0: alignY_ = 1 if iPosX / 10 == 0: alignX_ = 1 elif iPosX / 10 == 1: alignX_ = 1 elif iPosX / 10 == 2: alignX_ = 2 elif iPosX / 10 == 3: alignX_ = 3 align = 10 * alignX_ + alignY_ extraTextSize = extraOverCmsTextSize * cmsTextSize H = pad.GetWh() * pad.GetHNDC() W = pad.GetWw() * pad.GetWNDC() l = pad.GetLeftMargin() t = pad.GetTopMargin() r = pad.GetRightMargin() b = pad.GetBottomMargin() e = 0.025 scale = float(H) / W if W > H else 1 # float(W)/H pad.cd() latex = TLatex() latex.SetNDC() latex.SetTextAngle(0) latex.SetTextColor(kBlack) latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(lumiTextSize_ * t) if lumiText_: latex.DrawLatex(1 - r, 1 - t + lumiTextOffset * t, lumiText_) if iPosX == 0: relPosX_ = relPosX_ * (50 * t * scale) * (cmsTextSize / 0.84) posX = l + relPosX_ * (1 - l - r) posY = 1 - t + lumiTextOffset * t else: posX = 0 posY = 1 - t - relPosY * (1 - t - b) if iPosX % 10 <= 1: posX = l + relPosX_ * (1 - l - r) # left aligned elif iPosX % 10 == 2: posX = l + 0.5 * (1 - l - r) # centered elif iPosX % 10 == 3: posX = 1 - r - relPosX_ * (1 - l - r) # right aligned if outOfFrame: TGaxis.SetExponentOffset(-0.12 * float(H) / W, 0.015, 'y') latex.SetTextFont(cmsTextFont) latex.SetTextAlign(11) latex.SetTextSize(cmsTextSize * t) latex.DrawLatex(l, 1 - t + lumiTextOffset * t, cmsText) if writeExtraText: latex.SetTextFont(extraTextFont) latex.SetTextSize(extraTextSize * t) latex.SetTextAlign(align) latex.DrawLatex(posX, posY, extraText) elif drawLogo: posX = l + 0.045 * (1 - l - r) * W / H posY = 1 - t - 0.045 * (1 - t - b) xl_0 = posX yl_0 = posY - 0.15 xl_1 = posX + 0.15 * H / W yl_1 = posY CMS_logo = TASImage("CMS-BW-label.png") pad_logo = TPad("logo", "logo", xl_0, yl_0, xl_1, yl_1) pad_logo.Draw() pad_logo.cd() CMS_logo.Draw('X') pad_logo.Modified() pad.cd() else: latex.SetTextFont(cmsTextFont) latex.SetTextSize(cmsTextSize * t) latex.SetTextAlign(align) latex.DrawLatex(posX, posY, cmsText) if writeExtraText: latex.SetTextFont(extraTextFont) latex.SetTextAlign(align) latex.SetTextSize(extraTextSize * t) latex.DrawLatex(posX, posY - relExtraDY * cmsTextSize * t, extraText) pad.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")
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()
def SetGlobalStyle(**kwargs): ''' Method to set global style. Parameters ---------- - padrightmargin (float), default = 0.035 - padleftmargin (float), default = 0.12 - padtopmargin (float), default = 0.035 - padbottommargin (float), default = 0.12 - titlesize (float), default = 0.050 - titlesizex (float), default = 0.050 - titlesizey (float), default = 0.050 - titlesizez (float), default = 0.050 - labelsize (float), default = 0.045 - labelsizex (float), default = 0.045 - labelsizey (float), default = 0.045 - labelsizez (float), default = 0.045 - titleoffset (float), default = 1.2 - titleoffsetx (float), default = 1.2 - titleoffsey (float), default = 1.2 - titleoffsetz (float), default = 1.2 - opttitle (int), default = 0 - optstat (int), default = 0 - padtickx (int), default = 1 - padticky (int), default = 1 - maxdigits (int), default no max value - palette (int), default kBird ''' # pad margins if 'padrightmargin' in kwargs: gStyle.SetPadRightMargin(kwargs['padrightmargin']) else: gStyle.SetPadRightMargin(0.035) if 'padleftmargin' in kwargs: gStyle.SetPadLeftMargin(kwargs['padleftmargin']) else: gStyle.SetPadLeftMargin(0.12) if 'padtopmargin' in kwargs: gStyle.SetPadTopMargin(kwargs['padtopmargin']) else: gStyle.SetPadTopMargin(0.035) if 'padbottommargin' in kwargs: gStyle.SetPadBottomMargin(kwargs['padbottommargin']) else: gStyle.SetPadBottomMargin(0.1) # title sizes if 'titlesize' in kwargs: gStyle.SetTitleSize(kwargs['titlesize'], 'xyz') else: gStyle.SetTitleSize(0.050, 'xyz') if 'titlesizex' in kwargs: gStyle.SetTitleSize(kwargs['titlesizex'], 'x') if 'titlesizey' in kwargs: gStyle.SetTitleSize(kwargs['titlesizex'], 'y') if 'titlesizez' in kwargs: gStyle.SetTitleSize(kwargs['titlesizex'], 'z') # label sizes if 'labelsize' in kwargs: gStyle.SetLabelSize(kwargs['labelsize'], 'xyz') else: gStyle.SetLabelSize(0.045, 'xyz') if 'labelsizex' in kwargs: gStyle.SetLabelSize(kwargs['labelsizex'], 'x') if 'labelsizey' in kwargs: gStyle.SetLabelSize(kwargs['labelsizex'], 'y') if 'labelsizez' in kwargs: gStyle.SetLabelSize(kwargs['labelsizex'], 'z') # title offsets if 'titleoffset' in kwargs: gStyle.SetTitleOffset(kwargs['titleoffset'], 'xyz') else: gStyle.SetTitleOffset(1.2, 'xyz') if 'titleoffsetx' in kwargs: gStyle.SetTitleOffset(kwargs['titleoffsetx'], 'x') if 'titleoffsety' in kwargs: gStyle.SetTitleOffset(kwargs['titleoffsety'], 'y') if 'titleoffsetz' in kwargs: gStyle.SetTitleOffset(kwargs['titleoffsetz'], 'z') # other options if 'opttitle' in kwargs: gStyle.SetOptTitle(kwargs['opttitle']) else: gStyle.SetOptTitle(0) if 'optstat' in kwargs: gStyle.SetOptStat(kwargs['optstat']) else: gStyle.SetOptStat(0) if 'padtickx' in kwargs: gStyle.SetPadTickX(kwargs['padtickx']) else: gStyle.SetPadTickX(1) if 'padticky' in kwargs: gStyle.SetPadTickY(kwargs['padticky']) else: gStyle.SetPadTickY(1) gStyle.SetLegendBorderSize(0) if 'maxdigits' in kwargs: TGaxis.SetMaxDigits(kwargs['maxdigits']) if 'palette' in kwargs: gStyle.SetPalette(kwargs['palette']) gROOT.ForceStyle()
def invert_col(pad, fgcol=rt.kOrange - 3, bgcol=rt.kBlack): #set foreground and background color #fgcol = rt.kAzure #fgcol = rt.kGreen #fgcol = rt.kOrange-3 pad.SetFillColor(bgcol) pad.SetFrameLineColor(fgcol) next = TIter(pad.GetListOfPrimitives()) obj = next() while obj != None: #H1 if obj.InheritsFrom(TH1.Class()) == True: if obj.GetLineColor() == rt.kBlack: obj.SetLineColor(fgcol) obj.SetFillColor(bgcol) if obj.GetMarkerColor() == rt.kBlack: obj.SetMarkerColor(fgcol) obj.SetAxisColor(fgcol, "X") obj.SetAxisColor(fgcol, "Y") obj.SetLabelColor(fgcol, "X") obj.SetLabelColor(fgcol, "Y") obj.GetXaxis().SetTitleColor(fgcol) obj.GetYaxis().SetTitleColor(fgcol) #Legend if obj.InheritsFrom(TLegend.Class()) == True: obj.SetTextColor(fgcol) #obj.SetFillStyle(1000) #obj.SetFillColor(fgcol) #obj.SetTextColor(bgcol) #ln = TIter(obj.GetListOfPrimitives()) #lo = ln.Next() #while lo != None: #if lo.GetObject() == None: #lo = ln.Next() #continue #if lo.GetObject().InheritsFrom(TH1.Class()) == True: #hx = lo.GetObject() #hx.SetFillColor(bgcol) #if hx.GetMarkerColor() == rt.kBlack: #hx.SetMarkerColor(fgcol) #hx.SetLineColor(fgcol) #pass #lo = ln.Next() #RooHist if obj.InheritsFrom(RooHist.Class()) == True: if obj.GetMarkerColor() == rt.kBlack: obj.SetLineColor(fgcol) obj.SetMarkerColor(fgcol) #H2 if obj.InheritsFrom(TH2.Class()) == True: obj.SetAxisColor(fgcol, "Z") obj.SetLabelColor(fgcol, "Z") obj.GetZaxis().SetTitleColor(fgcol) #obj.SetLineColor(fgcol) #obj.SetMarkerColor(fgcol) #TLatex if obj.InheritsFrom(TLatex.Class()) == True: if obj.GetTextColor() == rt.kBlack: obj.SetTextColor(fgcol) #F2 if obj.InheritsFrom(TF2.Class()) == True: axes = [obj.GetXaxis(), obj.GetYaxis(), obj.GetZaxis()] for i in range(len(axes)): axes[i].SetAxisColor(fgcol) axes[i].SetLabelColor(fgcol) axes[i].SetTitleColor(fgcol) #F1 if obj.InheritsFrom(TF1.Class()) == True: axes = [obj.GetXaxis(), obj.GetYaxis()] for i in range(len(axes)): axes[i].SetAxisColor(fgcol) axes[i].SetLabelColor(fgcol) axes[i].SetTitleColor(fgcol) #TGraph if obj.InheritsFrom(TGraph.Class()) == True: obj.SetFillColor(bgcol) ax = obj.GetXaxis() ay = obj.GetYaxis() ax.SetAxisColor(fgcol) ay.SetAxisColor(fgcol) ax.SetLabelColor(fgcol) ay.SetLabelColor(fgcol) ax.SetTitleColor(fgcol) ay.SetTitleColor(fgcol) if obj.GetLineColor() == rt.kBlack: obj.SetLineColor(fgcol) obj.SetMarkerColor(fgcol) #TGaxis if obj.InheritsFrom(TGaxis.Class()) == True: obj.SetLineColor(fgcol) obj.SetLabelColor(fgcol) obj.SetTitleColor(fgcol) #TFrame if obj.InheritsFrom(TFrame.Class()) == True: if obj.GetLineColor() == rt.kBlack: obj.SetLineColor(fgcol) obj.SetFillColor(bgcol) #move to next item obj = next()
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))
def __init__(self): super(StyleClass, self).__init__('CmsRootStyle', 'CmsRootStyle') ################################ custom root style commands ### self.SetFrameBorderMode(0) self.SetCanvasBorderMode(0) self.SetPadBorderMode(0) self.SetPadBorderMode(0) #self.SetFrameColor(0) self.SetPadColor(0) self.SetCanvasColor(0) self.SetStatColor(0) self.SetFillColor(0) self.SetNdivisions(505, 'XY') self.SetTextFont(42) #132 self.SetTextSize(0.09) self.SetLabelFont(42, 'xyz') self.SetTitleFont(42, 'xyz') self.SetLabelSize(0.045, 'xyz') #0.035 self.SetTitleSize(0.045, 'xyz') self.SetTitleOffset(1.3, 'xy') self.SetTitleX(0.16) self.SetTitleY(0.93) self.SetTitleColor(1) self.SetTitleTextColor(1) self.SetTitleFillColor(0) self.SetTitleBorderSize(1) self.SetTitleFontSize(0.04) self.SetPadTopMargin(0.05) self.SetPadBottomMargin(0.13) #self.SetPadLeftMargin(0.14) #self.SetPadRightMargin(0.02) self.SetPaperSize(20, 26) self.SetPadRightMargin(0.3) self.SetPadLeftMargin(0.16) #self.SetCanvasDefH(800) #self.SetCanvasDefW(800) #self.SetPadGridX(1) #self.SetPadGridY(1) self.SetPadTickX(1) self.SetPadTickY(1) # use bold lines and markers self.SetMarkerStyle(8) self.SetMarkerSize(1.2) self.SetHistLineWidth(1) self.SetLineWidth(1) self.SetEndErrorSize(0) self.SetOptTitle(1) self.SetOptStat(0) # don't know what these are for. Need to ask the kuess'l-o-mat. self.colors = [1, 2, 3, 4, 6, 7, 8, 9, 11] self.markers = [20, 21, 22, 23, 24, 25, 26, 27, 28] self.styles = [1, 2, 3, 4, 5, 6, 7, 8, 9] ############################ end custom root style commands ### self.cd() self.set_palette() gROOT.SetStyle('CmsRootStyle') gROOT.ForceStyle() TGaxis.SetMaxDigits(3)
def main(): filename = read_file_name("OUTPUT_TWITTER_TXT_generator/LA_OUTPUT_week1n2n3n4.txt") ##FIXME TGaxis.SetMaxDigits(3) can = TCanvas("can","can") can.SetGrid() mg = TMultiGraph() nn = 7 GR = [] NAME = [] px,py = array('d'), array('d') f = open(filename[2],'r') indicator = 0 for line in f: if(indicator == 0): indicator = indicator + 1 continue Name, Total, Pos, Neg, TNum = line.split() name = Find_Loca(Name) name = Name.replace(Name[name:],"") # print(name) px.append((indicator-1)%7); py.append(float(TNum)) if((indicator)%7 == 0): NAME.append(name) gr = TGraph( nn, px, py ) GR.append(gr) px,py = array('d'), array('d') indicator = indicator + 1 # print(GR); print(len(GR)) for i in range(len(GR)): GR[i].SetLineWidth(2) if "water" in NAME[i]: GR[i].SetLineWidth(5); GR[i].SetLineColor(1) ;GR[i].SetMarkerColor(1) if "wine" in NAME[i]: GR[i].SetMarkerColor(2);GR[i].SetLineColor(2) if "beer" in NAME[i]: GR[i].SetMarkerColor(5);GR[i].SetLineColor(5) if "tea" in NAME[i]: GR[i].SetMarkerColor(4);GR[i].SetLineColor(4) if "coffee" in NAME[i]: GR[i].SetMarkerColor(3);GR[i].SetLineColor(3) if "juice" in NAME[i]: GR[i].SetMarkerColor(7);GR[i].SetLineColor(7) if "COLA" in NAME[i]: GR[i].SetMarkerColor(6);GR[i].SetLineColor(6) GR[i].GetXaxis().SetTitle("days") GR[i].SetMarkerStyle(20) # GR[i].Fit("pol4","q") mg.Add(GR[i]) mg.Draw("ALP") leg = TLegend(0.65, 0.65, 0.9, 0.8) leg.SetBorderSize(0) leg.SetFillColor(10) for i in range(len(GR)): leg_entry = leg.AddEntry(GR[i], NAME[i],"l") # leg.Draw() mg.SetTitle("Total tweets counts at LA(week 1&2&3&4)") ##FIXME mg.GetHistogram().GetXaxis().SetTitle("days") mg.GetHistogram().GetXaxis().SetTitleOffset(1) mg.GetHistogram().GetXaxis().SetLabelSize(0.03) mg.GetHistogram().GetYaxis().SetTitle("Counts") mg.GetHistogram().GetYaxis().SetTitleOffset(1.3) mg.GetHistogram().GetYaxis().SetLabelSize(0.03) mg.GetHistogram().GetXaxis().SetBinLabel(5,"Mon") mg.GetHistogram().GetXaxis().SetBinLabel(20,"Tue") mg.GetHistogram().GetXaxis().SetBinLabel(35,"Wed") mg.GetHistogram().GetXaxis().SetBinLabel(51,"Thu") mg.GetHistogram().GetXaxis().SetBinLabel(66,"Fri") mg.GetHistogram().GetXaxis().SetBinLabel(81,"Sat") mg.GetHistogram().GetXaxis().SetBinLabel(96,"Sun") # mg.GetHistogram().GetXaxis().SetBinLabel(84,"Mon") # mg.GetHistogram().GetXaxis().SetBinLabel(96,"Tue") # for i in range(len(GR)): # mg.GetHistogram().GetXaxis().SetBinLabel(i,DAYS) # mg.GetHistogram().GetXaxis().SetLabel("tt") can.Modified() can.Update() # can.GetFrame().SetBorderSize( 12 ) can.Print("Total_tweet_LA_week1n2n3n4.pdf") ##FIXME
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
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 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_significance(num_injected_events, plot=True, name=""): ROOT.IABstyles.global_style() TGaxis.SetMaxDigits(3) hist_model_scaled = [ num_injected_events * bin_content for bin_content in hist_model_contents ] hist_random_bg = [] hist_random = [] for bg_content, model_content, center in zip(hist_contents, hist_model_scaled, hist_center): if bg_content > 0 or center / 1000 > 2: x = center / 1000 bg = poisson.ppf(random.random(), bg_content) peak = 0 if model_content > 0: peak = poisson.ppf(random.random(), model_content) hist_random.append(bg + peak) else: hist_random.append(0) fits = Fits() fits.model_scale_values = list(hist_model_contents) nbins = hist_bins fits.xwidth = [(a - b) / 1000 / 2 for a, b in zip(hist_left[1:], hist_left)] fits.xmiddle = [x / 1000 for x in hist_center] fits.xmins = [x / 1000 for x in hist_left] fits.xmaxes = [x / 1000 for x in hist_right] fits.data = hist_random fits.data_fits = [ 0, ] * nbins fits.errors = [math.sqrt(x) for x in fits.data] fits.num_bins = nbins """root_file = TFile.Open("data/mjj_mc15_13TeV_361023_Pythia8EvtGen_A14NNPDF23LO_jetjet_JZ3W_total_final.root") hist = root_file.Get("mjj_mc15_13TeV_361023_Pythia8EvtGen_A14NNPDF23LO_jetjet_JZ3W_total_final") root_file_qstar = TFile.Open("data/dataLikeHistograms.QStar{0}.root".format(MASS_FILE)) nominal = root_file_qstar.GetDirectory("Nominal") hist_model = nominal.Get("mjj_Scaled_QStar{0}_30fb".format(MASS_FILE)) hist_model.Smooth(1) hist_model.Scale(1/hist_model.Integral()) model_scale_values = [hist_model.GetBinContent(b) for b in range(1, hist_model.GetNbinsX()+1)] hist_model.Scale(num_injected_events) hist_original_bin_contents = [hist.GetBinContent(b) for b in range(0, hist.GetNbinsX()+1)] for b in range(0, hist.GetNbinsX()+1): hist.SetBinContent(b, 0) for b in range(1, hist.GetNbinsX()+1): if hist_original_bin_contents[b] > 0 or hist.GetBinLowEdge(b)/1000 > 2: x = hist.GetBinCenter(b)/1000 bg = poisson.ppf(random.random(), hist_original_bin_contents[b]) peak = 0 if hist_model.GetBinContent(b) > 0: peak = poisson.ppf(random.random(), hist_model.GetBinContent(b)) hist.SetBinContent(b, bg+peak) fits = Fits() fits.model_scale_values = model_scale_values nbins = hist.GetNbinsX() fits.xwidth = [(hist.GetBinLowEdge(b+1)/1000-hist.GetBinLowEdge(b)/1000)/2 for b in range(1, nbins+1)] fits.xmiddle = [hist.GetBinCenter(b)/1000 for b in range(1, nbins+1)] fits.xmins = [hist.GetBinLowEdge(b)/1000 for b in range(1, nbins+1)] fits.xmaxes = [hist.GetBinLowEdge(b+1)/1000 for b in range(1, nbins+1)] fits.data = [hist.GetBinContent(b) for b in range(1, nbins+1)] fits.data_fits = [0,]*nbins root_file.Close() root_file_qstar.Close() fits.errors = [math.sqrt(x) for x in fits.data] fits.num_bins = nbins""" remove_bins = 0 for x in fits.data: if x == 0: remove_bins += 1 else: break nbins -= remove_bins fits.xwidth = fits.xwidth[remove_bins:] fits.xmiddle = fits.xmiddle[remove_bins:] fits.xmins = fits.xmins[remove_bins:] fits.xmaxes = fits.xmaxes[remove_bins:] fits.data = fits.data[remove_bins:] fits.data_fits = fits.data_fits[remove_bins:] fits.errors = fits.errors[remove_bins:] fits.num_bins = nbins fits.model_scale_values = fits.model_scale_values[remove_bins:] x, y = fits.run_mass_fit(num_injected_events) if x is None and y is None: return None plot_only = False if fits.iflag != 4: plot_only = True print("Fit did not converge") return None if not plot_only: y = [math.exp(-a) for a in y] ycumulative = [sum(y[0:i]) for i in range(0, len(y))] if max(ycumulative) == 0: print("Iteration {0} max(ycumulative)=0".format(name)) plot_data_histogram(fits, name) return None ycumulative = [yval / max(ycumulative) for yval in ycumulative] limit_x = 0 limit_y = 0 for xv, yv in zip(x, ycumulative): if yv >= 0.95: limit_x = xv limit_y = yv break if limit_x < 4500: return limit_x else: limit_x = None return limit_x canvas = TCanvas("dist", "dist", 0, 0, 650, 450) graph = TGraph(len(x), array("d", x), array("d", y)) ROOT.IABstyles.h1_style(graph, ROOT.IABstyles.lWidth // 2, ROOT.IABstyles.Scolor, 1, 0, 0, -1111.0, -1111.0, 508, 508, 8, ROOT.IABstyles.Scolor, 0.1, 0) graph.SetMarkerColor(2) graph.SetMarkerStyle(3) graph.SetMarkerSize(1.25) graph.Draw("ap") label = ROOT.TText() label.SetNDC() label.SetTextSize(0.03) label.DrawText(0.5, 0.7, "{0}GeV q*".format(MASS_FILE)) canvas.SaveAs("plots/{0}/{2}/plot-{1}-{2}-sig_dist.png".format( CLUSTER_ID, name, MASS_FILE)) canvas2 = TCanvas("cumsum", "cumsum", 0, 0, 650, 450) graph = TGraph(len(x), array("d", x), array("d", ycumulative)) ROOT.IABstyles.h1_style(graph, ROOT.IABstyles.lWidth // 2, ROOT.IABstyles.Scolor, 1, 0, 0, -1111.0, -1111.0, 508, 508, 8, ROOT.IABstyles.Scolor, 0.1, 0) graph.SetMarkerColor(4) graph.SetMarkerStyle(3) graph.SetMarkerSize(1.25) graph.Draw("ap") line = ROOT.TLine(limit_x, 0, limit_x, limit_y) line.SetLineColor(2) line.Draw("same") label = ROOT.TText() label.SetNDC() label.SetTextSize(0.03) label.DrawText( 0.5, 0.7, "{0}GeV q* {1:.02f} confidence limit = {2} events".format( MASS_FILE, limit_y, limit_x)) canvas2.SaveAs("plots/{0}/{2}/plot-{1}-{2}-sig_cumsum.png".format( CLUSTER_ID, name, MASS_FILE)) plot_data_histogram(fits, name) return limit_x
def DrawStack(self, xtit='', ytit=''): ''' Draws a stack plot ''' # Set the canvas and pads if xtit != '': self.axisXtit = xtit if ytit != '': self.axisYtit = ytit self.SetCanvas() # Stack processes and draw stack and data self.plot.cd() gPad.SetTickx() gPad.SetTicky() if not os.path.isdir(self.GetOutPath()): os.makedirs(self.GetOutPath()) self.hStack.Draw('hist') if hasattr(self, 'MCstatUnc'): self.MCstatUnc.Draw("e2,same") if hasattr(self, 'MCunc'): self.MCunc.Draw("e2,same") # Extra histograms for h in self.overlapHistos: h.Draw("hist,same") # Errors in data if hasattr(self, 'hData'): self.hData.SetBinErrorOption(TH1.kPoisson) self.hData.Sumw2(False) self.hData.Draw('psameE0X0') #self.data.GetDrawStyle()) # Set Maximum datamax = self.hData.GetMaximum() if hasattr(self, 'hData') else -999 bkgmax = self.TotMC.GetMaximum() if hasattr( self, 'TotMC') else self.hStack.GetStack().Last().GetMaximum() dmax = max(datamax, bkgmax) if isinstance(self.PlotMaximum, float): self.hStack.SetMaximum(self.PlotMaximum) else: self.hStack.SetMaximum(dmax * self.PlotMaxScale) if isinstance(self.PlotMinimum, float): self.hStack.SetMinimum(self.PlotMinimum) # Set titles... TGaxis.SetMaxDigits(3) self.SetAxisPlot(self.hStack) if self.doRatio: self.SetAxisRatio(self.hRatio) self.SetAxisRatio(self.hRatioUnc) self.SetAxisRatio(self.hRatioStatUnc) # Legend if hasattr(self, 'processes'): self.hleg = [] leg = self.SetLegend() for pr in self.processes: h = self.TotMC.Clone('leg%s' % pr) h.SetFillStyle(1000) h.SetLineColor(0) h.SetLineWidth(0) h.SetFillColor(self.colors[pr]) self.hleg.append(h) leg.AddEntry(self.hleg[-1], pr, 'f') for h in self.overlapHistos: leg.AddEntry(h, h.GetName(), 'l') if hasattr(self, 'hData'): leg.AddEntry(self.hData, 'data', 'pe') leg.Draw() # Ratio if self.doRatio: self.ratio.cd() legr = self.SetLegendRatio() if hasattr(self, 'hRatioStatUnc'): self.hRatioStatUnc.Draw('e2same') self.hRatioStatUnc.SetLineWidth(0) self.hRatioStatUnc.SetMaximum(self.PlotRatioMax) self.hRatioStatUnc.SetMinimum(self.PlotRatioMin) legr.AddEntry(self.hRatioStatUnc, 'Stat', 'f') if hasattr(self, 'hRatioUnc'): self.hRatioUnc.Draw('e2same') self.hRatioUnc.SetLineWidth(0) self.hRatioUnc.SetMinimum(self.PlotRatioMin) self.hRatioUnc.SetMaximum(self.PlotRatioMax) legr.AddEntry(self.hRatioUnc, 'Stat #oplus Syst', 'f') if hasattr(self, 'hRatio'): self.hRatio.Draw('pE0X0,same') self.hRatio.SetMaximum(self.PlotRatioMax) self.hRatio.SetMinimum(self.PlotRatioMin) for h in self.extraRatio: h.Draw("hist, same") legr.Draw() else: for r in self.Tex: r.Draw() if len(self.binLabels) > 0: for i in range(len(self.binLabels)): if self.doRatio: if hasattr(self, 'hRatio'): self.hRatio.GetXaxis().SetBinLabel( i + 1, self.binLabels[i]) if hasattr(self, 'hRatioUnc'): self.hRatioUnc.GetXaxis().SetBinLabel( i + 1, self.binLabels[i]) if hasattr(self, 'hRatioStatUnc'): self.hRatioStatUnc.GetXaxis().SetBinLabel( i + 1, self.binLabels[i]) else: self.hStack.GetXaxis().SetBinLabel(i + 1, self.binLabels[i]) self.Save()