Exemple #1
0
def plot_histo_and_fit(hs, f):
    n = 0
    r = 0
    c2 = TCanvas("c2", "c2", 1000, 600)
    hs.Draw("nostack")
    hs.GetXaxis().SetTitle("mbb [GeV]")
    hs.GetYaxis().SetTitle("Number of events")
    while n < 7:
        h[n].SetXTitle("mbb [GeV]")
        h[n].SetYTitle("Number of events")
        f[n].SetLineColor(n + 1)
        f[n].Draw("SAME")
        n = n + 1
    legend = TLegend(0.13, 0.41, 0.25, 0.88)
    legend.AddEntry(None, "#bf{mean[GeV] / sigma[GeV] / ratio}", "")
    while r < 7:
        legend.AddEntry(h[r], h[r].GetName(), "f[r]")
        result[r] = (height[r], mean[r], rms[r])
        legend_text[r] = "#bf{%-.3f/%-.3f/%-.3f}" % (
            result[r][1], result[r][2], ratio(result[r][2], result[r][1]))
        legend.AddEntry(None, legend_text[r], "")
        r = r + 1
    legend.SetBorderSize(0)
    legend.SetTextFont(42)
    legend.SetTextSize(0.03)
    legend.SetTextColor(1)
    legend.Draw("SAME")
    t = TLatex()
    t.SetNDC()
    t.SetTextSize(14)
    t.SetTextFont(43)
    t.SetTextAlign(13)
    t.DrawLatex(0.73, 0.85, "#it{#bf{ATLAS} Simulation Internal}")
    t.Draw()
    c2.Print("plot_histo_and_fit.pdf")
Exemple #2
0
 def addLatex(self, x, y, text, textsize=0.3, textcolor=1):
     tl = TLatex(x, y, text)
     tl.SetTextSize(textsize)
     tl.SetTextColor(textcolor)
     tl.Draw("same")
     self.tls.append(tl)
     return tl
Exemple #3
0
def plot_histo(hs):
    l = 0
    c = TCanvas("c", "c", 1000, 600)
    hs.Draw("nostack")
    hs.GetXaxis().SetTitle("mbb [GeV]")
    hs.GetYaxis().SetTitle("Number of events")
    legend = TLegend(0.13, 0.41, 0.25, 0.88)
    legend.AddEntry(None, "#bf{mean[GeV] / sigma[GeV] / ratio}", "")
    while l < 7:
        legend.AddEntry(h[l], h[l].GetName(), "f[l]")
        result[l] = (height[l], mean[l], rms[l])
        legend_text[l] = "#bf{%-.3f/%-.3f/%-.3f}" % (
            result[l][1], result[l][2], ratio(result[l][2], result[l][1]))
        legend.AddEntry(None, legend_text[l], "")
        l = l + 1
    legend.SetBorderSize(0)
    legend.SetTextFont(42)
    legend.SetTextSize(0.03)
    legend.SetTextColor(1)
    legend.Draw("SAME")
    t = TLatex()
    t.SetNDC()
    t.SetTextSize(14)
    t.SetTextFont(43)
    t.SetTextAlign(13)
    t.DrawLatex(0.73, 0.85, "#it{#bf{ATLAS} Simulation Internal}")
    t.Draw()
    c.Print("plot_histo.pdf")
Exemple #4
0
def setUpPalette(histo2D, plot) :

    # Configure Palette for 2D Histos

    minX = 1.03*histo2D.GetXaxis().GetXmin();
    maxX = 1.03*histo2D.GetXaxis().GetXmax();
    minY = 1.03*histo2D.GetYaxis().GetXmin();
    maxY = 1.03*histo2D.GetYaxis().GetXmax();

    palette = histo2D.GetListOfFunctions().FindObject("palette")
    if palette:
        palette.__class__ = TPaletteAxis
        palette.SetX1NDC(0.945)
        palette.SetY1NDC(gPad.GetBottomMargin())
        palette.SetX2NDC(0.96)
        palette.SetY2NDC(1-gPad.GetTopMargin())
        palette.GetAxis().SetTickSize(.01)
        palette.GetAxis().SetTitle("")
        if plots[plot].zLog:
            palette.GetAxis().SetLabelOffset(-0.01)
            if histo2D.GetMaximum()/histo2D.GetMinimum() < 1e3 :
                palette.GetAxis().SetMoreLogLabels(True)
                palette.GetAxis().SetNoExponent(True)

    paletteTitle = TLatex(1.12*maxX, maxY, plots[plot].quotaName)
    paletteTitle.SetTextAngle(90.)
    paletteTitle.SetTextSize(0.05)
    paletteTitle.SetTextAlign(31)
    paletteTitle.Draw()

    histo2D.GetXaxis().SetTickLength(histo2D.GetXaxis().GetTickLength()/4.)
    histo2D.GetYaxis().SetTickLength(histo2D.GetYaxis().GetTickLength()/4.)
    histo2D.SetTitleOffset(0.5,'Y')
    histo2D.GetXaxis().SetNoExponent(True)
    histo2D.GetYaxis().SetNoExponent(True)
