def __init__(self, models, bcids, values, fill=4954, workinprogress=False): """Initialize a summary plot of values per model and bcid.""" nbcid, nmodels = len(bcids), len(models) order = sorted(range(nbcid), key=lambda i: bcids[i]) mini, maxi = 1.0e99, -1.0e99 multi = TMultiGraph('summary', '') for i, mod in enumerate(models): xval = array( 'd', [c + 0.09 * (i - 0.5 * nmodels) for c in range(nbcid)]) xerr = array('d', [0.0] * nbcid) yval = array('d', [values[i][j][0] for j in order]) yerr = array('d', [values[i][j][1] for j in order]) #[0.0]*nbcid) mini = min(mini, min([v - e for v, e in zip(yval, yerr)])) maxi = max(maxi, max([v + e for v, e in zip(yval, yerr)])) graph = TGraphErrors(nbcid, xval, yval, xerr, yerr) graph.SetName('summary_{0}'.format(mod)) multi.Add(graph) self._multi = multi mini, maxi = mini - 0.08 * (maxi - mini), maxi + 0.25 * (maxi - mini) hist = TH2F('axishist', '', nbcid, -0.5, nbcid - 0.5, 100, mini, maxi) for i, j in enumerate(order): hist.GetXaxis().SetBinLabel(i + 1, str(bcids[j])) SingleGraphBase.__init__(self, hist, 'summary', fill, workinprogress) for gr in multi.GetListOfGraphs(): self.add(gr, draw=False) self._xtitle = 'bcid' self._drawoption = 'AXIS' self.markers = [markers(i) for i in range(nmodels)] self.colors = [colors(i) for i in range(nmodels)] self.xrange(-0.5, nbcid - 0.5) self.yrange(mini, maxi)
def draw_residuals_vs_chi2(self, show=True): mg = TMultiGraph('mgtr', 'Tracking Resolution') leg = Draw.make_legend(y2=.41, nentries=4) for roc, mode in zip([1, 1, 2, 2], ['x', 'y', 'x', 'y']): g = self.draw_residual_vs_chi2(roc, mode, show=False) format_histo(g, color=self.Draw.get_color(4)) mg.Add(g, 'pl') leg.AddEntry(g, 'ROC {} in {}'.format(roc, mode.title()), 'pl') y_range = [ 0, max(g.GetY()[i] for g in mg.GetListOfGraphs() for i in range(g.GetN())) * 1.1 ] format_histo(mg, x_tit='#chi^{2} [quantile]', y_tit='Residual Standard Deviation [#mum]', y_off=1.5, y_range=y_range, draw_first=True) self.Draw(mg, 'EventOffsets', show, draw_opt='ap', leg=leg, lm=.13)
def Draw_2D_Comp(rootfile_name, var_x, var_y, min, max, WP_list, leg, isTgraph=False): gStyle.SetErrorX(0.5) ## Creating a multigraph for the canvas if we are looking at TGraphs if isTgraph: stack = TMultiGraph() args = "AP" ## Creating a stack for the canvas if we are looking at TPofiles else: stack = THStack("stack", var_x.name + var_y.name) args = "nostack " stack.SetMinimum(min) stack.SetMaximum(max) for wp in WP_list: ## Generating the graph name graph_name = "{}_vs_{}_{}".format(var_x.name, var_y.name, wp.name) if isTgraph: graph_name += "_res" ## Loading the graph using its name and file location graph = GetGraphFromFile(rootfile_name, graph_name) if graph == -1: continue ## Setting the colors specific to the working point graph.SetLineColor(wp.colour) graph.SetMarkerColor(wp.colour) graph.SetMarkerStyle(wp.marker) ## Adding the legend entry leg.AddEntry(graph, wp.name, "p") ## Adding the object to the stack stack.Add(graph) del graph ## Checking to see if any graphs were found for this variable nhists = stack.GetListOfGraphs().GetSize( ) if isTgraph else stack.GetNhists() if nhists == 0: print("\n\n\nNo graphs found for working point {}\n\n\n".format( wp.name)) return -1 ## Drawing the stack on the currrent canvas stack.Draw(args) leg.Draw() ## Setting axis labels stack.GetXaxis().SetTitle(var_x.x_label + " " + var_x.units) stack.GetYaxis().SetTitle(var_y.x_label + " " + var_y.units) ## Moving axis tick marks stack.GetYaxis().SetMaxDigits(3) stack.GetXaxis().SetLabelOffset(0.017) return stack
rawfitresultList.At(i).getError()) tageffVsEtaGraph.SetLineColor(currentColor) linFunc.SetLineColor(currentColor) tageffVsEtaGraph.Fit(linFunc) graphHolder.Add(tageffVsEtaGraph) currentColor += 1 #tageffVsEtaGraph = TGraph(rawfitresultList.GetSize(),etaAvgValList,tageffValVList)#,etaAvgErrorList,tageffErrorList); #tageffVsEtaGraph. #ROOT.gSystem.ProcessEvents(); #img.FromPad(theCanvas); os.chdir("..") theCanvas = TCanvas() if (graphHolder.GetListOfGraphs().GetSize() == 1): graphHolder.SetTitle( "Tagging efficiency vs. Eta;Eta;Tagging Efficiency (omega)") else: graphHolder.SetTitle( "Tagging efficiency vs. Eta (multiple eta sets);Eta;Tagging Efficiency (omega)" ) graphHolder.Draw("AP") #raw_input("Press Enter to continue"); theCanvas.Print("tageffVsEtaGraph_%f.pdf" % time.time(), "pdf") print "SHIT"
class PlotGraphs: def __init__(self, data, xlow, xhigh, ylow, yhigh, xlabel = "", ylabel = "", xLegend = .45, yLegend = .60, legendWidth = 0.20, legendHeight = 0.45, fillStyle = 3395, drawOption = 'APL3', make_tfile = False): self.graph_index = {} self.ngraphs = 0 self.data = data self.drawOption = drawOption self.xlow=xlow self.xhigh=xhigh self.ylow=ylow self.yhigh=yhigh self.xlabel = xlabel self.ylabel = ylabel self.multigraph=TMultiGraph("MultiGraph", "") self.legend_type = {} if make_tfile: self.tfile = TFile('tgraphs.root', 'recreate') self.legend = TLegend(xLegend, yLegend, xLegend + legendWidth, yLegend + legendHeight) self.g_ = {} self.g2_ = {} self.g3_ = {} for cat in data.cat: if data.type[cat] == 'observed': #self.g_[cat] = TGraph(len(data.x[cat]), data.x[cat], data.y[cat]) self.g_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat], data.y[cat], data.exl[cat], data.exh[cat], data.eyl[cat], data.eyh[cat]) self.g_[cat].SetName(cat) if make_tfile: _gcopy = self.g_[cat].Clone() self.tfile.Append(_gcopy) if data.dofit[cat]: #self.g_[cat].Fit("pol3", "M", "", data.fit_min[cat], data.fit_max[cat]) f1 = TF1("f1", "[0]+[1]*(x-1000.0)/1000.0+[2]*(x-1000.0)*(x-1000.0)/1000000.0+[3]*(x-1000.0)*(x-1000.0)*(x-1000.0)/1000000000.0", data.fit_min[cat], data.fit_max[cat]) f2 = TF1("f2", "[0]+[1]*(x-1000.0)/1000.0+[2]*(x-1000.0)*(x-1000.0)/1000000.0", data.fit_min[cat], data.fit_max[cat]) f3 = TF1("f3", "[0]+[1]*(x-1000.0)/1000.0", data.fit_min[cat], data.fit_max[cat]) _fr = self.g_[cat].Fit("f2", "MEWS", "", data.fit_min[cat], data.fit_max[cat]) _fr.Print() elif data.type[cat] == 'expected': self.g_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat], data.y[cat], data.exl[cat], data.exh[cat], data.eyl[cat], data.eyh[cat]) self.g2_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat], data.y[cat], data.exl2[cat], data.exh2[cat], data.eyl2[cat], data.eyh2[cat]) self.g3_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat], data.y[cat], data.exl2[cat], data.exh2[cat], data.y[cat], data.exl2[cat]) self.g3_[cat].SetFillStyle(1002) #self.g3_[cat].SetFillStyle(3008) # 95% quantile self.g2_[cat].SetMarkerColor(data.fill2_color[cat]) self.g2_[cat].SetMarkerStyle(data.marker_style[cat]) self.g2_[cat].SetMarkerSize(data.marker_size[cat]) self.g2_[cat].SetLineColor(data.fill2_color[cat]) self.g2_[cat].SetLineStyle(data.line_style[cat]) self.g2_[cat].SetLineWidth(data.line_width[cat]) #self.g2_[cat].SetFillColor(data.marker_color[cat]+2) self.g2_[cat].SetFillColor(data.fill2_color[cat]) #self.g2_[cat].SetFillStyle(3008) #self.g2_[cat].SetFillStyle(3003) self.g2_[cat].SetFillStyle(data.fill2_style[cat]) self.g_[cat].SetMarkerColor(data.marker_color[cat]) self.g_[cat].SetMarkerStyle(data.marker_style[cat]) self.g_[cat].SetMarkerSize(data.marker_size[cat]) self.g_[cat].SetLineColor(data.line_color[cat]) self.g_[cat].SetLineStyle(data.line_style[cat]) self.g_[cat].SetLineWidth(data.line_width[cat]) self.g_[cat].SetFillColor(data.fill_color[cat]) if data.fill_style[cat] == None: self.g_[cat].SetFillStyle(fillStyle) else: self.g_[cat].SetFillStyle(data.fill_style[cat]) if data.type[cat] == 'observed': # only the main observed limit is a line, # everything else is a filled area if cat[0:3] == 'obs': _legend_type = 'lp' if 'PC' in drawOption: _draw_option = 'PC' else: _draw_option = 'PL' self.multigraph.Add(self.g_[cat], _draw_option) elif cat[0:3] == 'SSM': _legend_type = 'lp' _draw_option = '3' self.multigraph.Add(self.g_[cat], _draw_option) # print theory curve #self.g_[cat].Print() elif cat[0:3] == 'Psi': _legend_type = 'lp' _draw_option = '3' self.multigraph.Add(self.g_[cat], _draw_option) elif cat[0:2] == 'RS': _legend_type = 'f' _draw_option = '3' self.multigraph.Add(self.g_[cat], _draw_option) else: _legend_type = 'f' self.multigraph.Add(self.g_[cat]) #self.multigraph.Add(self.g_[cat]) self.graph_index[cat] = self.ngraphs self.ngraphs += 1 #self.legend . AddEntry( self.g_[cat], data.tlegend[cat], _legend_type); self.legend_type[cat] = _legend_type elif data.type[cat] == 'expected': self.g3_[cat].SetFillColor(0) self.g3_[cat].SetMinimum(self.ylow) self.g3_[cat].SetMaximum(self.yhigh) self.g3_[cat].GetXaxis().SetLimits(self.xlow, self.xhigh) self.multigraph.Add(self.g3_[cat], 'C3') self.ngraphs += 1 # 95 expected band self.multigraph.Add(self.g2_[cat]) self.ngraphs += 1 self.multigraph.Add(self.g_[cat], 'C3L') self.graph_index[cat] = self.ngraphs self.ngraphs += 1 # median line gline = self.g_[cat].Clone() gline.SetLineWidth(3) gline.SetLineColor(ROOT.kBlue) gline.SetLineStyle(2) # print graph contents #gline.Print() #self.multigraph.Add(gline, 'LXC') self.multigraph.Add(gline, 'C3X') self.legend . AddEntry( gline, 'median expected', "l"); self.ngraphs += 1 #self.legend . AddEntry( self.g_[cat], data.tlegend[cat], "f"); self.legend . AddEntry( self.g_[cat], '68% expected', "f"); # 95% expected band legend self.legend . AddEntry( self.g2_[cat], '95% expected', "f"); keylist = data.legend_index.keys() # keys are indices keylist.sort() for key in keylist: self.legend . AddEntry( self.g_[data.legend_index[key]], data.tlegend[data.legend_index[key]], self.legend_type[data.legend_index[key]]); self.legend . SetShadowColor(0) self.legend . SetFillColor(0) self.legend . SetLineColor(0) if make_tfile: self.tfile.Write() self.tfile.Close() def draw(self, yLabelSize = 0.045): self.multigraph.SetMinimum(self.ylow) self.multigraph.SetMaximum(self.yhigh) self.multigraph . Draw(self.drawOption) self.multigraph.GetXaxis().SetNdivisions(405) self.multigraph.GetYaxis().SetNdivisions(405) self.multigraph.GetXaxis().SetLimits(self.xlow, self.xhigh) #self.multigraph.GetYaxis().SetTitle("") #self.multigraph.GetYaxis().SetLabelSize(yLabelSize) #self.multigraph.GetXaxis().SetLabelSize(yLabelSize) # axis labels #latex = TLatex() #latex.SetNDC() ##latex.SetTextSize(0.04) #latex.SetTextSize(yLabelSize) #latex.SetTextAlign(31) # align right #latex.DrawLatex(0.95,0.01, self.xlabel) #latex.SetTextAngle(90) #latex.DrawLatex(0.04,0.95, self.ylabel) XLabel(self.xlabel, 0.95, 0.03, text_size = 0.07) YLabel(self.ylabel, 0.04,0.9, text_size = 0.07) self.legend.SetFillStyle(0) self.legend.SetBorderSize(0) #self.legend.SetTextSize(0.04) self.legend.SetTextSize(yLabelSize) self.legend.SetTextFont(22) self.legend . Draw() return self.multigraph def draw_line(self, xline, ymin = -0.02, ymax = 0.20): if xline == None: return #print 'XXXX', xline _x = array('d') _y = array('d') _x.append(xline) _y.append(ymin) _x.append(float(xline)) _y.append(ymax) g_ = TGraph(len(_x), _x, _y) self.multigraph.Add(g_, 'L') def print_values(self, cat1, cat2): legend = 'PlotGraphs::print_values():' if cat1 in self.data.cat: graph1 = self.multigraph.GetListOfGraphs().At(self.graph_index[cat1]) else: return None if cat2 in self.data.cat: graph2 = self.multigraph.GetListOfGraphs().At(self.graph_index[cat2]) else: return None for x in range (750, 1150, 50): dmax = 0.0 drelmax = 0.0 v1 = graph1.Eval(x) v2 = graph2.Eval(x) d = math.fabs(v2-v1) drel = math.fabs((v2-v1)/v1) if d>dmax: dmax = d if drel>drelmax: drelmax = drel print legend, 'x =', x print legend, cat1, 'value =', v1 print legend, cat2, 'value =', v2 print legend, 'abs diff =', d print legend, 'abs relative diff =', drel print legend, 'max abs diff =', dmax print legend, 'max abs relative diff =', drelmax def find_intersection(self, cat1, cat2, xmin = 250, xmax = 2500, precision = 0.00001): legend = 'PlotGraphs::find_intersection():' if cat1 in self.data.cat: graph1 = self.multigraph.GetListOfGraphs().At(self.graph_index[cat1]) else: return None if cat2 in self.data.cat: graph2 = self.multigraph.GetListOfGraphs().At(self.graph_index[cat2]) #graph2.Print() else: return None _x = xmin print legend, graph1.Eval(_x) - graph2.Eval(_x) _d = graph1.Eval(_x) - graph2.Eval(_x) _step = xmax - xmin while abs(_d) > precision: _x += _step if _x > xmax or _x < xmin: return None _d2 = graph1.Eval(_x) - graph2.Eval(_x) _sign1 = _d > 0 _sign2 = _d2 > 0 if _sign1 != _sign2: _step = -0.5*_step _d = _d2 if abs(_d2) < precision: return _x
def plotDistributionComparisonPlot(cfg): multiGraph = TMultiGraph() multiGraph.SetName("triggerRateMultiGraph") tfiles = [] histograms = [] canvas = TCanvas("canvas", "canvas", 800, 800) '''Contains the legend''' legend = TLegend(0.3, 0.7, 0.90, 0.9) '''Maximum value container, used to scale histograms''' maximumY = float("-inf") pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.SetBottomMargin(0.05) # Upper and lower plot are joined #pad1.SetBottomMargin(0) # Upper and lower plot are joined pad1.SetGridx() # Vertical grid pad1.Draw() # Draw the upper pad: pad1 pad1.cd() # pad1 becomes the current pad for histogramFileNameAndTitle in cfg.plots: tfile = TFile(histogramFileNameAndTitle[0]) tfiles.append(tfile) histogram = tfile.Get(histogramFileNameAndTitle[1]) histograms.append(histogram) if histogram.ClassName() == "TH1F": histogram.SetStats(0) # No statistics on upper plot maximumY = histogram.GetMaximum( ) if histogram.GetMaximum() > maximumY else maximumY legend.AddEntry(histogram, histogramFileNameAndTitle[2], "l") # histograms[0] settings histograms[0].SetMarkerColor(4) histograms[0].SetLineColor(4) histograms[0].SetLineWidth(1) # Y axis histograms[0] plot settings histograms[0].GetYaxis().SetTitleSize(20) histograms[0].GetYaxis().SetTitleFont(43) histograms[0].GetYaxis().SetTitleOffset(1.55) #histograms[0].Scale(1./histograms[0].GetEntries()) if histograms[0].ClassName() == "TH1F": histograms[0].Draw( "SAME HIST") # Draw histograms[1] on top of histograms[0] else: histograms[0].Draw( "SAME APE") # Draw histograms[1] on top of histograms[0] #multiGraph.Add(histograms[0]) if getattr(cfg, "xRange", None) is not None: histograms[0].GetXaxis().SetRangeUser(cfg.xRange[0], cfg.xRange[1]) gPad.RedrawAxis() if getattr(cfg, "xAxisLabel", None) is not None: histograms[0].GetXaxis().SetTitle(cfg.xAxisLabel) gPad.RedrawAxis() if getattr(cfg, "yAxisLabel", None) is not None: histograms[0].GetYaxis().SetTitle(cfg.yAxisLabel) gPad.RedrawAxis() if getattr(cfg, "yRange", None) is not None: histograms[0].GetYaxis().SetRangeUser(cfg.yRange[0], cfg.yRange[1]) gPad.RedrawAxis() else: maximumY *= 1.1 histograms[0].GetYaxis().SetRangeUser(1e-6, maximumY) if getattr(cfg, "logY", False): canvas.SetLogy() # histograms[1] settings histograms[1].SetMarkerColor(2) histograms[1].SetLineColor(2) histograms[1].SetLineWidth(1) #histograms[1].Scale(1./histograms[1].GetEntries()) if histograms[1].ClassName() == "TH1F": histograms[1].Draw( "SAME HIST") # Draw histograms[1] on top of histograms[0] else: histograms[1].Draw( "SAME PE") # Draw histograms[1] on top of histograms[0] #multiGraph.Add(histograms[1]) #if multiGraph.GetListOfGraphs() != None: # multiGraph.Draw("SAME PE") # 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. #histograms[0].GetYaxis().SetLabelSize(0.) #axis = TGaxis( 0, 20, 0, maximumY, 20, maximumY, 510,"") #axis.SetLabelFont(43) # Absolute font size in pixel (precision 3) #axis.SetLabelSize(15) #axis.Draw() # Adding a small text with the chi-squared chiSquared = 0 if (histograms[0].ClassName() == "TGraph") or (histograms[0].ClassName() == "TGraphErrors"): numberOfBins = histograms[0].GetN() numberOfDegreesOfFreedom = numberOfBins else: numberOfBins = histograms[0].GetNbinsX() numberOfDegreesOfFreedom = numberOfBins for x in xrange( 1, numberOfBins + 1 ): # numberOfBins contains last bin, numberOfBins+1 contains the overflow (latter excluded), underflow also excluded if (histograms[0].ClassName() == "TGraph") or (histograms[0].ClassName() == "TGraphErrors"): binContent0 = histograms[0].GetY()[x - 1] else: binContent0 = histograms[0].GetBinContent(x) if (histograms[1].ClassName() == "TGraph") or (histograms[1].ClassName() == "TGraphErrors"): binContent1 = histograms[1].GetY()[x - 1] else: binContent1 = histograms[1].GetBinContent(x) bin0ErrorSquared = binContent0 bin1ErrorSquared = binContent1 #bin1ErrorSquared = 0 if (binContent0 == 0) and (binContent1 == 0): numberOfDegreesOfFreedom -= 1 #No data means one less degree of freedom else: binDifferenceSquared = (binContent0 - binContent1)**2 chiSquaredTerm = binDifferenceSquared / (bin0ErrorSquared + bin1ErrorSquared) chiSquared += chiSquaredTerm if chiSquaredTerm > chiSquaredWarningThreshold: if (histograms[0].ClassName() == "TGraph") or (histograms[0].ClassName() == "TGraphErrors"): print "Bin", x, "-", histograms[0].GetX()[ x - 1], "has a CS=", chiSquaredTerm else: print "Bin", x, "-", histograms[0].GetBinCenter( x), "has a CS=", chiSquaredTerm chiSquareLabel = TPaveText(0.7, 0.6, 0.9, 0.4) chiSquareLabel.AddText("#chi^{2}/ndf = " + str(chiSquared) + "/" + str(numberOfDegreesOfFreedom) + " = " + str(chiSquared / numberOfDegreesOfFreedom)) chiSquareLabel.Draw() print "FINAL CS IS", format( chiSquared, ".2f") + "/" + str(numberOfDegreesOfFreedom) + " = " + format( chiSquared / numberOfDegreesOfFreedom, ".2f") legend.SetHeader( "#chi^{2}/ndf = " + format(chiSquared, ".2f") + "/" + str(numberOfDegreesOfFreedom) + " = " + format(chiSquared / numberOfDegreesOfFreedom, ".2f"), "C") legend.Draw() # lower plot will be in pad canvas.cd() # Go back to the main canvas before defining pad2 pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3) pad2.SetTopMargin(0) pad2.SetBottomMargin(0.2) pad2.SetGridx() # vertical grid pad2.Draw() pad2.cd() # pad2 becomes the current pad pad2.SetGridy() # Define the ratio plot ratioPlot = TGraphErrors(histograms[0]) ratioPlot.SetName("ratioPlot") graph_histo0 = TGraphErrors(histograms[0]) graph_histo1 = TGraphErrors(histograms[1]) ratioPlot.SetLineColor(1) ratioPlot.SetMinimum(0.6) # Define Y .. ratioPlot.SetMaximum(1.5) # .. range #ratioPlot.Sumw2() #ratioPlot.SetStats(0) # No statistics on lower plot #Dividing point by point for index in xrange(0, ratioPlot.GetN()): if graph_histo1.GetY()[index] == 0: ratioPlot.GetY()[index] = 0 ratioPlot.GetEY()[index] = 0 else: ratioPlot.GetY()[index] /= graph_histo1.GetY()[index] ratioPlot.GetEY()[index] = sqrt( ((graph_histo1.GetY()[index])**2 * (graph_histo0.GetEY()[index])**2 + (graph_histo0.GetY()[index])**2 * (graph_histo1.GetEY()[index])**2) / (graph_histo1.GetY()[index])**4) ratioPlot.SetMarkerStyle(21) if getattr(cfg, "xRange", None) is not None: ratioPlot.GetXaxis().SetRangeUser(cfg.xRange[0], cfg.xRange[1]) gPad.RedrawAxis() if getattr(cfg, "yRangeRatio", None) is not None: ratioPlot.GetYaxis().SetRangeUser(cfg.yRangeRatio[0], cfg.yRangeRatio[1]) gPad.RedrawAxis() ratioPlot.Draw("APE") # Draw the ratio plot line0 = TLine(ratioPlot.GetXaxis().GetXmin(), 1, ratioPlot.GetXaxis().GetXmax(), 1) line0.SetLineColor(2) line0.SetLineWidth(2) line0.SetLineStyle(2) line0.Draw() # Ratio plot (ratioPlot) settings ratioPlot.SetTitle("") # Remove the ratio title # Y axis ratio plot settings ratioPlot.GetYaxis().SetTitle("Ratio #frac{blue}{red}") ratioPlot.GetYaxis().SetNdivisions(505) ratioPlot.GetYaxis().SetTitleSize(20) ratioPlot.GetYaxis().SetTitleFont(43) ratioPlot.GetYaxis().SetTitleOffset(1.55) ratioPlot.GetYaxis().SetLabelFont( 43) # Absolute font size in pixel (precision 3) ratioPlot.GetYaxis().SetLabelSize(15) # X axis ratio plot settings ratioPlot.GetXaxis().SetTitleSize(20) ratioPlot.GetXaxis().SetTitleFont(43) ratioPlot.GetXaxis().SetTitleOffset(4.) ratioPlot.GetXaxis().SetLabelFont( 43) # Absolute font size in pixel (precision 3) ratioPlot.GetXaxis().SetLabelSize(15) xRangeBinning = getattr(cfg, "simplifiedRatioPlotXRangeBinning", None) if xRangeBinning is not None: simplifiedRatioPlot = TGraphErrors(len(xRangeBinning) - 1) simplifiedRatioPlot.SetName("simplifiedRatioPlot") ratioPlotIndex = 0 for idx in xrange(0, simplifiedRatioPlot.GetN()): yAverage = 0. yMax = float("-inf") yMin = float("+inf") nPoints = 0. simplifiedRatioPlot.GetX()[idx] = (xRangeBinning[idx] + xRangeBinning[idx + 1]) / 2. simplifiedRatioPlot.GetEX()[idx] = (xRangeBinning[idx + 1] - xRangeBinning[idx]) / 2. while (ratioPlot.GetX()[ratioPlotIndex] < xRangeBinning[idx]): ratioPlotIndex += 1 while ((ratioPlotIndex < ratioPlot.GetN()) and (ratioPlot.GetX()[ratioPlotIndex] < xRangeBinning[idx + 1]) and (ratioPlot.GetX()[ratioPlotIndex] >= xRangeBinning[idx])): yAverage += ratioPlot.GetY()[ratioPlotIndex] if (yMax < ratioPlot.GetY()[ratioPlotIndex] + ratioPlot.GetEY()[ratioPlotIndex]): yMax = ratioPlot.GetY()[ratioPlotIndex] + ratioPlot.GetEY( )[ratioPlotIndex] if (yMin > ratioPlot.GetY()[ratioPlotIndex] - ratioPlot.GetEY()[ratioPlotIndex]): yMin = ratioPlot.GetY()[ratioPlotIndex] - ratioPlot.GetEY( )[ratioPlotIndex] nPoints += 1. ratioPlotIndex += 1 simplifiedRatioPlot.GetY()[idx] = yAverage / nPoints simplifiedRatioPlot.GetEY()[idx] = (yMax - yMin) / 2. saveFile = TFile(cfg.saveFileName, "RECREATE") saveFile.cd() canvas.Write() histograms[0].Write() histograms[1].Write() if multiGraph.GetListOfGraphs() != None: multiGraph.Write() ratioPlot.Write() if xRangeBinning is not None: simplifiedRatioPlot.Write() saveFile.Close() for tfile in tfiles: tfile.Close()
class PlotGraphs: def __init__(self, data, xlow, xhigh, ylow, yhigh, xlabel="", ylabel="", xLegend=.45, yLegend=.60, legendWidth=0.20, legendHeight=0.45, fillStyle=3395, drawOption='APL3', make_tfile=False): self.graph_index = {} self.ngraphs = 0 self.data = data self.drawOption = drawOption self.xlow = xlow self.xhigh = xhigh self.ylow = ylow self.yhigh = yhigh self.xlabel = xlabel self.ylabel = ylabel self.multigraph = TMultiGraph("MultiGraph", "") self.legend_type = {} if make_tfile: self.tfile = TFile('tgraphs.root', 'recreate') self.legend = TLegend(xLegend, yLegend, xLegend + legendWidth, yLegend + legendHeight) self.g_ = {} self.g2_ = {} self.g3_ = {} for cat in data.cat: if data.type[cat] == 'observed': #self.g_[cat] = TGraph(len(data.x[cat]), data.x[cat], data.y[cat]) self.g_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat], data.y[cat], data.exl[cat], data.exh[cat], data.eyl[cat], data.eyh[cat]) self.g_[cat].SetName(cat) if make_tfile: _gcopy = self.g_[cat].Clone() self.tfile.Append(_gcopy) if data.dofit[cat]: #self.g_[cat].Fit("pol3", "M", "", data.fit_min[cat], data.fit_max[cat]) f1 = TF1( "f1", "[0]+[1]*(x-1000.0)/1000.0+[2]*(x-1000.0)*(x-1000.0)/1000000.0+[3]*(x-1000.0)*(x-1000.0)*(x-1000.0)/1000000000.0", data.fit_min[cat], data.fit_max[cat]) f2 = TF1( "f2", "[0]+[1]*(x-1000.0)/1000.0+[2]*(x-1000.0)*(x-1000.0)/1000000.0", data.fit_min[cat], data.fit_max[cat]) f3 = TF1("f3", "[0]+[1]*(x-1000.0)/1000.0", data.fit_min[cat], data.fit_max[cat]) _fr = self.g_[cat].Fit("f2", "MEWS", "", data.fit_min[cat], data.fit_max[cat]) _fr.Print() elif data.type[cat] == 'expected': self.g_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat], data.y[cat], data.exl[cat], data.exh[cat], data.eyl[cat], data.eyh[cat]) self.g2_[cat] = TGraphAsymmErrors( len(data.x[cat]), data.x[cat], data.y[cat], data.exl2[cat], data.exh2[cat], data.eyl2[cat], data.eyh2[cat]) self.g3_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat], data.y[cat], data.exl2[cat], data.exh2[cat], data.y[cat], data.exl2[cat]) self.g3_[cat].SetFillStyle(1002) #self.g3_[cat].SetFillStyle(3008) # 95% quantile self.g2_[cat].SetMarkerColor(data.fill2_color[cat]) self.g2_[cat].SetMarkerStyle(data.marker_style[cat]) self.g2_[cat].SetMarkerSize(data.marker_size[cat]) self.g2_[cat].SetLineColor(data.fill2_color[cat]) self.g2_[cat].SetLineStyle(data.line_style[cat]) self.g2_[cat].SetLineWidth(data.line_width[cat]) #self.g2_[cat].SetFillColor(data.marker_color[cat]+2) self.g2_[cat].SetFillColor(data.fill2_color[cat]) #self.g2_[cat].SetFillStyle(3008) #self.g2_[cat].SetFillStyle(3003) self.g2_[cat].SetFillStyle(data.fill2_style[cat]) self.g_[cat].SetMarkerColor(data.marker_color[cat]) self.g_[cat].SetMarkerStyle(data.marker_style[cat]) self.g_[cat].SetMarkerSize(data.marker_size[cat]) self.g_[cat].SetLineColor(data.line_color[cat]) self.g_[cat].SetLineStyle(data.line_style[cat]) self.g_[cat].SetLineWidth(data.line_width[cat]) self.g_[cat].SetFillColor(data.fill_color[cat]) if data.fill_style[cat] == None: self.g_[cat].SetFillStyle(fillStyle) else: self.g_[cat].SetFillStyle(data.fill_style[cat]) if data.type[cat] == 'observed': # only the main observed limit is a line, # everything else is a filled area if cat[0:3] == 'obs': _legend_type = 'lp' if 'PC' in drawOption: _draw_option = 'PC' else: _draw_option = 'PL' self.multigraph.Add(self.g_[cat], _draw_option) elif cat[0:3] == 'SSM': _legend_type = 'lp' _draw_option = '3' self.multigraph.Add(self.g_[cat], _draw_option) # print theory curve #self.g_[cat].Print() elif cat[0:3] == 'Psi': _legend_type = 'lp' _draw_option = '3' self.multigraph.Add(self.g_[cat], _draw_option) elif cat[0:3] == 'Stu': _legend_type = 'lp' _draw_option = '3' self.multigraph.Add(self.g_[cat], _draw_option) elif cat[0:2] == 'RS': _legend_type = 'f' _draw_option = '3' self.multigraph.Add(self.g_[cat], _draw_option) else: _legend_type = 'f' self.multigraph.Add(self.g_[cat]) #self.multigraph.Add(self.g_[cat]) self.graph_index[cat] = self.ngraphs self.ngraphs += 1 #self.legend . AddEntry( self.g_[cat], data.tlegend[cat], _legend_type); self.legend_type[cat] = _legend_type elif data.type[cat] == 'expected': self.g3_[cat].SetFillColor(0) self.g3_[cat].SetMinimum(self.ylow) self.g3_[cat].SetMaximum(self.yhigh) self.g3_[cat].GetXaxis().SetLimits(self.xlow, self.xhigh) self.multigraph.Add(self.g3_[cat], 'C3') self.ngraphs += 1 # 95 expected band self.multigraph.Add(self.g2_[cat], 'C4L') self.ngraphs += 1 self.multigraph.Add(self.g_[cat], 'C4L') self.graph_index[cat] = self.ngraphs self.ngraphs += 1 # median line gline = self.g_[cat].Clone() gline.SetLineWidth(3) gline.SetLineColor(ROOT.kBlue) gline.SetLineStyle(2) # median expected marker gline.SetMarkerStyle(8) gline.SetMarkerSize(1) # print graph contents #gline.Print() #self.multigraph.Add(gline, 'LXC') self.multigraph.Add(gline, 'C3X') self.ngraphs += 1 # median expected legend #self.legend . AddEntry( gline, 'median expected', "l"); self.legend_type[cat] = "l" _g = self.g_[cat] self.g_[cat] = gline # 68% expected band legend #self.legend . AddEntry( self.g_[cat], '68% expected', "f"); self.legend_type[cat + '1sig'] = "f" self.g_[cat + '1sig'] = _g # 95% expected band legend #self.legend . AddEntry( self.g2_[cat], '95% expected', "f"); self.legend_type[cat + '2sig'] = "f" self.g_[cat + '2sig'] = self.g2_[cat] keylist = data.legend_index.keys() # keys are indices keylist.sort() for key in keylist: print key, data.legend_index[key] self.legend.AddEntry(self.g_[data.legend_index[key]], data.tlegend[data.legend_index[key]], self.legend_type[data.legend_index[key]]) self.legend.SetShadowColor(0) self.legend.SetFillColor(0) self.legend.SetLineColor(0) if make_tfile: self.tfile.Write() self.tfile.Close() def draw(self, yLabelSize=0.055): self.multigraph.SetMinimum(self.ylow) self.multigraph.SetMaximum(self.yhigh) self.multigraph.Draw(self.drawOption) self.multigraph.GetXaxis().SetNdivisions(405) self.multigraph.GetYaxis().SetNdivisions(405) self.multigraph.GetXaxis().SetLimits(self.xlow, self.xhigh) #self.multigraph.GetYaxis().SetTitle("") self.multigraph.GetYaxis().SetLabelSize(yLabelSize) self.multigraph.GetXaxis().SetLabelSize(yLabelSize) latex = TLatex() latex.SetNDC() #latex.SetTextSize(0.04) latex.SetTextSize(yLabelSize) latex.SetTextAlign(31) # align right latex.DrawLatex(0.95, 0.01, self.xlabel) latex.SetTextAngle(90) latex.DrawLatex(0.03, 0.9, self.ylabel) self.legend.SetFillStyle(0) self.legend.SetBorderSize(0) #self.legend.SetTextSize(0.04) #self.legend.SetTextSize(yLabelSize) self.legend.SetTextSize(yLabelSize * 0.7) self.legend.SetTextFont(42) self.legend.SetTextAlign(11) self.legend.Draw() return self.multigraph def draw_line(self, xline, ymin=-0.02, ymax=0.20): if xline == None: return #print 'XXXX', xline _x = array('d') _y = array('d') _x.append(xline) _y.append(ymin) _x.append(float(xline)) _y.append(ymax) g_ = TGraph(len(_x), _x, _y) self.multigraph.Add(g_, 'L') def print_values(self, cat1, cat2): legend = 'PlotGraphs::print_values():' if cat1 in self.data.cat: graph1 = self.multigraph.GetListOfGraphs().At( self.graph_index[cat1]) else: return None if cat2 in self.data.cat: graph2 = self.multigraph.GetListOfGraphs().At( self.graph_index[cat2]) else: return None for x in range(750, 1150, 50): dmax = 0.0 drelmax = 0.0 v1 = graph1.Eval(x) v2 = graph2.Eval(x) d = math.fabs(v2 - v1) drel = math.fabs((v2 - v1) / v1) if d > dmax: dmax = d if drel > drelmax: drelmax = drel print legend, 'x =', x print legend, cat1, 'value =', v1 print legend, cat2, 'value =', v2 print legend, 'abs diff =', d print legend, 'abs relative diff =', drel print legend, 'max abs diff =', dmax print legend, 'max abs relative diff =', drelmax def find_intersection(self, cat1, cat2, xmin=350, xmax=3500, precision=0.000000001): legend = 'PlotGraphs::find_intersection(%s,%s):' % (cat1, cat2) #always put "exp" or "obs" in cat1 if cat1 is "exp" or cat1 is "obs": if cat1 in self.data.cat: graph1 = self.multigraph.GetListOfGraphs().At( self.graph_index[cat1]) else: print "Failed to get ", cat1 return ["None"] else: print cat1, " is not obs/exp limit." return ["None"] if cat2 in self.data.cat: graph2 = self.multigraph.GetListOfGraphs().At( self.graph_index[cat2]) #graph2.Print() else: print "Failed to get ", cat2 return ["None"] _x = xmin print legend, graph1.Eval(_x) - graph2.Eval(_x) if graph1.Eval(_x) > graph2.Eval(_x): result = ["lowlimit"] else: result = [] _interval = 1 _sign1 = graph1.Eval(_x) > graph2.Eval(_x) while _x < xmax: _x += _interval _sign2 = graph1.Eval(_x) > graph2.Eval(_x) if _sign1 != _sign2: _d = 100000 _step = -0.5 * _interval _crosspt = _x while abs(_d) > precision: _crosspt += _step _d = graph1.Eval(_crosspt) - graph2.Eval(_crosspt) _sign2 = _d > 0 if _sign1 != _sign2: _step = -0.5 * abs(_step) else: _step = 0.5 * abs(_step) _sign1 = not (_sign1) result.append(_crosspt) if result: print "Allowed region:", _x = 0 while _x < len(result): if _x + 1 < len(result): print "[", result[_x], ",", result[_x + 1], "];", else: if _x + 1 == len(result): print "[", result[_x], ", inf ];" if _x + 2 == len(result): print _x += 2 else: print "[", xmin, "~", xmax, "] is excluded." del graph1 del graph2 return result