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 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 __init__(self): super(StyleClass, self).__init__("CRRootStyle", "CRRootStyle") self.root_style_settings() self.cd() gROOT.SetStyle("CRRootStyle") gROOT.ForceStyle() TGaxis.SetMaxDigits(3)
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 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 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 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 __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 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 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()
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 = [] seed = random.randrange(sys.maxsize) print("Random seed: ", seed) random.seed(seed) 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 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:] #for i in range(0, nbins): # print(i, fits.data[i], fits.model_scale_values[i]) sys.stdout.flush() x, y = fits.run_mass_fit(num_injected_events) """for i in range(0, 5): k = ROOT.Double(0) fits.gMinuit.GetParameter(i, k, ROOT.Double(0)) print("Parameter {0}: {1}".format(i, k))""" if x is None or 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)) 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 return limit_x
def plotRateProfiles(data,label=False,runNumber=None,fillNumber=None,log=True,minY=None,maxY=None,luminousBunches=None,drawOption='H'): TGaxis.SetMaxDigits(3) data['canvases']={} for groupNum,group in enumerate(data['groups']): if minY is None: minY = 0. if log: minY = max([10**-9,minY]) if maxY is None: maxY = 10.**10 currentMin = maxY currentMax = minY aliases = [] for rateName,alias,level in group: aliases.append(alias) temp = [data['profiles'][alias].GetBinContent(i) for i in range(data['profiles'][alias].GetNbinsX()+1) if minY<data['profiles'][alias].GetBinContent(i)<maxY] if not len(temp): continue thisMin = min(temp) thisMax = max(temp) currentMin = min(currentMin,thisMin) currentMax = max(currentMax,thisMax) canvas = getNiceCanvas('canvas{0}'.format(('000'+str(groupNum))[-3:]),aliases) if currentMin>=currentMax: logger.warning('No data in group, {0} is empty'.format(canvas.GetName())) data['canvases'].update({canvas.GetName():canvas}) continue scale = 1.1 if log: scale = 1.5 thisMinY = currentMin/scale thisMaxY = currentMax*scale subPad1 = canvas.GetPad(1) if log: subPad1.SetLogy() canvas,legend = configureCanvasLegend(canvas,aliases) legendOption = 'L' if 'P' in drawOption: legendOption = 'p' canvas.cd(1) for i,(rateName,alias,level) in enumerate(group): profile = data['profiles'][alias] profile = configureProfile(profile,i,thisMinY,thisMaxY,drawOption,data,log) if drawOption: if not i: profile.Draw(drawOption) else: profile.Draw('{0} SAME'.format(drawOption)) else: if not i: profile.Draw() else: profile.Draw('SAME') if log: yAxis = profile.GetYaxis() if int(log10(minY)) == int(log10(maxY)): yAxis.SetMoreLogLabels(True) else: yAxis.SetMoreLogLabels(False) yAxis.Draw() legend.AddEntry(profile,alias,legendOption) canvas.cd(2) legend.Draw() canvas.cd(1) if label: scale = 1.0*10**9 timeStart = min(data['time'].values())/scale timeEnd = max(data['time'].values())/scale timeLabel = fetchTimeLabel(timeStart,timeEnd) #startLumi,endLumi = getLumiEndPoints(data) canvas = generateAtlasLabel(canvas,timeLabel,luminousBunches,runNumber=runNumber,fillNumber=fillNumber) data['canvases'].update({canvas.GetName():canvas}) return data
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 __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)
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() cSyst = TCanvas('cSyst', '', 800, 800) cSyst.DrawFrame(hSyst.GetBinLowEdge(1), 0.1, ptMax, 20., ';#it{p}_{T} (GeV/#it{c}); Syst (%)') SetObjectStyle(hRMS, color=kRed + 1, fillstyle=0, linewidth=3) SetObjectStyle(hMeanShift, color=kBlack, fillstyle=0, linewidth=3) SetObjectStyle(hSyst, color=kBlue + 1, fillstyle=0, linewidth=3) hMeanShift.DrawCopy('same') hSyst.DrawCopy('same') hRMS.DrawCopy('same') leg = TLegend(0.5, 0.8, 0.8, 0.95) leg.SetTextSize(0.04)
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
def setTDRStyle(): tdrStyle = TStyle("tdrStyle","Style for P-TDR") #for the canvas: tdrStyle.SetCanvasBorderMode(0) tdrStyle.SetCanvasColor(kWhite) tdrStyle.SetCanvasDefH(600) #Height of canvas tdrStyle.SetCanvasDefW(600) #Width of canvas tdrStyle.SetCanvasDefX(0) #POsition on screen tdrStyle.SetCanvasDefY(0) tdrStyle.SetPadBorderMode(0) #tdrStyle.SetPadBorderSize(Width_t size = 1) tdrStyle.SetPadColor(kWhite) tdrStyle.SetPadGridX(False) tdrStyle.SetPadGridY(False) tdrStyle.SetGridColor(0) tdrStyle.SetGridStyle(3) tdrStyle.SetGridWidth(1) #For the frame: tdrStyle.SetFrameBorderMode(0) tdrStyle.SetFrameBorderSize(1) tdrStyle.SetFrameFillColor(0) tdrStyle.SetFrameFillStyle(0) tdrStyle.SetFrameLineColor(1) tdrStyle.SetFrameLineStyle(1) tdrStyle.SetFrameLineWidth(1) #For the histo: #tdrStyle.SetHistFillColor(1) #tdrStyle.SetHistFillStyle(0) tdrStyle.SetHistLineColor(1) tdrStyle.SetHistLineStyle(0) tdrStyle.SetHistLineWidth(1) #tdrStyle.SetLegoInnerR(Float_t rad = 0.5) #tdrStyle.SetNumberContours(Int_t number = 20) tdrStyle.SetEndErrorSize(2) #tdrStyle.SetErrorMarker(20) #tdrStyle.SetErrorX(0.) tdrStyle.SetMarkerStyle(20) #For the fit/function: tdrStyle.SetOptFit(1) tdrStyle.SetFitFormat("5.4g") tdrStyle.SetFuncColor(2) tdrStyle.SetFuncStyle(1) tdrStyle.SetFuncWidth(1) #For the date: tdrStyle.SetOptDate(0) # tdrStyle.SetDateX(Float_t x = 0.01) # tdrStyle.SetDateY(Float_t y = 0.01) # For the statistics box: tdrStyle.SetOptFile(0) tdrStyle.SetOptStat(0) # To display the mean and RMS: SetOptStat("mr") tdrStyle.SetStatColor(kWhite) tdrStyle.SetStatFont(42) tdrStyle.SetStatFontSize(0.025) tdrStyle.SetStatTextColor(1) tdrStyle.SetStatFormat("6.4g") tdrStyle.SetStatBorderSize(1) tdrStyle.SetStatH(0.1) tdrStyle.SetStatW(0.15) # tdrStyle.SetStatStyle(Style_t style = 1001) # tdrStyle.SetStatX(Float_t x = 0) # tdrStyle.SetStatY(Float_t y = 0) # Margins: tdrStyle.SetPadTopMargin(0.05) tdrStyle.SetPadBottomMargin(0.13) tdrStyle.SetPadLeftMargin(0.16) tdrStyle.SetPadRightMargin(0.02) # For the Global title: tdrStyle.SetOptTitle(0) tdrStyle.SetTitleFont(42) tdrStyle.SetTitleColor(1) tdrStyle.SetTitleTextColor(1) tdrStyle.SetTitleFillColor(10) tdrStyle.SetTitleFontSize(0.05) # tdrStyle.SetTitleH(0) # Set the height of the title box # tdrStyle.SetTitleW(0) # Set the width of the title box # tdrStyle.SetTitleX(0) # Set the position of the title box # tdrStyle.SetTitleY(0.985) # Set the position of the title box # tdrStyle.SetTitleStyle(Style_t style = 1001) # tdrStyle.SetTitleBorderSize(2) # For the axis titles: tdrStyle.SetTitleColor(1, "XYZ") tdrStyle.SetTitleFont(42, "XYZ") tdrStyle.SetTitleSize(0.06, "XYZ") # tdrStyle.SetTitleXSize(Float_t size = 0.02) # Another way to set the size? # tdrStyle.SetTitleYSize(Float_t size = 0.02) tdrStyle.SetTitleXOffset(0.9) tdrStyle.SetTitleYOffset(1.25) # tdrStyle.SetTitleOffset(1.1, "Y") # Another way to set the Offset # For the axis labels: tdrStyle.SetLabelColor(1, "XYZ") tdrStyle.SetLabelFont(42, "XYZ") tdrStyle.SetLabelOffset(0.007, "XYZ") tdrStyle.SetLabelSize(0.05, "XYZ") # For the axis: tdrStyle.SetAxisColor(1, "XYZ") tdrStyle.SetStripDecimals(True) tdrStyle.SetTickLength(0.03, "XYZ") tdrStyle.SetNdivisions(510, "XYZ") tdrStyle.SetPadTickX(1) # To get tick marks on the opposite side of the frame tdrStyle.SetPadTickY(1) # Change for log plots: tdrStyle.SetOptLogx(0) tdrStyle.SetOptLogy(0) tdrStyle.SetOptLogz(0) # Postscript options: tdrStyle.SetPaperSize(20.,20.) # tdrStyle.SetLineScalePS(Float_t scale = 3) # tdrStyle.SetLineStyleString(Int_t i, const char* text) # tdrStyle.SetHeaderPS(const char* header) # tdrStyle.SetTitlePS(const char* pstitle) # tdrStyle.SetBarOffset(Float_t baroff = 0.5) # tdrStyle.SetBarWidth(Float_t barwidth = 0.5) # tdrStyle.SetPaintTextFormat(const char* format = "g") # tdrStyle.SetPalette(Int_t ncolors = 0, Int_t* colors = 0) # tdrStyle.SetTimeOffset(Double_t toffset) # tdrStyle.SetHistMinimumZero(kTRUE) tdrStyle.SetHatchesLineWidth(5) tdrStyle.SetHatchesSpacing(0.05) tdrStyle.SetLegendBorderSize(0) TGaxis.SetMaxDigits(3) tdrStyle.cd()
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 SAME3VsLumi(g1, g2, g3, title, ptype, lineMC1, lineDATA1, lineMC2, lineDATA2, lineMC3, lineDATA3, DoInclusive, dataPeriod): canvas = makeCMSCanvas(str(random.random()),"canvas",900,700) canvas.cd() graph2=copy.deepcopy(g2) graph3=copy.deepcopy(g3) graph2.SetMarkerColor(kBlue)#electrons graph3.SetMarkerColor(kRed)#muons multigraph = TMultiGraph() if(DoInclusive): graph1=copy.deepcopy(g1) multigraph.Add(graph1,"AP") multigraph.Add(graph2,"AP") multigraph.Add(graph3,"AP") multigraph.Draw("AP") TGaxis.SetMaxDigits(2) TGaxis.SetExponentOffset(-0.05, 0.02, "y") multigraph.GetXaxis().SetTitle("L [fb^{-1}]") multigraph.GetYaxis().SetTitleOffset(1.4) if(ptype == "Zmass"): multigraph.GetYaxis().SetTitle("M_{Z} [GeV]") # multigraph.GetYaxis().SetTitle("M_{l^{+}l^{-}} [GeV]") multigraph.SetMaximum(max(multigraph.GetHistogram().GetMaximum(),91.4)) multigraph.SetMinimum(min(multigraph.GetHistogram().GetMinimum(),89.6)) elif(ptype == "Zwidth"): multigraph.GetYaxis().SetTitle("#Gamma_{Z} [GeV]") elif(ptype == "Zmult"): multigraph.GetYaxis().SetTitle("#Z / fb^{-1}") if(not DoInclusive) : multigraph.SetMaximum(max(multigraph.GetHistogram().GetMaximum(),60000.)) # set y axis minimum at 60000. multigraph.SetMinimum(0.) # set y axis minimum at 0. # multigraph.SetMaximum(60000.) #second type: vs 2016 plots # multigraph.SetMinimum(25000.) printLumiPrelOut(canvas) # Draw legend legend = TLegend(0.93,0.84,0.99,0.93) if(DoInclusive): #legend.AddEntry(graph1,"inclusive","P") legend.AddEntry(graph1,"BB","P") legend.AddEntry(graph2,"BE","P") legend.AddEntry(graph3,"EE","P") else : legend.AddEntry(graph2,"e^{+}e^{-}","P") legend.AddEntry(graph3,"#mu^{+}#mu^{-}","P") legend.SetFillColor(kWhite) legend.SetLineColor(kBlack) legend.SetTextFont(43) legend.SetTextSize(20) legend.Draw() canvas.Update() # Draw letters for data-taking periods if(dataPeriod == "data2017"): textLetters = TLatex() textLetters.SetTextColor(kGray+1) textLetters.SetTextSize(0.03) if(ptype == "Zmass"): textLetters.DrawLatex(2., gPad.GetUymin()+0.2,"B") textLetters.DrawLatex(9.5, gPad.GetUymin()+0.2,"C") textLetters.DrawLatex(16., gPad.GetUymin()+0.2,"D") textLetters.DrawLatex(23., gPad.GetUymin()+0.2,"E") textLetters.DrawLatex(36., gPad.GetUymin()+0.2,"F") elif(ptype == "Zwidth"): textLetters.DrawLatex(2., gPad.GetUymin()+0.3,"B") textLetters.DrawLatex(9.5, gPad.GetUymin()+0.3,"C") textLetters.DrawLatex(16., gPad.GetUymin()+0.3,"D") textLetters.DrawLatex(23., gPad.GetUymin()+0.3,"E") textLetters.DrawLatex(36., gPad.GetUymin()+0.3,"F") elif(ptype == "Zmult") : textLetters.DrawLatex(2., 260000,"B") textLetters.DrawLatex(9.5, 260000,"C") textLetters.DrawLatex(16., 260000,"D") textLetters.DrawLatex(23., 260000,"E") textLetters.DrawLatex(36., 260000,"F") if(dataPeriod == "data2018"): textLetters = TLatex() textLetters.SetTextColor(kGray+1) textLetters.SetTextSize(0.03) if(ptype == "Zmass"): textLetters.DrawLatex(6., gPad.GetUymin() + 0.6,"A") textLetters.DrawLatex(16., gPad.GetUymin() + 0.6,"B") textLetters.DrawLatex(23., gPad.GetUymin() + 0.6,"C") textLetters.DrawLatex(43., gPad.GetUymin() + 0.6,"D") elif(ptype == "Zwidth"): textLetters.DrawLatex(6., gPad.GetUymin() +0.3,"A") textLetters.DrawLatex(16., gPad.GetUymin() +0.3,"B") textLetters.DrawLatex(23., gPad.GetUymin() +0.3,"C") textLetters.DrawLatex(43., gPad.GetUymin() +0.3,"D") elif(ptype == "Zmult") : textLetters.DrawLatex(6., 260000,"A") textLetters.DrawLatex(16., 260000,"B") textLetters.DrawLatex(23., 260000,"C") textLetters.DrawLatex(43., 260000,"D") # **** if(dataPeriod == "data2018"): # draw vertical lines that divide different data taking periods down = gPad.GetUymin() up = gPad.GetUymax() lineA = TLine(13.48, down, 13.48, up) # Run2018A up to 13.48 fb-1 lineA.SetLineColor(kBlack) lineA.SetLineStyle(2) lineA.Draw() lineB = TLine(20.265, down, 20.265, up) # Run2018B up to 20.265 fb-1 lineB.SetLineColor(kBlack) lineB.SetLineStyle(2) lineB.Draw() lineC = TLine(26.877, down, 26.877, up) # Run2018C up to 26.877 fb-1 lineC.SetLineColor(kBlack) lineC.SetLineStyle(2) lineC.Draw() if(dataPeriod == "data2017"): # draw vertical lines that divide different data taking periods down = gPad.GetUymin() up = gPad.GetUymax() lineB = TLine(4.793, down, 4.793, up) # Run2017B up to 4.793 fb-1 lineB.SetLineColor(kBlack) lineB.SetLineStyle(2) lineB.Draw() lineC = TLine(14.549, down, 14.549, up) # Run2017C up to 14.549 fb-1 lineC.SetLineColor(kBlack) lineC.SetLineStyle(2) lineC.Draw() lineD = TLine(18.868, down, 18.868, up) # Run2017D up to 18.868 fb-1 lineD.SetLineColor(kBlack) lineD.SetLineStyle(2) lineD.Draw() lineE = TLine(28.293, down, 28.293, up) # Run2017E up to 28.293 fb-1 lineE.SetLineColor(kBlack) lineE.SetLineStyle(2) lineE.Draw() if(dataPeriod == "data2016"): # draw vertical lines that divide different data taking periods down = gPad.GetUymin() up = gPad.GetUymax() lineB = TLine(5.789, down, 5.789, up) # Run2016B up to 5.789 fb-1 lineB.SetLineColor(kBlack) lineB.SetLineStyle(2) lineB.Draw() lineC = TLine(8.366, down, 8.366, up) # Run2016C up to 8.366 fb-1 lineC.SetLineColor(kBlack) lineC.SetLineStyle(2) lineC.Draw() lineD = TLine(12.616, down, 12.616, up) # Run2016D up to 12.616 fb-1 lineD.SetLineColor(kBlack) lineD.SetLineStyle(2) lineD.Draw() lineE = TLine(16.624, down, 16.624, up) # Run2016E up to 16.624 fb-1 lineE.SetLineColor(kBlack) lineE.SetLineStyle(2) lineE.Draw() lineF = TLine(19.725, down, 19.725, up) # Run2016F up to 19.725 fb-1 lineF.SetLineColor(kBlack) lineF.SetLineStyle(2) lineF.Draw() lineG = TLine(27.268, down, 27.268, up) # Run2016G up to 27.268 fb-1 lineG.SetLineColor(kBlack) lineG.SetLineStyle(2) lineG.Draw() # **** # draw orizontal lines for MC and DATA fit if(ptype == "Zmass" or ptype == "Zwidth") : leftEnd = gPad.GetUxmin() rightEnd = gPad.GetUxmax() if(DoInclusive): line1 = TLine(leftEnd,lineMC1,rightEnd,lineMC1) line1.SetLineColor(kBlack) line1.SetLineStyle(1) line1.Draw() line2 = TLine(leftEnd,lineDATA1,rightEnd,lineDATA1) line2.SetLineColor(kBlack) line2.SetLineStyle(2) line2.Draw() # line for graph 2: color blue line3 = TLine(leftEnd,lineMC2,rightEnd,lineMC2) line3.SetLineColor(kBlue) line3.SetLineStyle(1) line3.Draw() line4 = TLine(leftEnd,lineDATA2,rightEnd,lineDATA2) line4.SetLineColor(kBlue) line4.SetLineStyle(2) line4.Draw() # line for graph 3: color red line5 = TLine(leftEnd,lineMC3,rightEnd,lineMC3) line5.SetLineColor(kRed) line5.SetLineStyle(1) line5.Draw() line6 = TLine(leftEnd,lineDATA3,rightEnd,lineDATA3) line6.SetLineColor(kRed) line6.SetLineStyle(2) line6.Draw() # *** canvas.SaveAs(title + ".root") canvas.SaveAs(title + ".pdf") canvas.SaveAs(title + ".png") return;
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 SAME2VsLumi(g1, g2,title, ptype, dataPeriod): canvas = makeCMSCanvas(str(random.random()),"canvas",900,700) canvas.cd() graph1=copy.deepcopy(g1) graph2=copy.deepcopy(g2) graph1.SetMarkerColor(kBlue)#electrons graph2.SetMarkerColor(kRed)#muons multigraph = TMultiGraph() multigraph.Add(graph1,"AP") multigraph.Add(graph2,"AP") multigraph.Draw("AP") TGaxis.SetMaxDigits(2) TGaxis.SetExponentOffset(-0.06, 0.02, "y") multigraph.GetXaxis().SetTitle("L [fb^{-1}]") multigraph.GetYaxis().SetTitleOffset(1.4) if(ptype == "ISO"): multigraph.GetYaxis().SetTitle("Isolation") gPad.Modified() multigraph.SetMinimum(0.5*gPad.GetUymin()) multigraph.SetMaximum(1.5*gPad.GetUymax()) elif(ptype == "SIP"): multigraph.GetYaxis().SetTitle("SIP") multigraph.SetMinimum(min(multigraph.GetHistogram().GetMinimum(),1.)) multigraph.SetMaximum(max(multigraph.GetHistogram().GetMinimum(),2.2)) min(multigraph.GetHistogram().GetMinimum(),1.) printLumiPrelOut(canvas) # Draw legend legend = TLegend(0.93,0.84,0.99,0.93) legend.AddEntry(graph1,"e^{+}e^{-}","P") legend.AddEntry(graph2,"#mu^{+}#mu^{-}","P") legend.SetFillColor(kWhite) legend.SetLineColor(kBlack) legend.SetTextFont(43) legend.SetTextSize(20) legend.Draw() canvas.Update() # Draw letters for data-taking periods if(dataPeriod == "data2017"): textLetters = TLatex() textLetters.SetTextColor(kGray+1) textLetters.SetTextSize(0.03) if(ptype == "ISO"): textLetters.DrawLatex(2., 0.8*gPad.GetUymax(),"B") textLetters.DrawLatex(9.5, 0.8*gPad.GetUymax(),"C") textLetters.DrawLatex(16., 0.8*gPad.GetUymax(),"D") textLetters.DrawLatex(23., 0.8*gPad.GetUymax(),"E") textLetters.DrawLatex(36., 0.8*gPad.GetUymax(),"F") elif(ptype == "SIP"): textLetters.DrawLatex(2., 1.5,"B") textLetters.DrawLatex(9.5, 1.5,"C") textLetters.DrawLatex(16., 1.5,"D") textLetters.DrawLatex(23., 1.5,"E") textLetters.DrawLatex(36., 1.5,"F") if(dataPeriod == "data2018"): textLetters = TLatex() textLetters.SetTextColor(kGray+1) textLetters.SetTextSize(0.03) if(ptype == "ISO"): textLetters.DrawLatex(6., 0.8*gPad.GetUymax(), "A") textLetters.DrawLatex(16., 0.8*gPad.GetUymax(), "B") textLetters.DrawLatex(23., 0.8*gPad.GetUymax(), "C") textLetters.DrawLatex(43., 0.8*gPad.GetUymax(), "D") elif(ptype == "SIP"): textLetters.DrawLatex(6., 1.5, "A") textLetters.DrawLatex(16., 1.5, "B") textLetters.DrawLatex(23., 1.5, "C") textLetters.DrawLatex(43., 1.5, "D") # **** if(dataPeriod == "data2018"): # draw vertical lines that divide different data taking periods down = gPad.GetUymin() up = gPad.GetUymax() lineA = TLine(13.48, down, 13.48, up) # Run2018A up to 13.48 fb-1 lineA.SetLineColor(kBlack) lineA.SetLineStyle(2) lineA.Draw() lineB = TLine(20.265, down, 20.265, up) # Run2018B up to 20.265 fb-1 lineB.SetLineColor(kBlack) lineB.SetLineStyle(2) lineB.Draw() lineC = TLine(26.877, down, 26.877, up) # Run2018C up to 26.877 fb-1 lineC.SetLineColor(kBlack) lineC.SetLineStyle(2) lineC.Draw() # **** if(dataPeriod == "data2017"): # draw vertical lines that divide different data taking periods down = gPad.GetUymin() up = gPad.GetUymax() lineB = TLine(4.793, down, 4.793, up) # Run2017B up to 4.793 fb-1 lineB.SetLineColor(kBlack) lineB.SetLineStyle(2) lineB.Draw() lineC = TLine(14.549, down, 14.549, up) # Run2017C up to 14.549 fb-1 lineC.SetLineColor(kBlack) lineC.SetLineStyle(2) lineC.Draw() lineD = TLine(18.868, down, 18.868, up) # Run2017D up to 18.868 fb-1 lineD.SetLineColor(kBlack) lineD.SetLineStyle(2) lineD.Draw() lineE = TLine(28.293, down, 28.293, up) # Run2017E up to 28.293 fb-1 lineE.SetLineColor(kBlack) lineE.SetLineStyle(2) lineE.Draw() # **** if(dataPeriod == "data2016"): # draw vertical lines that divide different data taking periods down = gPad.GetUymin() up = gPad.GetUymax() lineB = TLine(5.789, down, 5.789, up) # Run2016B up to 5.789 fb-1 lineB.SetLineColor(kBlack) lineB.SetLineStyle(2) lineB.Draw() lineC = TLine(8.366, down, 8.366, up) # Run2016C up to 8.366 fb-1 lineC.SetLineColor(kBlack) lineC.SetLineStyle(2) lineC.Draw() lineD = TLine(12.616, down, 12.616, up) # Run2016D up to 12.616 fb-1 lineD.SetLineColor(kBlack) lineD.SetLineStyle(2) lineD.Draw() lineE = TLine(16.624, down, 16.624, up) # Run2016E up to 16.624 fb-1 lineE.SetLineColor(kBlack) lineE.SetLineStyle(2) lineE.Draw() lineF = TLine(19.725, down, 19.725, up) # Run2016F up to 19.725 fb-1 lineF.SetLineColor(kBlack) lineF.SetLineStyle(2) lineF.Draw() lineG = TLine(27.268, down, 27.268, up) # Run2016G up to 27.268 fb-1 lineG.SetLineColor(kBlack) lineG.SetLineStyle(2) lineG.Draw() # **** canvas.SaveAs(title + ".root") canvas.SaveAs(title + ".pdf") canvas.SaveAs(title + ".png") return;
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 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') x0, x1 = self.rangeX if x0 < x1: self.hStack.GetXaxis().SetRangeUser(x0, x1) if hasattr(self, 'MCstatUnc') and self.MCstatUnc != None: self.MCstatUnc.Draw("e2,same") if hasattr(self, 'MCnormUnc') and self.MCnormUnc != None: self.MCnormUnc.Draw("e2,same") if hasattr(self, 'MCunc') and self.MCunc != None: self.MCunc.Draw("e2,same") # Extra histograms for h in self.overlapHistos: h.Draw("hist,same") # Errors in data if hasattr(self, 'hData'): if not isinstance(self.hData, TGraphAsymmErrors): 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) if hasattr(self, 'hRatioStatUnc') and self.hRatioStatUnc != None: self.SetAxisRatio(self.hRatioStatUnc) if hasattr(self, 'hRatioNormUnc') and self.hRatioNormUnc != None: self.SetAxisRatio(self.hRatioNormUnc) # Legend if hasattr(self, 'processes'): self.hleg = [] leg = self.SetLegend() for pr in self.processes: htot = self.TotMC if hasattr( self, 'TotMC') else self.hStack.GetStack().Last() h = htot.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 if not pr in self.legnames.keys() else self.legnames[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() if self.doZoom: self.mini.cd() gPad.SetTickx() gPad.SetTicky() #if not os.path.isdir(self.GetOutPath()): os.makedirs(self.GetOutPath()) self.hStack2 = self.hStack.Clone("hStack2") self.hStack2.Draw('hist') if hasattr(self, 'MCstatUnc') and self.MCstatUnc != None: self.MCstatUnc.Draw("e2,same") if hasattr(self, 'MCnormUnc') and self.MCnormUnc != None: self.MCnormUnc.Draw("e2,same") if hasattr(self, 'MCunc') and self.MCunc != None: self.MCunc.Draw("e2,same") self.hStack2.GetYaxis().SetTitle("") # 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()) self.hStack2.GetXaxis().SetRangeUser(16, 20) #XLIMITS self.hStack2.GetYaxis().SetLabelSize(0.075) self.hStack2.GetXaxis().SetLabelSize(0.075) self.hStack2.GetXaxis().SetNdivisions(4) # Set Maximum datamax = self.hData.GetMaximum() if hasattr(self, 'hData') else -999 bkgmax = self.TotMC.GetMaximum() if hasattr( self, 'TotMC') else self.hStack2.GetStack().Last().GetMaximum() dmax = max(datamax, bkgmax) #if isinstance(self.PlotMaximum, float): self.hStack2.SetMaximum(self.PlotMaximum) self.hStack2.SetMaximum(dmax - dmax * 0.9) self.hStack2.SetMinimum(10) # Set titles... #TGaxis.SetMaxDigits(2) #self.SetAxisPlot(self.hStack) #self.mini.Draw() # Ratio if self.doRatio: self.ratio.cd() legr = self.SetLegendRatio() x0, x1 = self.rangeX if hasattr(self, 'hRatioStatUnc') and self.hRatioStatUnc != None: if x0 < x1: self.hRatioStatUnc.GetXaxis().SetRangeUser(x0, x1) 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, 'hRatioNormUnc') and self.hRatioNormUnc != None: if x0 < x1: self.hRatioNormUnc.GetXaxis().SetRangeUser(x0, x1) self.hRatioNormUnc.Draw('e2same') self.hRatioNormUnc.SetLineWidth(0) self.hRatioNormUnc.SetMaximum(self.PlotRatioMax) self.hRatioNormUnc.SetMinimum(self.PlotRatioMin) legr.AddEntry(self.hRatioNormUnc, 'Bkg norm', 'f') if hasattr(self, 'hRatioUnc') and self.hRatioUnc != None: if x0 < x1: self.hRatioUnc.GetXaxis().SetRangeUser(x0, x1) self.hRatioUnc.Draw('e2same') self.hRatioUnc.SetLineWidth(0) self.hRatioUnc.SetMinimum(self.PlotRatioMin) self.hRatioUnc.SetMaximum(self.PlotRatioMax) legr.AddEntry(self.hRatioUnc, 'Tot unc', 'f') #'Stat #oplus Syst', 'f') if hasattr(self, 'hRatio'): if x0 < x1: self.hRatio.GetXaxis().SetRangeUser(x0, x1) 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() for l in self.Line: l.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]) if hasattr(self, 'hRatioNormUnc'): self.hRatioNormUnc.GetXaxis().SetBinLabel( i + 1, self.binLabels[i]) else: self.hStack.GetXaxis().SetBinLabel(i + 1, self.binLabels[i]) self.Save()