Exemple #5
0
def drawEtaValues():
    """Function to draw the eta.

    Function to draw the eta references on top of an already existing
    TCanvas. The lines and labels drawn are collected inside a list and
    the list is returned to the user to extend the live of the objects
    contained, otherwise no lines and labels will be drawn, since they
    will be garbage-collected as soon as this function returns.
    """

    # Add eta labels
    keep_alive = []
    etas = [0.2 * i for i in range(-17, 18)]

    etax = 2850.
    etay = 1240.
    lineL = 110.
    offT = 10.

    for ieta in etas:
        th = 2 * atan(exp(-ieta))
        talign = 21

        #IP
        lineh = TLine(-20., 0., 20., 0.)
        lineh.Draw()
        linev = TLine(0., -10., 0., 10.)
        linev.Draw()
        keep_alive.append(lineh)
        keep_alive.append(linev)

        x1 = 0
        y1 = 0
        if ieta > -1.6 and ieta < 1.6:
            x1 = etay / tan(th)
            y1 = etay
        elif ieta <= -1.6:
            x1 = -etax
            y1 = -etax * tan(th)
            talign = 11
        elif ieta >= 1.6:
            x1 = etax
            y1 = etax * tan(th)
            talign = 31
        x2 = x1 + lineL * cos(th)
        y2 = y1 + lineL * sin(th)
        xt = x2
        yt = y2 + offT

        line1 = TLine(x1, y1, x2, y2)
        line1.Draw()
        keep_alive.append(line1)

        text = "%3.1f" % ieta
        t1 = TLatex(xt, yt, '%s' % ('#eta = 0' if ieta == 0 else text))
        t1.SetTextSize(0.03)
        t1.SetTextAlign(talign)
        t1.Draw()
        keep_alive.append(t1)
    return keep_alive
    def DrawResolutionSingleGaussianFit(self, list, cvs, mantisse, opt=""):
        FileMantisse = mantisse.split('/')[0]
        for h in list:
            h.SetFillColor(38)
            h.SetMarkerStyle(8)
            sgngaus = TF1("sgngaus", "gaus",
                          h.GetMean() - 2 * h.GetRMS(),
                          h.GetMean() + 2 * h.GetRMS())
            h.Fit(sgngaus, "", "", sgngaus.GetXmin(), sgngaus.GetXmax())
            comment = TLatex(
                .6, .6,
                "#sigma = " + str("%.3f" % sgngaus.GetParameter(2)) + " mm")
            comment.SetTextColor(kRed)
            comment.SetNDC(1)

            RangeSupEdge = 1
            if (self.LogScale): RangeSupEdge = 2
            for i in range(RangeSupEdge):
                if i == 1:
                    cvs.SetLogy()
                    ext = "_LOG" + self.OutFileType
                else:
                    cvs.SetLogy(0)
                    ext = self.OutFileType
                h.Draw("bar2")
                sgngaus.Draw("SAME")
                comment.Draw()
                cvs.SaveAs(mantisse + "/" + FileMantisse + "_" + h.GetName() +
                           "SingleGaussFit" + ext)
def make_ratio(nom, up, down, channel):
    ratio1 = up.Clone("ratio")
    #ratio1.Sumw2()
    ratio1.SetStats(0)
    ratio1.Add(nom, -1)
    ratio1.Divide(nom)
    ratio1.Scale(100)
    ratio1.SetTitle("")
    y = ratio1.GetYaxis()
    y.SetTitle("#frac{Syst-Nom.}{Nom.} [%]")
    y.SetNdivisions(505)
    y.SetTitleOffset(2.3)
    y.SetTitleSize(10)
    x = ratio1.GetXaxis()
    x.SetTitle("event level descriminator")
    x.SetTitleOffset(6.2)
    ratio1.SetLineColor(632)
    ratio1.SetFillColor(632)
    ratio1.SetMarkerColor(632)
    ratio1.SetMarkerStyle(0)
    ratio2 = down.Clone("ratio")
    #ratio2.Sumw2()
    ratio2.Add(nom, -1)
    ratio2.Divide(nom)
    ratio2.Scale(100)
    ratio2.SetLineColor(857)
    ratio2.SetFillColor(857)
    ratio2.SetMarkerColor(857)
    ratio2.SetMarkerStyle(0)
    line = TF1("fa1", "0", -1000, 1000)
    line.SetLineColor(1)
    ymax = abs(ratio1.GetMaximum())
    ymin = abs(ratio2.GetMaximum())
    Range = [ymax, ymin]
    maxv = max(Range)
    if maxv < 0.8:
        offset = 0.2
    else:
        offset = 0.8
    ratio1.SetMinimum(-maxv - offset)
    ratio1.SetMaximum(maxv + offset)
    ratio2.SetMinimum(-maxv - offset)
    ratio2.SetMaximum(maxv + offset)

    ratio1.Draw("hist")
    ratio2.Draw("same hist")
    line.Draw("same")

    #axis1 = TGaxis(0,-maxv-offset,1,-maxv-offset,-maxv-offset,-maxv-offset,50510,"-");
    #axis1.SetName("axis1");

    channel_label = TLatex()
    channel_label.SetNDC()
    channel_label.SetTextAlign(12)
    channel_label.SetTextFont(63)
    channel_label.SetTextSizePixels(15)
    channel_label.DrawLatex(0.45, 0.89, channel)
    channel_label.Draw("same")

    return ratio1, ratio2, line, channel_label
Exemple #8
0
def plotGroomed( obs="grthrust", filenames=[ "sjm136_test.root" ], ecm="136", logy=1, canv=None ):
    thplotoptions= { "xmin": 0.0, "xmax": 0.5, "ymin": 0.005, "ymax": 50.0, "markerStyle": 20, "markerSize": 0.5, "title": "groomed Thrust", "xlabel": "1-T_{gr}", "ylabel": "1/\sigma d\sigma/d(1-T_{gr})", "logy":logy }
    cpplotoptions= { "xmin": 0.0, "xmax": 1.0, "ymin": 0.03, "ymax": 30.0, "markerStyle": 20, "markerSize": 0.5, "title": "groomed C-parameter", "xlabel": "C_{gr}", "ylabel": "1/\sigma d\sigma/d(C_{gr})", "logy":logy }
    plotopts= { "grthrust": thplotoptions, "grcpar": cpplotoptions }
    if canv == None:
        canv= TCanvas( "canv", obs+" "+ecm, 1200, 800 )
    icanv= 0
    for beta in [ "0.0", "1.0" ]:
        for zcut in [ "0.05", "0.10", "0.15" ]:
            icanv= icanv+1
            canv.cd( icanv )
            gPad.SetLeftMargin( 0.15 )
            gPad.SetRightMargin( 0.025 )
            key= obs + "_" + beta + "_" + zcut
            print key
            aogr= createCombineAnalysisObservables( filenames, key )
            aogr.plot( plotopts[obs] )
            tl= TLegend( 0.4, 0.8, 0.85, 0.85 )
            tl.SetTextSize( 0.05 )
            tl.SetBorderSize( 0 )
            tl.AddEntry( key, "OPAL "+ecm+" GeV", "ep" )
            tl.Draw( "same" )
            txt= TLatex( 0.6, 0.7, "#beta="+beta+ " z_{cut}="+zcut )
            txt.SetNDC( True )
            txt.SetTextSize( 0.035 )
            txt.Draw()            
    return
