def Create_Legend(x1, y1, x2, y2, font=42, text_size=0.045, fill=0, border_size=1, entry_sep=0, margin=0.3, show_stats=False, ncols=1): leg = TLegend(x1, y1, x2, y2) leg.SetTextFont(font) leg.SetTextSize(text_size) leg.SetFillColor(fill) leg.SetBorderSize(border_size) leg.SetEntrySeparation(entry_sep) leg.SetMargin(margin) leg.SetNColumns(ncols) if show_stats: leg.SetNColumns(2) ## Creating headers for the legend leg.AddEntry(0, "", "") # leg.AddEntry( 0, "#bf{Mean}", "") leg.AddEntry(0, "#bf{RMSE}", "") return leg
def SetLegendRatio(self): legr = TLegend(self.legratx0, self.legraty0, self.legratx1, self.legraty1) legr.SetTextSize(self.legratTextSize) legr.SetBorderSize(0) legr.SetFillColor(10) legr.SetNColumns(self.legratNcol) return legr
def doSuperTGraph( data, canvas, obj): xmin=-1.8 xmax=1.8 gStyle.SetOptFit(0) gStyle.SetOptStat(0) gROOT.SetBatch(1) color=[601,417,920,633,910,433,400,619,1,922] mg = TMultiGraph(); leg = TLegend(0.58,0.75,0.89,0.89); i=0 for ivar in data['var']: if not os.path.exists(data['fold']+"/"+ivar+"_ll.root"): continue print '>>> Opening File :' , data['fold']+"/"+ivar+"_ll.root" inFile = TFile.Open ( data['fold']+"/"+ivar+"_ll.root" ," READ ") c1 = inFile.Get(canvas); gr = c1.GetListOfPrimitives().FindObject(obj) xaxis = gr.GetXaxis().GetTitle() yaxis = gr.GetYaxis().GetTitle() gr.SetLineColor(color[i]) mg.Add(gr) leg.AddEntry(gr,ivar,"l") i=i+1 print i c = TCanvas() c.cd() c.SetGrid() mg.Draw("al") line1 = TF1("line1","pol0",-100,100) line1.FixParameter(0,1.) line1.SetLineWidth(2) line1.SetLineStyle(2) line1.SetLineColor(2) line1.Draw("same") line2 = TF1("line2","pol0",-100,100) line2.FixParameter(0,3.84) line2.SetLineWidth(2) line2.SetLineStyle(2) line2.SetLineColor(2) line2.Draw("same") mg.SetTitle(";" +xaxis+";" +yaxis) mg.GetYaxis().SetRangeUser(0,10) leg.SetNColumns(2) leg.SetBorderSize(0) leg.Draw("same") c.SaveAs(data['fold']+"combined10.png") c.SaveAs(data['fold']+"combined10.pdf") c.SaveAs(data['fold']+"combined10.root")
def SetLegend(self): leg = TLegend(self.legx0, self.legy0, self.legx1, self.legy1) leg.SetTextSize(self.legTextSize) leg.SetBorderSize(0) leg.SetFillColor(10) leg.SetNColumns(self.legNcol) return leg
def make_photon_fraction_plot(f_base, f_nightly, result_file): """ This functions created a photon validation plot with efficiencies and fractions :param f_base TFile with the baseline histograms: :param f_nightly TFile with the nightly histograms: """ for histo in get_key_names(f_nightly, 'truthPhotonConvRecoConvEfficiency'): variable_name = histo.split("_", 1)[1] c1 = TCanvas() leg = TLegend(0.1, 0.75, 0.9, 0.9) leg.SetNColumns(2) for i, folder in enumerate(photon_fraction_list): baseline = f_base.Get(folder['name'] + '/' + folder['name'] + "_" + variable_name) baseline.SetDirectory(0) nightly = f_nightly.Get(folder['name'] + '/' + folder['name'] + "_" + variable_name) nightly.SetDirectory(0) baseline.SetMinimum( min(baseline.GetMinimum(), baseline.GetMinimum()) * 0.7) baseline.SetMaximum( max(baseline.GetMaximum(), baseline.GetMaximum()) * 1.3) baseline.GetYaxis().SetTitle("Efficiency and fraction") baseline.SetLineColor(folder['color']) nightly.SetLineColor(folder['color']) baseline.SetMarkerColor(folder['color']) nightly.SetMarkerColor(folder['color']) baseline.SetMarkerStyle(1) nightly.SetMarkerStyle(20) leg.AddEntry(nightly, folder['title'], "p") if i == 0: baseline.Draw("hist ") else: baseline.Draw("same hist") nightly.Draw("p same") leg.Draw() c1.Update() result_file.cd() c1.SaveAs("ConvertionEff_" + variable_name + ".png") c1.Write("ConvertionEff_" + variable_name)
def draw_nice_legend(x=[0.7, 0.92], y=[0.7, 0.92], tit="", columns=1): global nice_legends leg = TLegend(x[0], y[0], x[1], y[1], tit) leg.SetLineColor(0) leg.SetNColumns(columns) nice_legends.append(leg) leg.Draw() return leg
def drawNorm(): hists = allHists() os.mkdir("plots/%s_norm" % region) for variable in variables: hist_data = hists[region + "_" + variable + "_data"] hist_signal = hists[region + "_" + variable + "_tth"] mchists = {} for i in processes: if i != 'data' and i != 'tth': temp = hists[region + "_" + variable + "_" + i] mchists[i] = temp hs = makeStack(mchists) h_bkg = hs.GetStack().Last().Clone("h_bkg") c = createCanvas() XTitle, YTitle = (titles[variable[0:len(variable) - 2]])[0], ( titles_norm[variable[0:len(variable) - 2]])[1] leg = TLegend(0.60, 0.70, 0.90, 0.90) leg.SetNColumns(2) leg.SetFillStyle(0) leg.SetBorderSize(0) leg.AddEntry(hist_data, "data", "pe") leg.AddEntry(hist_signal, "tth", "l") #normalize individual hist mchists_norm = {} for i in mchists: mchists[i].Scale(1. / h_bkg.Integral()) mchists_norm[i] = mchists[i] hs_norm = makeStack(mchists_norm) for i in mchists: leg.AddEntry(mchists_norm[i], i, "f") leg.AddEntry(h_bkg, "uncertainty", 'f') #draw hs_norm.SetTitle("") hs_norm.SetMaximum(3 * hist_data.GetBinContent(hist_data.GetMaximumBin()) / hist_data.Integral()) hs_norm.Draw("hist") hs_norm.GetYaxis().SetTitleSize(0.06) hs_norm.GetYaxis().SetTitleOffset(1) hs_norm.GetYaxis().SetTitle(YTitle) hs_norm.GetXaxis().SetTitle(XTitle) #hs_norm.GetXaxis().SetTitleSize(0.) #hs_norm.GetXaxis().SetLabelSize(0.) h_bkg.SetFillStyle(3253) h_bkg.SetFillColor(13) h_bkg.SetLineColor(13) h_bkg.DrawNormalized("E2 same") hist_data.SetMarkerStyle(20) hist_data.SetMarkerSize(0.8) #hist_data.SetLineColor(kBlack) hist_data.DrawNormalized("e x0 same") hist_signal.SetLineColor(kRed) hist_signal.SetLineStyle(kDashed) hist_signal.DrawNormalized("hist same") createLabels() leg.Draw("same") c.SaveAs("plots/%s_norm/%s.pdf" % (region, variable))
def doSuperTGraphAll( file_list, canvas, obj, output): gStyle.SetOptFit(0) gStyle.SetOptStat(0) gROOT.SetBatch(1) mg = TMultiGraph(); leg = TLegend(0.58,0.75,0.89,0.89); for iFile in file_list: if not os.path.exists(iFile['path']): print '>>> This File does not exist --> '+iFile['path']+'... check path ... ' continue print '>>> Opening File :' , iFile['path'] inFile = TFile.Open ( iFile['path'] ," READ ") c1 = inFile.Get(canvas); gr = c1.GetListOfPrimitives().FindObject(obj) xaxis = gr.GetXaxis().GetTitle() yaxis = gr.GetYaxis().GetTitle() gr.SetLineColor(iFile['color']) mg.Add(gr) leg.AddEntry(gr,iFile['legend'],"l") c = TCanvas() c.cd() c.SetGrid() mg.Draw("al") line1 = TF1("line1","pol0",-100,100) line1.FixParameter(0,1.) line1.SetLineWidth(2) line1.SetLineStyle(2) line1.SetLineColor(2) line1.Draw("same") line2 = TF1("line2","pol0",-100,100) line2.FixParameter(0,3.84) line2.SetLineWidth(2) line2.SetLineStyle(2) line2.SetLineColor(2) line2.Draw("same") mg.SetTitle(";" +xaxis+";" +yaxis) mg.GetYaxis().SetRangeUser(0,10) leg.SetNColumns(2) leg.SetBorderSize(0) leg.Draw("same") c.SaveAs(output+"10.png") c.SaveAs(output+"10.pdf") c.SaveAs(output+"10.root")
def Draw(self): canvas=TCanvas(self.name+'canvas','') canvas.Print('picture/'+self.name+'.pdf[') j=0 text_name='' textvalue='' if(self.ValueName1=='colrow'): text_name='(col, row)' else: text_name=self.ValueName1 text2_name='' text2value='' if(self.ValueName2=='colrow'): #text2_name='#splitline{pixel coordinates}{(col,row)}' text2_name='pixel(column,row)' else: text2_name=self.ValueName2 for graph_list_1 in self.graph_list: legend=TLegend(self.legend_xl,self.legend_yb,self.legend_xr,self.legend_yt,text2_name) legend.SetNColumns(self.legend_Col) legend.SetBorderSize(self.legend_Border) i=1 for pixel_graph in graph_list_1: graph=pixel_graph.CreateGraph() graph.SetLineColor(i) graph.SetMarkerColor(i) graph.SetMarkerStyle(8) if(self.ValueName2=='colrow'): text2value='('+str(int(self.Value3List[j][i-1]/1000))+', '+str(self.Value3List[j][i-1]%1000)+')' else: text2value=str(self.Value3List[j][i-1]) legend.AddEntry(graph,text2value,'lp') canvas.cd() if i == 1 : #graph.Draw("APL") graph.Draw("AP") else : #graph.Draw("PL") graph.Draw("P") i=i+1 legend.Draw('same') if(self.ValueName1=='colrow'): textvalue='('+str(int(self.Value1List[j]/1000))+', '+str(self.Value1List[j]%1000)+')' else: textvalue=str(self.Value1List[j]) text=ROOT.TText(0.18,0.83,text_name+'='+textvalue) text.SetTextFont(62) text.SetNDC(1) text.Draw() canvas.Print('picture/'+self.name+'.pdf') j=j+1 canvas.Print('picture/'+self.name+'.pdf]')
def makeLowerLegend(obs_over_pred, relative_bkg_stat_unc, relative_bkg_total_unc): legend = TLegend(0.18, 0.85, 0.94, 0.98, '', 'brNDC') legend.SetNColumns(3) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.AddEntry(relative_bkg_stat_unc, 'Stat. pred. unc.', 'f') legend.AddEntry(relative_bkg_total_unc, 'Total pred. unc.', 'f') legend.AddEntry(obs_over_pred, 'Obs./Pred.', 'pe12') return legend
def correctedCrossSectionsPlot(crossings, shapes, overDiff): uncorrected = {41: (3.2575816286, 0.00514858611944), \ 281: (3.26316215713, 0.00468789412223), \ 872: (3.27340775031, 0.00484925398906), \ 1783: (3.24986926821, 0.00460908436455), \ 2063: (3.26363843728, 0.0044071069983)} multi = TMultiGraph('sigmavis', '') graphs = [] n = len(shapes) + 1 for i, shape in enumerate([''] + list(shapes)): xval = array('d', [a + 0.08 * (i - 0.5 * n) for a in range(len(crossings))]) xerr = array('d', len(crossings) * [0]) yval = array('d', [uncorrected[int(bx)][0] for bx in crossings]) yerr = array('d', [uncorrected[int(bx)][1] for bx in crossings]) if shape: for j, bx in enumerate(crossings): yval[j] *= 1 + overDiff[shape][bx] yerr[j] *= 1 + overDiff[shape][bx] graph = TGraphErrors(len(crossings), xval, yval, xerr, yerr) graph.SetName('ge' + shape) graph.SetMarkerStyle(20) graph.SetMarkerColor(1 + i) multi.Add(graph) graphs.append(graph) gStyle.SetOptStat(0) hist = TH2F('hist', '', len(crossings), -0.5, len(crossings) - 0.5, 100, 3.23, 3.33) for i, bx in enumerate(crossings): hist.GetXaxis().SetBinLabel(i + 1, bx) canvas = TCanvas('c_' + multi.GetName(), '', 600, 600) hist.Draw('AXIS') multi.Draw('P') canvas.Update() hist.GetXaxis().SetLabelSize(0.035) hist.GetXaxis().SetNdivisions(len(crossings), False) hist.GetYaxis().SetTitle('#sigma_{vis} [b]') hist.GetYaxis().SetLabelSize(0.025) hist.GetYaxis().SetTitleOffset(1.3) leg = TLegend(0.15, 0.82, 0.85, 0.85) leg.SetNColumns(len(shapes) + 1) leg.SetBorderSize(0) for i, shape in enumerate([''] + list(shapes)): entry = leg.AddEntry('ge' + shape, shapeNames[shape], 'P') entry.SetMarkerStyle(20) entry.SetMarkerColor(1 + i) leg.Draw() drawCMS() canvas.Modified() canvas.Update() canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.pdf') canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.C')
def myLegend(coordinate=[0.48, 0.55, 0.97, 0.87], ncol=1): co = coordinate leg = TLegend(co[0], co[1], co[2], co[3]) leg.SetNColumns(ncol) leg.SetBorderSize(0) leg.SetLineColor(1) leg.SetLineStyle(1) leg.SetLineWidth(1) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextFont(42) leg.SetTextSize(0.035) return leg
def SetLegend(coordinate_=[.15, .7, .47, .87], ncol=1): c_ = coordinate_ legend = TLegend(c_[0], c_[1], c_[2], c_[3]) legend.SetBorderSize(0) legend.SetNColumns(ncol) legend.SetLineColor(1) legend.SetLineStyle(1) legend.SetLineWidth(1) legend.SetFillColor(0) legend.SetFillStyle(0) legend.SetTextFont(42) legend.SetTextSize(0.05) return legend
def create_legend(self, models): """Add a legend with the model names to the plot.""" l = TLegend(0.15, 0.77, 0.85, 0.83) l.SetNColumns(3) l.SetBorderSize(0) for mod, gr, mark, clr in zip(models, self._multi.GetListOfGraphs(), self.markers, self.colors): gr.SetMarkerStyle(mark) gr.SetMarkerColor(clr) entry = l.AddEntry(gr.GetName(), mod, 'P') entry.SetMarkerStyle(mark) entry.SetMarkerColor(clr) self.add(l) return l
def makeUpperLegend(data, processCollection, bkg_total, legend_names=None, draw_signal=False, signal_legend_names=None): legend = TLegend(0.25, 0.73, 0.87, 0.92, '', 'brNDC') legend.SetNColumns(3) if draw_signal else legend.SetNColumns(2) legend.SetFillStyle(0) #avoid box legend.SetBorderSize(0) legend.AddEntry(data, 'Data', 'pe1') for p in processCollection: if p.isSignal(): continue addProcessToLegend(legend, p, 'f', legend_names) legend.AddEntry(bkg_total, 'Total bkg. unc.', 'f') if draw_signal: for s in processCollection.signals(): addProcessToLegend(legend, s, 'l', signal_legend_names) return legend
def drawHisto(h1, h2, name, var): #gStyle.SetOptStat(0000) name = os.path.join('inVarPlots/', name) h1.SetMarkerStyle(20) h1.SetMarkerColor(kBlue) h1.SetLineColor(kBlue) h1.SetLineWidth(2) h2.SetMarkerStyle(20) h2.SetMarkerColor(kRed) h2.SetLineColor(kRed) h2.SetLineWidth(2) h1.GetXaxis().SetTitle(var) h1.Scale(41.5) if h1.Integral() != 0 and h2.Integral() != 0: h2.Scale(h1.Integral() / h2.Integral()) h2.GetXaxis().SetTitle(var) leg = TLegend(0.455, 0.85, 0.76, 0.89, "", "brNDC") leg.SetBorderSize(0) leg.SetTextSize(0.035) leg.SetFillColor(0) leg.SetNColumns(2) leg.AddEntry(h1, "w/ weights", "L") leg.AddEntry(h2, "w/o weights", "L") maximum = h1.GetMaximum() if h2.GetMaximum() >= maximum: maximum = h2.GetMaximum() maximum *= 1.01 h2.GetYaxis().SetRangeUser(0., maximum) c = TCanvas() h2.Draw("HIST") h1.Draw("HIST,same") leg.Draw("same") c.SaveAs(name + ".png", "png") c.SaveAs(name + ".pdf", "pdf") h2.GetYaxis().SetRangeUser(0.001, maximum * 5.) c.SetLogy() h2.Draw("HIST") h1.Draw("HIST,same") leg.Draw("same") c.SaveAs(name + "_log.png", "png") c.SaveAs(name + "_log.pdf", "pdf")
def setup_canvas(hist_name): canvas = TCanvas(hist_name, hist_name, 0, 0, 800, 800) canvas.SetMargin(0.13, 0.05, 0.12, 0.05) canvas.SetTicks(1, 1) leg = TLegend(0.3, 0.15, 0.75, 0.4) leg.SetNColumns(3) leg.SetBorderSize(0) leg.SetTextSize(0.03) leg.SetTextFont(42) leg.SetMargin(0.2) leg.SetHeader("Train setup: #it{N}_{ev}^{training}, #it{n}_{#it{#varphi}}" +\ " #times #it{n}_{#it{r}} #times #it{n}_{#it{z}}", "C") return canvas, leg
def makeDiscr(discr_dict, outfile, xtitle="discriminator", nbins=30, x_min=0, x_max=1): c = ROOT.TCanvas("c", "c", 800, 500) ROOT.gStyle.SetOptStat(0) ROOT.gPad.SetMargin(0.15, 0.1, 0.2, 0.1) #ROOT.gPad.SetLogy(1) #ROOT.gPad.SetGrid(1,1) ROOT.gStyle.SetGridColor(17) l = TLegend(0.17, 0.75, 0.88, 0.88) l.SetTextSize(0.055) l.SetBorderSize(0) l.SetFillStyle(0) l.SetNColumns(2) colors = [2, 4, 8, ROOT.kCyan + 2] counter = 0 for leg, discr in discr_dict.iteritems(): a = Hist(nbins, x_min, x_max) #fill_hist_with_ndarray(a, discr) a.fill_array(discr) a.SetLineColor(colors[counter]) a.SetLineWidth(2) a.GetXaxis().SetTitle(xtitle) a.GetXaxis().SetLabelSize(0.05) a.GetXaxis().SetTitleSize(0.05) a.GetXaxis().SetTitleOffset(1.45) a.GetYaxis().SetTitle("a.u.") a.GetYaxis().SetTickSize(0) a.GetYaxis().SetLabelSize(0) a.GetYaxis().SetTitleSize(0.06) a.GetYaxis().SetTitleOffset(0.9) a.Scale(1. / a.Integral()) #a.GetYaxis().SetRangeUser(0.00001,100) a.GetYaxis().SetRangeUser(0, 0.2) if counter == 0: a.draw("hist") else: a.draw("same hist") l.AddEntry(a, leg, "l") counter += 1 l.Draw("same") c.SaveAs(outfile)
def makeUpperLegend(data, processCollection, bkg_total, legend_names=None): legend = TLegend(0.20, 0.73, 0.92, 0.90, '', 'brNDC') legend.SetNColumns(3) legend.SetFillStyle(0) #avoid box legend.SetBorderSize(0) legend.AddEntry(data, 'Total bkg', 'pe1') for p in processCollection: if p.isSignal(): continue name = p.name() if legend_names is not None: try: name = legend_names[p.name()] except KeyError: pass legend.AddEntry(p.nominal(), name, 'f') legend.AddEntry(bkg_total, 'Total bkg. unc.', 'f') return legend
def main(directories): hists = [] for directory in directories: #basename = os.path.basename(root_file_name) #print '--> processing %s' % basename hist = get_hist_from_files(directory) hists.append(hist) # end loop over hists canvas = TCanvas('canvas', '') canvas.SetLogy(1) legend = TLegend(0.1, 0.9, 0.9, 0.99) legend.SetNColumns(2) hist_zero = hists[0] hist_zero.Draw('hist') max = hist_zero.GetMaximum() for i_hist in range(len(hists)): hist = hists[i_hist] hist.SetLineColor(i_hist + 1) hist.Draw('hist same') legend.AddEntry(hist, hist.GetName(), 'l') legend.Draw() hist_zero.SetMinimum(max / 1e4) canvas.Update() canvas.Print('mageSpectra.pdf') raw_input('--> enter to continue') return hist_zero.SetAxisRange(2030, 2040) hist_zero.SetMinimum(0) canvas.SetLogy(0) canvas.Update() canvas.Print('mageSpectra_zoom.pdf') raw_input('--> enter to continue')
def compare(objs, add_leg_title=True, normalize=True): print("Comparing") cols = ['#e41a1c', '#377eb8', '#4daf4a'] colors = {} drawn = {} for i in objs: print("Entry", len(colors), i) colors[i] = TColor.GetColor(cols[len(colors)]) # Drawing objects for i in objs: for j in objs[i]: obj = objs[i][j] opt = "" if drawn.setdefault(j, None) is None: drawn[j] = [TCanvas(j, j)] else: opt += "same" drawn[j][0].cd() print("Drawing", obj, "with opt", opt, "on canvas", gPad.GetName()) obj.SetLineColor(colors[i]) obj.SetBit(TH1.kNoTitle) obj.SetBit(TH1.kNoStats) obj.SetTitle(i) if normalize: drawn[j].append(obj.DrawNormalized(opt)) else: drawn[j].append(obj.DrawClone(opt)) for i in drawn: d = drawn[i] can = d[0] can.cd() gPad.SetLogy() leg = TLegend(.1, .9, .9, .99, can.GetName()) leg.SetNColumns(2) d.append(leg) for j in can.GetListOfPrimitives(): leg.AddEntry(j) leg.Draw() return drawn
def efficiencytracking(var): # plots the efficiency vs pT, eta and phi for all the species(it extracts the # Efficiency from qa - tracking - efficiency if you have ran with-- make - eff) hadron_list = [ "pion", "proton", "kaon", "electron", "muon", ] color_list = [1, 2, 4, 6, 8] marker_list = [20, 21, 22, 34, 45] fileo2 = TFile("../codeHF/AnalysisResults_O2.root") c1 = TCanvas("c1", "Efficiency") gStyle.SetOptStat(0) gStyle.SetErrorX(0) gStyle.SetFrameLineWidth(2) gStyle.SetTitleSize(0.045, "x") gStyle.SetTitleSize(0.045, "y") gStyle.SetMarkerSize(1) gStyle.SetLabelOffset(0.015, "x") gStyle.SetLabelOffset(0.02, "y") gStyle.SetTickLength(-0.02, "x") gStyle.SetTickLength(-0.02, "y") gStyle.SetTitleOffset(1.1, "x") gStyle.SetTitleOffset(1.0, "y") c1.SetCanvasSize(800, 600) c1.cd() c1.SetGridy() c1.SetGridx() eff_list = [] if var == "Pt": hempty = TH1F("hempty", ";Transverse Momentum(GeV/c);Efficiency", 100, 0.05, 10) gPad.SetLogx() elif var == "Eta": hempty = TH1F("hempty", ";Pseudorapidity;Efficiency", 100, -4.0, 4.0) elif var == "Phi": hempty = TH1F("hempty", ";Azimuthal angle(rad);Efficiency", 100, 0.0, 6.0) hempty.GetYaxis().CenterTitle() hempty.GetXaxis().CenterTitle() hempty.GetXaxis().SetNoExponent() hempty.GetXaxis().SetMoreLogLabels(1) hempty.Draw() leg = TLegend(0.55, 0.15, 0.89, 0.35, "P") leg.SetNColumns(2) leg.SetHeader("Minimum bias KrKr #sqrt{s} = 6.46TeV", "C") leg.SetFillColor(0) for i, had in enumerate(hadron_list): leff = fileo2.Get("qa-tracking-efficiency-%s/Efficiency" % had) if var == "Pt": eff = leff.At(0) elif var == "Eta": eff = leff.At(1) elif var == "Phi": eff = leff.At(2) gPad.Update() eff.Paint("p") gr = eff.GetPaintedGraph().Clone() for j in range(0, gr.GetN()): gr.GetEXlow()[j] = 0 gr.GetEXhigh()[j] = 0 gr.SetLineColor(color_list[i]) gr.SetMarkerColor(color_list[i]) gr.SetMarkerStyle(marker_list[i]) eff_list.append(gr) gr.Draw(" same p") leg.AddEntry(eff_list[i], had, "p") leg.Draw() saveCanvas(c1, "efficiency_tracking_%s" % var)
def DrawOverlap(fileVec, histVec, titleVec, legendtext, pngname, logstatus=[0, 0], xRange=[-99999, 99999, 1], text_="", x_=0.5, y_=0.5, legendloc=[0.53, 0.13, 0.93, 0.39]): gStyle.SetOptTitle(0) gStyle.SetOptStat(0) #gStyle.SetTitleOffset(1.1,"Y"); #gStyle.SetTitleOffset(0.9,"X"); gStyle.SetLineWidth(3) gStyle.SetFrameLineWidth(3) i = 0 histList_ = [] histList = [] histList1 = [] maximum = [] ## Legend legpos = legendloc leg = TLegend(legpos[0], legpos[1], legpos[2], legpos[3]) leg.SetBorderSize(0) leg.SetNColumns(2) leg.SetLineColor(1) leg.SetLineStyle(1) leg.SetLineWidth(1) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextFont(42) leg.SetTextSize(0.049) from PlotTemplates import myCanvas1D c = myCanvas1D() c.SetLogy(logstatus[1]) c.SetLogx(logstatus[0]) #c.SetBottomMargin(0.15) #c.SetLeftMargin(0.15) #c1_2 = TPad("c1_2","newpad",0.04,0.13,1,0.994) #c1_2.Draw() print("you have provided " + str(len(fileVec)) + " files and " + str(len(histVec)) + " histograms to make a overlapping plot") print "opening rootfiles" c.cd() #c1_2.SetBottomMargin(0.013) #c1_2.SetLogy(logstatus[1]) #c1_2.SetLogx(logstatus[0]) #c1_2.cd() ii = 0 inputfile = {} print str(fileVec[(len(fileVec) - 1)]) for ifile_ in range(len(fileVec)): print("opening file " + fileVec[ifile_]) inputfile[ifile_] = TFile(fileVec[ifile_]) print "fetching histograms" for ihisto_ in range(len(histVec)): print("printing histo " + str(histVec[ihisto_])) histo = inputfile[ifile_].Get(histVec[ihisto_]) #status_ = type(histo) is TGraphAsymmErrors histList.append(histo) # for ratio plot as they should nt be normalize histList1.append(histo) #print histList[ii].Integral() #histList[ii].Rebin(xRange[2]) #histList[ii].Scale(1.0/histList[ii].Integral()) maximum.append(histList[ii].GetMaximum()) maximum.sort() ii = ii + 1 print histList for ih in range(len(histList)): tt = type(histList[ih]) if logstatus[1] is 1: histList[ih].SetMaximum(100) #1.4 for log histList[ih].SetMinimum(0.00001) #1.4 for log if logstatus[1] is 0: histList[ih].SetMaximum(1.4) #1.4 for log histList[ih].SetMinimum(0.001) #1.4 for log # print "graph_status =" ,(tt is TGraphAsymmErrors) # print "hist status =", (tt is TH1D) or (tt is TH1F) if ih == 0: if tt is TGraphAsymmErrors: histList[ih].Draw("APL") if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I): histList[ih].Draw("hist") if ih > 0: #histList[ih].SetLineWidth(2) if tt is TGraphAsymmErrors: histList[ih].Draw("PL same") if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I): histList[ih].Draw("hist same") if tt is TGraphAsymmErrors: histList[ih].SetMaximum(10) histList[ih].SetMarkerColor(colors[ih]) histList[ih].SetLineColor(colors[ih]) histList[ih].SetMarkerStyle(markerStyle[ih]) histList[ih].SetMarkerSize(1) leg.AddEntry(histList[ih], legendtext[ih], "PL") if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I): histList[ih].SetLineStyle(linestyle[ih]) histList[ih].SetLineColor(colors[ih]) histList[ih].SetLineWidth(3) leg.AddEntry(histList[ih], legendtext[ih], "L") histList[ih].GetYaxis().SetTitle(titleVec[1]) histList[ih].GetYaxis().SetTitleSize(0.052) histList[ih].GetYaxis().SetTitleOffset(1.08) histList[ih].GetYaxis().SetLabelSize(.052) histList[ih].GetXaxis().SetRangeUser(xRange[0], xRange[1]) histList[ih].GetXaxis().SetLabelSize(0.052) histList[ih].GetXaxis().SetTitle(titleVec[0]) histList[ih].GetXaxis().SetLabelSize(0.052) histList[ih].GetXaxis().SetTitleSize(0.052) histList[ih].GetXaxis().SetTitleOffset(1.14) #histList[ih].GetXaxis().SetTickLength(0.07) histList[ih].GetXaxis().SetNdivisions(508) from PlotTemplates import SetCMSAxis histList[ih] = SetCMSAxis(histList[ih], 1.0, 1.15) #histList[ih].GetXaxis().SetMoreLogLabels(); #histList[ih].GetXaxis().SetNoExponent(); #histList[ih].GetTGaxis().SetMaxDigits(3); i = i + 1 ''' pt = TPaveText(0.0877181,0.9,0.9580537,0.96,"brNDC") pt.SetBorderSize(0) pt.SetTextAlign(12) pt.SetFillStyle(0) pt.SetTextFont(22) pt.SetTextSize(0.046) text = pt.AddText(0.2,0.5,"CMS Internal") ''' from PlotTemplates import drawenergy1D pt_ = drawenergy1D(False) for ipt in pt_: ipt.Draw() ''' if len(text_) >0: ltx = TLatex() ltx.SetTextFont(42) ltx.SetTextSize(0.049) #text_f = "#font[42]{Phase Scan}" ltx.DrawTextNDC(x_,y_,text_) ''' from PlotTemplates import ExtraText text_ex = ExtraText(text_, x_, y_) text_ex.Draw() ExtraText("ECAL Endcaps", 0.4, 0.85) ltx_ = TLatex() ltx_.SetTextFont(42) ltx_.SetTextSize(0.049) ltx_.DrawLatexNDC(0.32, 0.81, "L1 e-#gamma object p_{T} > 10 GeV") #text_ex.Draw() #pt = TPaveText(0.0877181,0.9,0.9580537,0.96,"brNDC") #text = pt.AddText(0.65,0.5,"Phase Scan data #sqrt{s} = 13 TeV (2018)") #pt.Draw() # t2a = TPaveText(0.0877181,0.81,0.9580537,0.89,"brNDC") # t2a.SetBorderSize(0) # t2a.SetFillStyle(0) # t2a.SetTextSize(0.040) # t2a.SetTextAlign(12) # t2a.SetTextFont(62) # histolabel1= str(fileVec[(len(fileVec)-1)]) # text1 = t2a.AddText(0.06,0.5,"CMS Internal") # t2a.Draw() leg.SetHeader("Matched TP energy") leg.Draw() # # c.cd() outputdirname = './' histname = outputdirname + pngname c.SaveAs(histname + '.png') c.SaveAs(histname + '.pdf')
ttt = tt + ";" + tx + ";" + sys.argv[2] + " :: " + sys.argv[3] h0.SetTitle(ttt) if len(hh) > 2: ymin = h0.GetMinimum() ymax = h0.GetMaximum() max1 = ymax + ymax - ymin h0.SetMaximum(max1) h0.Draw("HIST") leg = TLegend(0.1, 0.55, 0.9, 0.9) for h in hh: h.Draw("HISTSAME") tit = h.GetTitle() leg.AddEntry(h, tit, "l") if len(hh) > 2: if len(hh) > 30: leg.SetNColumns(4) elif len(hh) > 20: leg.SetNColumns(3) elif len(hh) > 5: leg.SetNColumns(2) leg.Draw() #=== simple diff plot if cmd == "diff": h = dp.getDiffPlot(1) h.Draw('COLZ') #=== simple diff profile plot if cmd == "diffprof": h = dp.getDiffPlot(2) h.Draw('COLZ')
#bxs += ["%i-%i" % (x , x+24) for x in bx_list] #bxs += ["%i-%i" % (x+24, x+48) for x in bx_list] for ilayer, layer in enumerate(layers): for iplot, plot in enumerate(plots): print "\nPLOT %i / %i" % ( iplot + ilayer * len(plots) + 1 , len(layers) * len(plots)) # Do TH2 histos plotname = 'h_%s_%s' % (plot, layer) if 'TH2' in plots[plot]['class']: c2.cd() legend = TLegend(0.25, 0.72, 0.80, 0.93, "") legend.SetNColumns(2) legend.SetFillColor(ROOT.kWhite) legend.SetLineColor(ROOT.kWhite) legend.SetShadowColor(ROOT.kWhite) for irun, run in enumerate(runs): for ilumisection, lumisection in enumerate(lumisections): for ibx, bx in enumerate(bxs): # for ibx, bx in enumerate(bx_list): for k in keyList: if plots[plot]['histname'] not in k: continue if layer not in k or str(run) not in k: continue # if 'LS_%i-%i_%s' % (lumisection[0], lumisection[1], layer) not in k: if '_%i-%i_%s' % (lumisection[0], lumisection[1], layer) not in k: continue
qcd_color, vh_color, diboson_color, singletop_color, ttbar_color, zll_color, wjets_color, zvv_color ] print color legend = TLegend(0.65, 0.7, 0.92, 0.89) legend.SetTextSize(0.046) legend.SetBorderSize(0) legend.SetLineColor(1) legend.SetLineStyle(1) legend.SetLineWidth(1) legend.SetFillColor(0) legend.SetFillStyle(0) legend.SetTextFont(42) legend.SetNColumns(2) i = 0 for iprocess in processes: hist_met_ = fin.Get('h_summary_' + iprocess) hist_met_.Sumw2() hist_met_.SetDirectory(0) TH1.AddDirectory(0) # gStyle.SetPalette(53) hist_met_.SetFillColor(color[i]) #hist_met_.SetLineColor(color[i]) bkgStack.Add(hist_met_, 'hist') legend.AddEntry(hist_met_, processesLegend[i], "f") i = i + 1 c = TCanvas()
def stack_hists(self, hists_, title, variable_name, input_hist_data, dodata=0): c1 = ROOT.TCanvas('c1', ',1000,1000') p1 = ROOT.TPad('p1', 'p1', 0.0, 0.0, 1.0, 1.0) p1.Draw() p1.SetRightMargin(0.1) p1.SetLeftMargin(0.1) p1.SetBottomMargin(0.1) p1.SetTopMargin(0.1) p1.SetGridx(True) p1.SetGridy(True) p1.cd() ROOT.gStyle.SetOptStat(0) ROOT.gStyle.SetOptTitle(0) hist_count = 0 maxy = 0 legend = TLegend(0.7, 0.7, 0.9, 0.9) legend.SetNColumns(2) process_list = OrderedDict([("Conv", 5), ("EWK", 6), ("Fakes", 13), ("Flips", 17), ("Rares", 38), ("TTW", 8), ("TTZ", 9), ("TTWW", 3), ("TTH_hww", 2), ("TTH_hzz", 2), ("TTH_htt", 2), ("TTH_hot", 2), ("TTH_hmm", 2), ("Data", 1)]) stacked_hist = ROOT.THStack() #binning_ = self.define_binning(input_hist_data.GetName()) for name, hist_ in hists_.iteritems(): print 'name = ', name for key in process_list: if key in name: if key == 'TTW' and 'TTWW' in name: continue print 'add %s to legend' % (key) hist_.SetMarkerColor(process_list[key]) hist_.SetMarkerStyle(20) hist_.SetLineColor(process_list[key]) hist_.SetFillColor(process_list[key]) hist_.SetFillStyle(3002) if 'Data' in name: legend.AddEntry(hist_, key, 'p') else: legend.AddEntry(hist_, key, 'f') if 'Data' in name: continue stacked_hist.Add(hist_) stacked_hist.SetTitle(title) stacked_hist.SetMaximum(stacked_hist.GetStack().Last().GetMaximum() + (stacked_hist.GetStack().Last().GetMaximum() / 2)) stacked_hist.SetMinimum(0.) #input_hist_data = hists_.get(data_hist_name) maxy = stacked_hist.GetMaximum() * 1.2 if stacked_hist.GetStack().Last( ).GetMaximum() > input_hist_data.GetMaximum( ) else input_hist_data.GetMaximum() * 1.2 histo_title_mc = 'MC' stacked_hist.Draw('HIST') stacked_hist.SetTitle(histo_title_mc) stacked_hist.GetYaxis().SetTitle('Events') stacked_hist.GetXaxis().SetTitle(variable_name) stacked_hist.SetMaximum(maxy) if dodata == 1: histo_title_data = 'DATA' input_hist_data.Draw('HISTSAMEEP') input_hist_data.SetTitle(histo_title_data) input_hist_data.GetYaxis().SetTitle('Events') input_hist_data.GetXaxis().SetTitle(variable_name) input_hist_data.SetMaximum(maxy) legend.Draw('SAME') c1.Update() c1.SaveAs(self.output_fullpath, 'png') return stacked_hist
h_Night = f2.Get(folder + '/' + histo) h_Night.SetMarkerStyle(8) h_Night.SetMarkerSize(0.5) mainPad.cd() h_Base.Draw() h_Night.Draw("same p") c1.Update() var_name = histo.split("_", 1)[1] leg = TLegend(0.330986, 0.884087, 0.879499, 0.97053) leg.SetHeader(folder + '' + var_name, "C") leg.SetNColumns(2) leg.SetFillStyle(0) leg.SetBorderSize(0) leg.AddEntry(h_Base, "Baseline", "l") leg.AddEntry(h_Night, "Nightly", "p") leg.Draw() c1.Update() ratioPad.cd() h1clone = h_Night.Clone() h1clone.Sumw2() h1clone.SetStats(0) h1clone.Divide(h_Base) h1clone.SetMarkerColor(1)
def pulls(fileName): content = filterPullFile(fileName) nbins, off = len(content), 0.10 b_pulls = TH1F("b_pulls", ";;Pulls", nbins, 0. - off, nbins - off) s_pulls = TH1F("s_pulls", ";;Pulls", nbins, 0. + off, nbins + off) # for i, s in enumerate(content): l = s.split() b_pulls.GetXaxis().SetBinLabel(i + 1, l[0]) s_pulls.GetXaxis().SetBinLabel(i + 1, l[0]) b_pulls.SetBinContent(i + 1, float(l[1])) b_pulls.SetBinError(i + 1, float(l[2])) s_pulls.SetBinContent(i + 1, float(l[3])) s_pulls.SetBinError(i + 1, float(l[4])) b_pulls.SetFillStyle(3005) b_pulls.SetFillColor(923) b_pulls.SetLineColor(923) b_pulls.SetLineWidth(2) b_pulls.SetMarkerStyle(20) b_pulls.SetMarkerSize(1.25) s_pulls.SetLineColor(602) s_pulls.SetMarkerColor(602) s_pulls.SetMarkerStyle(24) #24 s_pulls.SetLineWidth(2) b_pulls.GetYaxis().SetRangeUser(-2.5, 2.5) canvas = TCanvas("canvas", "Pulls", 1600, 800) canvas.cd() canvas.GetPad(0).SetTopMargin(0.06) canvas.GetPad(0).SetRightMargin(0.05) canvas.GetPad(0).SetBottomMargin(0.15) canvas.GetPad(0).SetTicks(1, 1) # box = TBox(950., 105., 2000., 200.) # box.SetFillStyle(3354) # #box.SetFillStyle(0) # box.SetFillColor(1) # box.SetLineWidth(2) # box.SetLineStyle(2) # box.SetLineColor(1) # box.Draw() # Draw b_pulls.Draw("PE1") #b_pulls.Draw("B") s_pulls.Draw("SAME, PE1") leg = TLegend(0.25, 0.95, 0.75, 0.995) leg.SetBorderSize(0) leg.SetFillStyle(0) leg.SetFillColor(0) leg.SetNColumns(2) leg.AddEntry(b_pulls, "background-only fit", "flp") leg.AddEntry(s_pulls, "signal+background fit", "lp") if text: leg.AddEntry(0, text, "") line = TLine() line.DrawLine(0., 0., nbins, 0.) line.SetLineStyle(7) line.SetLineWidth(2) line.SetLineColor(417) line.DrawLine(0., 1., nbins, 1.) line.DrawLine(0., -1., nbins, -1.) line.SetLineColor(800) line.DrawLine(0., 2., nbins, 2.) line.DrawLine(0., -2., nbins, -2.) leg.Draw() # drawCMS(LUMI, "Simulation") # drawAnalysis("DM") # drawRegion(channel) # canvas.Print(outName+".jpg") canvas.Print(outName + ".png") canvas.Print(outName + ".pdf") if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
def pullsVertical(fileName): content = filterPullFile(fileName) nbins, off = len(content), 0.10 b_pulls = TH1F("b_pulls", ";;Pulls", nbins, 0. - off, nbins - off) s_pulls = TH1F("s_pulls", ";;Pulls", nbins, 0. + off, nbins + off) # for i, s in enumerate(content): l = s.split() b_pulls.GetXaxis().SetBinLabel(i + 1, l[0]) s_pulls.GetXaxis().SetBinLabel(i + 1, l[0]) b_pulls.SetBinContent(i + 1, float(l[1])) b_pulls.SetBinError(i + 1, float(l[2])) s_pulls.SetBinContent(i + 1, float(l[3])) s_pulls.SetBinError(i + 1, float(l[4])) b_pulls.SetFillStyle(3005) b_pulls.SetFillColor(923) b_pulls.SetLineColor(923) b_pulls.SetLineWidth(1) b_pulls.SetMarkerStyle(20) b_pulls.SetMarkerSize(1.25) s_pulls.SetLineColor(602) s_pulls.SetMarkerColor(602) s_pulls.SetMarkerStyle(24) #24 s_pulls.SetLineWidth(1) b_pulls.GetYaxis().SetRangeUser(-2.5, 2.5) # Graphs h_pulls = TH2F("pulls", "", 6, -3., 3., nbins, 0, nbins) B_pulls = TGraphAsymmErrors(nbins) S_pulls = TGraphAsymmErrors(nbins) boxes = [] canvas = TCanvas("canvas", "Pulls", 600, 150 + nbins * 10) #nbins*20) canvas.cd() canvas.SetGrid(0, 1) canvas.GetPad(0).SetTopMargin(0.01) canvas.GetPad(0).SetRightMargin(0.01) canvas.GetPad(0).SetBottomMargin(0.05) canvas.GetPad(0).SetLeftMargin(0.25) #(0.25)#(0.065) canvas.GetPad(0).SetTicks(1, 1) for i, s in enumerate(content): l = s.split() if "1034h" in l[0]: l[0] = "CMS_PDF_13TeV" h_pulls.GetYaxis().SetBinLabel(i + 1, l[0].replace('CMS2016_', '')) #C #y1 = gStyle.GetPadBottomMargin() #y2 = 1. - gStyle.GetPadTopMargin() #h = (y2 - y1) / float(nbins) #y1 = y1 + float(i) * h #y2 = y1 + h #box = TPaveText(0, y1, 1, y2, 'NDC') #box.SetFillColor(0) #box.SetTextSize(0.02) #box.SetBorderSize(0) #box.SetTextAlign(12) #box.SetMargin(0.005) #if i % 2 == 0: # box.SetFillColor(18) #box.Draw() #boxes.append(box) B_pulls.SetPoint(i + 1, float(l[1]), float(i + 1) - 0.3) #C B_pulls.SetPointError(i + 1, float(l[2]), float(l[2]), 0., 0.) #C for i, s in enumerate(content): l = s.split() S_pulls.SetPoint(i + 1, float(l[3]), float(i + 1) - 0.7) #C S_pulls.SetPointError(i + 1, float(l[4]), float(l[4]), 0., 0.) #C h_pulls.GetXaxis().SetTitle("(#hat{#theta} - #theta_{0}) / #Delta#theta") h_pulls.GetXaxis().SetLabelOffset(-0.01) h_pulls.GetXaxis().SetTitleOffset(.6) h_pulls.GetYaxis().SetNdivisions(nbins, 0, 0) B_pulls.SetFillColor(1) B_pulls.SetLineColor(1) B_pulls.SetLineStyle(1) B_pulls.SetLineWidth(2) B_pulls.SetMarkerColor(1) B_pulls.SetMarkerStyle(20) B_pulls.SetMarkerSize(1) #(0.75) S_pulls.SetFillColor(629) S_pulls.SetLineColor(629) S_pulls.SetMarkerColor(629) S_pulls.SetLineWidth(2) S_pulls.SetMarkerStyle(20) S_pulls.SetMarkerSize(1) box1 = TBox(-1., 0., 1., nbins) box1.SetFillStyle(3001) #box1.SetFillStyle(0) box1.SetFillColor(417) box1.SetLineWidth(2) box1.SetLineStyle(2) box1.SetLineColor(417) box2 = TBox(-2., 0., 2., nbins) box2.SetFillStyle(3001) #box2.SetFillStyle(0) box2.SetFillColor(800) box2.SetLineWidth(2) box2.SetLineStyle(2) box2.SetLineColor(800) leg = TLegend(0.1, -0.05, 0.7, 0.08) leg.SetBorderSize(0) leg.SetFillStyle(0) leg.SetFillColor(0) leg.SetNColumns(2) leg.AddEntry(B_pulls, "B-only fit", "lp") leg.AddEntry(S_pulls, "S+B fit", "lp") if text: leg.AddEntry(0, text, "") h_pulls.Draw("") box2.Draw() box1.Draw() B_pulls.Draw("P6SAME") S_pulls.Draw("P6SAME") leg.Draw() # drawCMS(35867, "Preliminary") # drawAnalysis("VH") # drawRegion(outName) canvas.Print(outName + ".png") canvas.Print(outName + ".pdf") if not gROOT.IsBatch(): raw_input("Press Enter to continue...")