Exemple #9
0
def plot_histo_and_fit(h):
    c = TCanvas("c", "c", 600, 300)
    h.SetXTitle("mbb [GeV]")
    h.SetYTitle("Number of events")
    h.Fit("bukin", "RQ", "HIST", xmin, xmax)
    f = h.GetFunction("bukin")
    result = (f.GetParameter(0), f.GetParameter(1), f.GetParameter(2),
              f.GetParameter(3), f.GetParameter(4), f.GetParameter(5))
    f.SetLineColor(color)
    f.Draw("same")
    # https://root.cern.ch/doc/master/classTLegend.html
    legend = TLegend(0.15, 0.60, 0.50, 0.80)
    legend.AddEntry(None, "#bf{mean[GeV] / sigma[GeV] / ratio}", "")
    legend.AddEntry(h, h.GetName(), "f")
    result = (height, mean, rms)
    legend_text = "#bf{%-.3f/%-.3f/%-.3f}" % (result[1], result[2],
                                              ratio(result[2], result[1]))
    legend.AddEntry(None, legend_text, "")
    legend.SetBorderSize(0)
    legend.SetTextFont(42)
    legend.SetTextSize(0.03)
    legend.SetTextColor(color)
    legend.Draw("SAME")
    # https://root.cern.ch/doc/master/classTLatex.html#L3
    t = TLatex()
    t.SetNDC()
    t.SetTextSize(10)
    t.SetTextFont(43)
    t.SetTextAlign(13)
    t.DrawLatex(0.15, 0.40, "#it{#bf{ATLAS} Simulation Internal}")
    t.Draw("same")
    # save the canvas to file
    c.Print("plot_histo_and_fit.pdf")
def PtRangeText(x=0.55, y=0.8, ptrange=(-1, -1), scale=1):
    rangetext = TLatex(x, y,
                       "%s < Photon P_{T} < %s" % (ptrange[0], ptrange[1]))
    rangetext.SetNDC()
    rangetext.SetTextFont(42)
    rangetext.SetTextSize(0.05 * scale)
    rangetext.Draw()
    return rangetext
Exemple #11
0
def drawCSCLabel(title, x=0.17, y=0.35, font_size=0.):
    tex = TLatex(x, y,title)
    if font_size > 0.:
      tex.SetTextSize(font_size)
      tex.SetTextSize(0.05)
      tex.SetNDC()
      tex.Draw()
      return tex
Exemple #12
0
def drawPuLabel(pu, x=0.17, y=0.35, font_size=0.):
    tex = TLatex(x, y,"<PU> = %d"%(pu))
    if font_size > 0.:
      tex.SetTextSize(font_size)
      tex.SetTextSize(0.05)
      tex.SetNDC()
      tex.Draw()
      return tex
Exemple #13
0
def drawEtaLabel(minEta, maxEta, x=0.17, y=0.35, font_size=0.):
    tex = TLatex(x, y,"%.2f < |#eta| < %.2f"%(minEta,maxEta))
    if font_size > 0.:
      tex.SetTextSize(font_size)
      tex.SetTextSize(0.05)
      tex.SetNDC()
      tex.Draw()
      return tex
Exemple #14
0
def plot(h, option, histoName):

    entries = h.GetEntries()
    height = h.GetMaximum()
    mean = h.GetMean()
    rms = h.GetRMS()
    color = h.GetLineColor()
    xmin = mean - 3 * rms
    xmax = mean + 3 * rms
    #Getting Bukin Function
    f = setBukin(mean=mean, rms=rms, height=height, xmin=xmin, xmax=xmax)

    c = TCanvas("c", "c", 600, 300)
    h.SetXTitle("mbb [GeV]")
    h.SetYTitle("Number of events")
    ########### start code specific to the histo and/or fit choice ##################
    if option == "histo":
        h.Draw("HIST")
    elif option == "histo+fit":
        h.Fit("bukin", "RQ", "HIST", xmin, xmax)
        f = h.GetFunction("bukin")
        result = (f.GetParameter(0), f.GetParameter(1), f.GetParameter(2),
                  f.GetParameter(3), f.GetParameter(4), f.GetParameter(5))
        f.SetLineColor(color)
        f.Draw("same")
    elif option == "fit":
        h.Fit("bukin", "RQ", "RO", xmin, xmax)
        f = h.GetFunction("bukin")
        result = (f.GetParameter(0), f.GetParameter(1), f.GetParameter(2),
                  f.GetParameter(3), f.GetParameter(4), f.GetParameter(5))
        f.SetLineColor(color)
    else:
        print "option", option, "not known"
        assert (False)
    ########## end   code specific to the histo and/or fit choice ##################
    # https://root.cern.ch/doc/master/classTLegend.html
    legend = TLegend(0.15, 0.60, 0.50, 0.80)
    legend.AddEntry(None, "#bf{mean[GeV] / sigma[GeV] / ratio}", "")
    legend.AddEntry(h, h.GetName(), "f")
    result = (height, mean, rms)
    legend_text = "#bf{%-.3f/%-.3f/%-.3f}" % (result[1], result[2],
                                              ratio(result[2], result[1]))
    legend.AddEntry(None, legend_text, "")
    legend.SetBorderSize(0)
    legend.SetTextFont(42)
    legend.SetTextSize(0.03)
    legend.SetTextColor(color)
    legend.Draw("SAME")
    # https://root.cern.ch/doc/master/classTLatex.html#L3
    t = TLatex()
    t.SetNDC()
    t.SetTextSize(10)
    t.SetTextFont(43)
    t.SetTextAlign(13)
    t.DrawLatex(0.15, 0.40, "#it{#bf{ATLAS} Simulation Internal}")
    t.Draw("same")
    # save the canvas to file
    c.Print(histoName + "_" + option + ".pdf")
    def DrawResolutionDoubleGaussianFit(self, list, cvs, mantisse, opt=""):
        FileMantisse = mantisse.split('/')[0]
        for h in list:
            h.SetFillColor(38)
            #h.Draw("bar2")
            doublgaus = TF1("doublgaus", "gaus(0)+gaus(3)",
                            h.GetXaxis().GetXmin(),
                            h.GetXaxis().GetXmax())
            sgngaus = TF1("sgngaus", "gaus", doublgaus.GetXmin(),
                          doublgaus.GetXmax())
            bckgaus = TF1("bckgaus", "gaus", doublgaus.GetXmin(),
                          doublgaus.GetXmax())
            h.Fit(sgngaus, "", "", sgngaus.GetXmin(), sgngaus.GetXmax())
            doublgaus.SetParameters(sgngaus.GetParameter(0),
                                    sgngaus.GetParameter(1),
                                    sgngaus.GetParameter(2),
                                    sgngaus.GetParameter(0) / 100.,
                                    sgngaus.GetParameter(1),
                                    sgngaus.GetParameter(2) * 2)
            doublgaus.SetParLimits(
                4, (doublgaus.GetXmin() -
                    (doublgaus.GetXmax() - doublgaus.GetXmin()) / 2),
                (doublgaus.GetXmin() +
                 (doublgaus.GetXmax() - doublgaus.GetXmin()) / 2))
            h.Fit(doublgaus, "", "", doublgaus.GetXmin(), doublgaus.GetXmax())
            sgngaus.SetParameters(doublgaus.GetParameter(0),
                                  doublgaus.GetParameter(1),
                                  doublgaus.GetParameter(2))
            bckgaus.SetParameters(doublgaus.GetParameter(3),
                                  doublgaus.GetParameter(4),
                                  doublgaus.GetParameter(5))
            bckgaus.SetLineStyle(7)
            bckgaus.SetLineColor(1)

            sgngaus.SetLineStyle(7)
            sgngaus.SetLineColor(4)

            comment = TLatex(
                .6, .6,
                "#sigma = " + str("%.3f" % doublgaus.GetParameter(2)) + " mm")
            comment.SetTextColor(kBlue)
            comment.SetNDC(1)

            RangeSupEdge = 1
            if (self.LogScale): RangeSupEdge = 2
            for i in range(RangeSupEdge):
                if i == 1:
                    cvs.SetLogy()
                    ext = "_LOG" + self.OutFileType
                else:
                    cvs.SetLogy(0)
                    ext = self.OutFileType
                h.Draw("bar2")
                bckgaus.Draw("SAME")
                sgngaus.Draw("SAME")
                comment.Draw()
                cvs.SaveAs(mantisse + "/" + FileMantisse + "_" + h.GetName() +
                           "DoubleGaussFit" + ext)
Exemple #16
0
def drawText(x, y, t, col=1):
    text = TLatex()
    text.SetTextColor(col)
    text.SetTextFont(42)
    text.SetTextAlign(23)
    text.SetTextSize(0.04)
    text.DrawLatex(x, y, t)
    text.Draw()
    return text
Exemple #17
0
def GetTLatex(t, x, y, s = 0.04):
  t = TLatex(-20, 50, t);
  t.SetNDC();
  t.SetTextAlign(12);
  t.SetX(x);
  t.SetY(y);
  t.SetTextFont(42);
  t.SetTextSize(s);
  t.Draw()
  return t
def drawText(x, y, t, isNDC=False):
    text = TLatex()
    text.SetTextColor(1)
    text.SetTextFont(42)
    text.SetTextAlign(23)
    text.SetTextSize(0.04)
    if isNDC: text.DrawLatexNDC(x, y, t)
    else: text.DrawLatex(x, y, t)
    text.Draw()
    return text
def drawBox(x1, y1, x2, y2, t=""):
    box = TBox(x1, y1, x2, y2)
    box.SetFillColor(1)
    box.SetFillStyle(3004)
    box.Draw()
    if not t == "":
        text = TLatex()
        text.SetTextColor(1)
        text.SetTextFont(42)
        text.SetTextAlign(23)
        text.SetTextSize(0.04)
        text.DrawLatex((x1 + x2) / 2., y2 / 1.15, t)
        text.Draw()
    return box
Exemple #20
0
def plot_fit(h, xmin, xmax, height, mean, rms):
    k = 0
    m = 0
    s = 0
    c1 = TCanvas("c1", "c1", 1000, 600)
    while k < 7:
        function = TF1("bukin", Bukin(), xmin[k], xmax[k], 6)
        function.SetParName(0, "height")
        function.SetParName(1, "mean")
        function.SetParName(2, "width")
        function.SetParName(3, "asymmetry")
        function.SetParName(4, "size of lower tail")
        function.SetParName(5, "size of higher tail")
        function.SetParameter(0, height[k])
        function.SetParameter(1, mean[k])
        function.SetParameter(2, rms[k])
        h[k].Fit("bukin", "RQ", "RO", xmin[k], xmax[k])
        f[k] = h[k].GetFunction("bukin")
        k = k + 1
    while m < 7:
        h[m].SetXTitle("mbb [GeV]")
        h[m].SetYTitle("Number of events")
        f[m].SetLineColor(m + 1)
        f[m].Draw("SAME")
        m = m + 1
    legend = TLegend(0.13, 0.41, 0.25, 0.88)
    legend.AddEntry(None, "#bf{mean[GeV] / sigma[GeV] / ratio}", "")
    while s < 7:
        legend.AddEntry(h[s], h[s].GetName(), "f[s]")
        result[s] = (height[s], mean[s], rms[s])
        legend_text[s] = "#bf{%-.3f/%-.3f/%-.3f}" % (
            result[s][1], result[s][2], ratio(result[s][2], result[s][1]))
        legend.AddEntry(None, legend_text[s], "")
        s = s + 1
    legend.SetBorderSize(0)
    legend.SetTextFont(42)
    legend.SetTextSize(0.03)
    legend.SetTextColor(1)
    legend.Draw("SAME")
    t = TLatex()
    t.SetNDC()
    t.SetTextSize(14)
    t.SetTextFont(43)
    t.SetTextAlign(13)
    t.DrawLatex(0.73, 0.85, "#it{#bf{ATLAS} Simulation Internal}")
    t.Draw()
    c1.Print("plot_fit.pdf")
 def DrawADCGainProfile(self, list, cvs, mantisse, opt=""):
     FileMantisse = mantisse.split('/')[0]
     cvs.SetLogy(0)
     for h in list:
         hProf = h.ProfileX()
         h.Draw("colz")
         hProf.SetLineWidth(5)
         hProf.SetLineColor(7)
         hProf.Draw("SAME")
         linFit = TF1("linFit", "pol1", 0, 0.3)
         hProf.Fit(linFit, "", "SAME", 0, 0.3)
         comment = TLatex(
             0.5, .2, "Slope = " + str("%.0f" % linFit.GetParameter(1)) +
             " MeV^{-1}")
         comment.SetTextColor(kRed)
         comment.SetNDC(1)
         comment.Draw()
         cvs.SaveAs(mantisse + "/" + FileMantisse + "_" + h.GetName() +
                    self.OutFileType)
def draw(h, opt="", copy=False, labelize=True):
    hd = h
    if copy:
        print("Drawing", h, "as a copy")
        hd = h.DrawCopy(opt)
        if type(copy) == type(""):
            hd.SetName(hd.GetName() + copy)
        else:
            hd.SetName(hd.GetName() + "copy")
        hd.SetDirectory(0)
    else:
        h.Draw(opt)
    if labelize and "same" not in opt:
        latex = TLatex(0.2, 0.95, hd.GetName())
        latex.SetNDC()
        latex.Draw()
        latexdrawn.append(latex)
    gPad.Update()
    ldrawn.append(hd)
    return hd
Exemple #23
0
def Draw2Dsig(tag='exp', pname='limits', ms=275, ml=100, lim=[]):
    h = Get2Dhisto(pname + '.p', tag)
    c = TCanvas('c', 'c', 10, 10, 1200, 800)
    if lim != []:
        zmin, zmax = lim
        h.SetMaximum(zmax)
        h.SetMinimum(zmin)
    h.SetTitle('%s significance' % tag)
    g = TGraph(1)
    g.SetPoint(1, ms + 5, ml + 5)
    g.SetMarkerSize(1)
    g.SetMarkerStyle(20)
    gStyle.SetPalette(51)  #58)
    h.Draw('colz')
    g.Draw('psame')
    t = TLatex(0, 0, 'Injected signal %s_%s' % (str(ms), str(ml)))
    t.SetNDC()
    t.SetX(0.15)
    t.SetY(0.85)
    t.SetTextAlign(12)
    t.Draw()
    for f in ['png', 'pdf']:
        c.Print('%s.%s' % (pname.replace('limits', 'scan'), f))
Exemple #24
0
def AddText(txt_x=0.50, txt_y=0.50, txt="dummy", txt_size=0.045, txt_angle=0, Alignment="left", UseNormalizedSize=1, txt_color=1):
	txt_align=12

	if Alignment == "left":
		txt_align = 12
	if Alignment == "right":
		txt_align = 32
	if Alignment == "center":
		txt_align = 22

	t1 = TLatex(txt_x, txt_y, txt ) 
	
	if UseNormalizedSize: 
		t1.SetNDC(kTRUE)

	#canvas.cd()
	
	t1.SetTextSize(txt_size)
	t1.SetTextAlign(txt_align)
	t1.SetTextAngle(txt_angle)
	t1.SetTextColor(txt_color)
	t1.Draw()

	return
Exemple #25
0
c.SetLogy(1)

bkgStack.Draw()
j = 0
for iregion in region:
    bkgStack.GetXaxis().SetBinLabel(j + 1, iregion)
    j = j + 1
legend.Draw()

latex = TLatex(0.15, 0.85, 'CMS')
latex.SetTextSize(0.036)
latex.SetTextAlign(12)
latex.SetNDC(kTRUE)
latex.SetTextFont(61)
latex.Draw()

latex1 = TLatex(0.13, 0.82, 'Preliminary')
latex1.SetTextSize(0.036)
latex1.SetTextAlign(12)
latex1.SetNDC(kTRUE)
latex1.SetTextFont(61)
latex1.Draw()

latex2 = TLatex(0.65, 0.93, "35.8 fb^{-1} (13 TeV)")
latex2.SetTextSize(0.036)
latex2.SetTextAlign(12)
latex2.SetNDC(kTRUE)
#latex2.SetTextFont(61)
latex2.Draw()
Exemple #26
0
def savePlots(title,
              saveName,
              listFromats,
              plot,
              Histos,
              keyHisto,
              listLegend,
              options,
              ratios=None,
              legendName=""):
    #create canvas
    c = {}
    pads = {}
    if options.doRatio:
        c[keyHisto] = TCanvas(saveName, keyHisto + plot.title, 700,
                              700 + 24 * len(listFlavors))
        pads["hist"] = TPad("hist", saveName + plot.title, 0,
                            0.11 * len(listFlavors), 1.0, 1.0)
    else:
        c[keyHisto] = TCanvas(keyHisto, saveName + plot.title, 700, 700)
        pads["hist"] = TPad("hist", saveName + plot.title, 0, 0., 1.0, 1.0)
    pads["hist"].Draw()
    if ratios:
        for r in range(0, len(ratios)):
            pads["ratio_" + str(r)] = TPad("ratio_" + str(r),
                                           saveName + plot.title + str(r), 0,
                                           0.11 * r, 1.0, 0.11 * (r + 1))
            pads["ratio_" + str(r)].Draw()
    pads["hist"].cd()
    #canvas style
    if plot.logY: pads["hist"].SetLogy()
    if plot.grid: pads["hist"].SetGrid()
    #legend
    leg = TLegend(0.6, 0.4, 0.8, 0.6)
    leg.SetMargin(0.12)
    leg.SetTextSize(0.035)
    leg.SetFillColor(10)
    leg.SetBorderSize(0)
    #draw histos
    first = True
    option = drawOption
    optionSame = drawOption + "same"
    if plot.doPerformance:
        option = "AP"
        optionSame = "sameP"
    for i in range(0, len(Histos)):
        if Histos[i] is None: continue
        if first:
            if not plot.doPerformance:
                Histos[i].GetPainter().PaintStat(ROOT.gStyle.GetOptStat(), 0)
            Histos[i].SetTitle(title)
            Histos[i].Draw(option)
            first = False
        else:
            Histos[i].Draw(optionSame)
        #Fill legend
        if plot.legend and len(Histos) % len(listLegend) == 0:
            r = len(Histos) / len(listLegend)
            index = i - r * len(listLegend)
            while (index < 0):
                index += len(listLegend)
            legName = legendName.replace("KEY", listLegend[index])
            if i < len(listLegend):
                legName = legName.replace("isVAL", options.ValRel)
            else:
                legName = legName.replace("isVAL", options.RefRel)
            if drawOption == "HIST":
                leg.AddEntry(Histos[i], legName, "L")
            else:
                leg.AddEntry(Histos[i], legName, "P")
    #Draw legend
    if plot.legend and options.drawLegend: leg.Draw("same")
    tex = None
    if options.printBanner:
        print(type(options.printBanner))
        tex = TLatex(0.55, 0.75, options.Banner)
        tex.SetNDC()
        tex.SetTextSize(0.05)
        tex.Draw()
    #save canvas
    if ratios:
        for r in range(0, len(ratios)):
            pads["ratio_" + str(r)].cd()
            if ratios[r] is None: continue
            pads["ratio_" + str(r)].SetGrid()
            ratios[r].GetYaxis().SetTitle(listLegend[r] + "-jets")
            ratios[r].GetYaxis().SetTitleSize(0.15)
            ratios[r].GetYaxis().SetTitleOffset(0.2)
            ratios[r].GetYaxis().SetNdivisions(3, 3, 2)
            ratios[r].Draw("")
            unity.Draw("same")
    for format in listFromats:
        save = saveName + "." + format
        c[keyHisto].Print(save)
    return [c, leg, tex, pads]
def create2DPlots(detector, plot, plotnum, plotmat, dosingledetector=True):
    """Produce the requested plot for the specified detector.

       Function that will plot the requested 2D-@plot for the
       specified @detector. The specified detector could either be a
       real detector or a compound one. The list of available plots
       are the keys of plots dictionary imported from plot_utils.
    """

    #gStyle.Reset()
    #Better to use an underscore.
    plotmat = plotmat.replace(" ", "_")

    if plotmat != "":
        theDirname = ('Images/%s' % plotmat).replace(" ", "")
    else:
        theDirname = 'Images'

    if not checkFile_(theDirname):
        os.mkdir(theDirname)
    if not os.path.isdir(('Images/%s/ZPlusZoom' % plotmat).replace(" ", "")):
        os.mkdir(('Images/%s/ZPlusZoom' % plotmat).replace(" ", ""))
    if not os.path.isdir(('Images/%s/ZMinusZoom' % plotmat).replace(" ", "")):
        os.mkdir(('Images/%s/ZMinusZoom' % plotmat).replace(" ", ""))

    goodToGo, theDetectorFilename = paramsGood_(detector, plot)
    if not goodToGo:
        return

    theDetectorFile = TFile(theDetectorFilename)

    prof2d_X0_det_total = TProfile2D()
    prof2d_X0_det_total.Reset()

    # get TProfiles
    #prof2d_X0_det_total = theDetectorFile.Get('%s' % plots[plot].plotNumber)
    prof2d_X0_det_total = theDetectorFile.Get('%s' % plotnum)
    print "=================================================================="
    print plotnum

    # histos
    prof2d_X0_det_total.__class__ = TProfile2D
    hist_X0_total = prof2d_X0_det_total.ProjectionXY()

    # keep files live forever
    files = []
    if detector in COMPOUNDS.keys() and not dosingledetector:
        #When the loop was:
        #for subDetector in COMPOUNDS[detector][1:]:
        #and the detector was single it never went in the loop and read the single file
        #from above. I alter this to COMPOUNDS[detector] to do the multi material budget plot.
        #This won't effect the single detector due to the alter in the if above
        for subDetector in COMPOUNDS[detector]:
            # filenames of single components
            subDetectorFilename = "matbdg_%s.root" % subDetector

            # open file
            if not checkFile_(subDetectorFilename):
                print("Error, missing file %s" % subDetectorFilename)
                continue

            subDetectorFile = TFile(subDetectorFilename)
            files.append(subDetectorFile)
            print("*** Open file... %s" % subDetectorFilename)

            # subdetector profiles
            prof2d_X0_det_total = subDetectorFile.Get('%s' %
                                                      plots[plot].plotNumber)
            prof2d_X0_det_total.__class__ = TProfile2D

            # add to summary histogram
            hist_X0_total.Add(
                prof2d_X0_det_total.ProjectionXY(
                    "B_%s" % prof2d_X0_det_total.GetName()), +1.000)

    # # properties
    #gStyle.SetPalette(1)
    gStyle.SetStripDecimals(False)
    # #

    # Create "null" histo
    minX = 1.03 * prof2d_X0_det_total.GetXaxis().GetXmin()
    maxX = 1.03 * prof2d_X0_det_total.GetXaxis().GetXmax()
    minY = 1.03 * prof2d_X0_det_total.GetYaxis().GetXmin()
    maxY = 1.03 * prof2d_X0_det_total.GetYaxis().GetXmax()

    frame = TH2F("frame", "", 10, minX, maxX, 10, minY, maxY)
    frame.SetMinimum(0.1)
    frame.SetMaximum(10.)
    frame.GetXaxis().SetTickLength(frame.GetXaxis().GetTickLength() * 0.50)
    frame.GetYaxis().SetTickLength(frame.GetXaxis().GetTickLength() / 4.)

    # Ratio
    if plots[plot].iRebin:
        prof2d_X0_det_total.Rebin2D()

    # stack
    hist2dTitle = ('%s %s;%s;%s;%s' %
                   (plots[plot].quotaName, detector, plots[plot].abscissa,
                    plots[plot].ordinate, plots[plot].quotaName))

    if dosingledetector:
        hist2d_X0_total = prof2d_X0_det_total
    else:
        hist2d_X0_total = hist_X0_total
    hist2d_X0_total.SetTitle(hist2dTitle)
    frame.SetTitle(hist2dTitle)
    frame.SetTitleOffset(0.5, "Y")

    #If here you put different histomin,histomaxin plot_utils you won't see anything
    #for the material plots.
    if plots[plot].histoMin != -1.:
        hist2d_X0_total.SetMinimum(plots[plot].histoMin)
    if plots[plot].histoMax != -1.:
        hist2d_X0_total.SetMaximum(plots[plot].histoMax)

    #
    can2name = "MBCan_2D_%s_%s_%s" % (detector, plot, plotmat)
    can2 = TCanvas(can2name, can2name, 2480 + 248, 580 + 58 + 58)
    can2.SetTopMargin(0.1)
    can2.SetBottomMargin(0.1)
    can2.SetLeftMargin(0.04)
    can2.SetRightMargin(0.06)
    can2.SetFillColor(kWhite)
    gStyle.SetOptStat(0)
    gStyle.SetTitleFillColor(0)
    gStyle.SetTitleBorderSize(0)

    #hist2d_X0_total.SetMaximum(hist2d_X0_total.GetMaximum())
    # Color palette
    # gStyle.SetPalette()#1
    acustompalette()
    ex1 = TExec("ex1", "acustompalette();")
    ex1.Draw()

    #for i in range(100): MyPaletteArray.append(i+1)

    #gStyle.SetPalette(first_color_number);

    # Log?
    can2.SetLogz(plots[plot].zLog)

    # Draw in colors
    #frame.Draw()
    #hist2d_X0_total.Draw("COLZsame") #Dummy draw to create the palette object
    hist2d_X0_total.Draw("COLZ")  #Dummy draw to create the palette object

    # Store
    can2.Update()

    #Aesthetic
    palette = hist2d_X0_total.GetListOfFunctions().FindObject("palette")
    if palette:
        palette.__class__ = TPaletteAxis
        palette.SetX1NDC(0.945)
        palette.SetX2NDC(0.96)
        palette.SetY1NDC(0.1)
        palette.SetY2NDC(0.9)
        palette.GetAxis().SetTickSize(.01)
        palette.GetAxis().SetTitle("")
        if plots[plot].zLog:
            palette.GetAxis().SetLabelOffset(-0.01)
    paletteTitle = TLatex(1.12 * maxX, maxY, plots[plot].quotaName)
    paletteTitle.SetTextAngle(90.)
    paletteTitle.SetTextSize(0.05)
    paletteTitle.SetTextAlign(31)
    paletteTitle.Draw()
    hist2d_X0_total.GetYaxis().SetTickLength(
        hist2d_X0_total.GetXaxis().GetTickLength() / 4.)
    hist2d_X0_total.GetYaxis().SetTickLength(
        hist2d_X0_total.GetXaxis().GetTickLength() / 4.)
    hist2d_X0_total.SetTitleOffset(0.5, "Y")
    hist2d_X0_total.GetYaxis().SetTitleOffset(0.45)
    #hist2d_X0_total.GetXaxis().SetTitleOffset(1.15);
    #hist2d_X0_total.GetXaxis().SetNoExponent(True)
    #hist2d_X0_total.GetYaxis().SetNoExponent(True)

    #Add eta labels
    keep_alive = []
    if plots[plot].iDrawEta:
        keep_alive.extend(drawEtaValues())

    can2.Modified()
    hist2d_X0_total.SetContour(255)

    # Store
    can2.Update()
    can2.Modified()

    can2.SaveAs("%s/%s_%s%s.pdf" % (theDirname, detector, plot, plotmat))
    can2.SaveAs("%s/%s_%s%s.png" % (theDirname, detector, plot, plotmat))
    #can2.SaveAs( "%s/%s_%s%s.root" % (theDirname, detector, plot, plotmat))

    #Zoom in a little bit
    if plot == "x_vs_z_vs_Rsum" or plot == "l_vs_z_vs_Rsum" or plot == "x_vs_z_vs_Rsumcos" or plot == "l_vs_z_vs_Rsumcos" or plot == "x_vs_z_vs_Rloc" or plot == "l_vs_z_vs_Rloc" or plot == "x_vs_z_vs_Rloccos" or plot == "l_vs_z_vs_Rloccos":
        #Z+
        #hist2d_X0_total.GetXaxis().SetLimits( 3100., 5200.)
        if dosingledetector:
            hist2d_X0_total.GetXaxis().SetRangeUser(3100., 5400.)
        else:
            hist2d_X0_total.GetXaxis().SetRangeUser(0., 7000.)
        #Do not draw eta values in the zoom case
        keep_alive = []
        #hist2d_X0_total.Draw("COLZ")
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s/%s_%s%s_ZplusZoom.pdf" %
                    (theDirname, "ZPlusZoom", detector, plot, plotmat))
        can2.SaveAs("%s/%s/%s_%s%s_ZplusZoom.png" %
                    (theDirname, "ZPlusZoom", detector, plot, plotmat))
        #Z-
        #hist2d_X0_total.GetXaxis().SetLimits( 3100., 5200.)
        if dosingledetector:
            hist2d_X0_total.GetXaxis().SetRangeUser(-5400., -3100.)
        else:
            hist2d_X0_total.GetXaxis().SetRangeUser(0., -7000.)
        #Do not draw eta values in the zoom case
        keep_alive = []
        #hist2d_X0_total.Draw("COLZ")
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s/%s_%s%s_ZminusZoom.pdf" %
                    (theDirname, "ZMinusZoom", detector, plot, plotmat))
        can2.SaveAs("%s/%s/%s_%s%s_ZminusZoom.png" %
                    (theDirname, "ZMinusZoom", detector, plot, plotmat))

    gStyle.SetStripDecimals(True)
Exemple #28
0
line36 = TLine(0.975, 0, 0.975, 1.925)
line37 = TLine(0.975, 1.925, -0.025, 1.925)
line38 = TLine(-0.025, 1.925, -0.0125, 0)

lineVector = [
    line1, line2, line3, line4, line5, line6, line7, line8, line9, line10,
    line11, line12, line13, line14, line15, line16, line17, line18, line19,
    line20, line21, line22, line23, line24, line25, line26, line27, line28,
    line29, line30, line31, line32, line33, line34, line35, line36, line37,
    line38
]
for line in lineVector:
    line.SetLineColor(ROOT.kBlack)
    line.SetLineWidth(3)
    line.Draw()

leg = TLegend(.54, .75, .58, .79)
leg.SetFillStyle(0)
leg.SetLineWidth(4)
leg.Draw()

text = TLatex(.6, .75, "NA49 Coverage")
text.SetTextColor(ROOT.kBlack)
text.SetNDC()
text.SetTextSize(1.4 / 30.)
text.SetTextAlign(11)
#text.DrawLatex(.48, .55, "#Square");
text.Draw()

raw_input("Please press enter to exit.")
Exemple #29
0
        pad2.SetGrid()
        pad1.Draw()
        pad2.Draw()

        pad1.cd()
        pad1.SetLogy()
        hs.SetMinimum(0.1)
        hs.Draw("HIST")
        #        hs.GetXaxis().SetTitle(TITLE[var])
        hs.GetYaxis().SetTitle("Events")
        hs.GetYaxis().SetTitleOffset(0.8)
        hs.GetYaxis().SetTitleSize(0.05)
        data_hist.Draw("same" "LPE")
        sig_hist.Draw("same" "LPE")
        leg.Draw()
        tex1.Draw()
        tex2.Draw()
        tex3.Draw()

        ROOT.gStyle.SetOptStat(0)
        ROOT.gStyle.SetOptTitle(0)
        pad2.cd()
        ratio_hist.SetMarkerColor(4)
        ratio_hist.SetMarkerSize(1)
        ratio_hist.SetMarkerStyle(ROOT.kFullCircle)
        ratio_hist.Draw()
        ratio_hist.GetXaxis().SetTitle(TITLE[var])
        ratio_hist.GetXaxis().SetTitleOffset(0.9)
        ratio_hist.GetXaxis().SetTitleSize(0.15)
        ratio_hist.GetXaxis().SetLabelSize(0.1)
        ratio_hist.GetYaxis().SetTitle("Data/MC")
            h3.GetYaxis().SetTitleFont(22)
            h4.GetYaxis().SetTitleFont(22)
            h3.GetXaxis().SetLabelFont(22)
            h4.GetXaxis().SetLabelFont(22)
            h3.GetYaxis().SetLabelFont(22)
            h4.GetYaxis().SetLabelFont(22)

            h1.Draw("hist")
            h2.Draw("histsame")

            #h3.Draw("hist")
            #h4.Draw("histsame")
            #h5.Draw("histsame")
            #h6.Draw("histsame")

            t1.Draw("same")
            t2.Draw("same")
            t3.Draw("same")
            t5.Draw("same")
            t6.Draw("same")
            t7.Draw("same")
            t8.Draw("same")

            leg.Draw()

            c.Print(str(energy[E])+"TeV/h_"+str(energy[E])+"TeV_Particles_Rank_"+str(list_PT_T[j])+"_"+str(i)+".pdf")