Example #1
0
def TextAuto(gPad, text, size=0.05, font=42, align=13, line=1):
    x = 0
    y = 0

    t = gPad.GetTopMargin()
    b = gPad.GetBottomMargin()
    l = gPad.GetLeftMargin()
    r = gPad.GetRightMargin()
    if align == 13:
        x = l + 0.02
        y = 1 - t - 0.02
    if align == 31:
        x = 1 - r
        y = 1 - t + 0.01
    if align == 11:
        x = l
        y = 1 - t + 0.01

    latex = ROOT.TLatex()
    latex.SetNDC()
    latex.SetTextSize(size)
    latex.SetTextAlign(align)
    latex.SetTextFont(font)
    latex.DrawLatex(x, y, text)
    return latex
Example #2
0
def Frame(gPad, width=2):
    gPad.Update()
    gPad.RedrawAxis()
    l = ROOT.TLine()
    l.SetLineWidth(width)
    lm = gPad.GetLeftMargin()
    rm = 1. - gPad.GetRightMargin()
    tm = 1. - gPad.GetTopMargin()
    bm = gPad.GetBottomMargin()
    #top
    l.DrawLineNDC(lm, tm, rm, tm)
    #right
    l.DrawLineNDC(rm, bm, rm, tm)
    #bottom
    l.DrawLineNDC(lm, bm, rm, bm)
    #top
    l.DrawLineNDC(lm, bm, lm, tm)
def CMS_label():
    cmsTextFont = 61
    extraTextFont = 52
    lumiTextSize = 0.6
    lumiTextOffset = 0.2
    extraOverCmsTextSize = 0.76
    cmsTextSize = 0.75
    cmsTextOffset = 0.1
    extraTextSize = extraOverCmsTextSize * cmsTextSize
    relPosX = 0.045
    relPosY = 0.035
    relExtraDY = 1.2
    lumiText = ""
    cmsText = "CMS"
    extraText = "Preliminary Phase II Simulation"

    old = (tlatex.GetTextFont(), tlatex.GetTextSize())
    l, r, t, b = gPad.GetLeftMargin(), gPad.GetRightMargin(
    ), gPad.GetTopMargin(), gPad.GetBottomMargin()
    posX_ = l + relPosX * (1 - l - r)
    posY_ = 1 - t + lumiTextOffset * t
    relPosX = 0.105
    posX_ = 0.62 - relPosX * (1 - l - r)
    # right aligned
    tlatex.SetTextFont(42)
    tlatex.SetTextSize(lumiTextSize * t)
    tlatex.DrawLatex(1 - r, 1 - t + lumiTextOffset * t, lumiText)
    tlatex.SetTextFont(cmsTextFont)
    tlatex.SetTextSize(cmsTextSize * t)
    tlatex.DrawLatex(posX_, 1 - t + lumiTextOffset * t,
                     cmsText)  # out of frame
    tlatex.SetTextFont(extraTextFont)
    tlatex.SetTextSize(extraTextSize * t)
    tlatex.DrawLatex(posX_ + relPosX * (1 - l - r), posY_, extraText)
    tlatex.SetTextFont(old[0])
    tlatex.SetTextSize(old[1])
    return
Example #4
0
    def drawtext(self, *texts, **kwargs):
        """
    Draw TLaTeX text in the corner.
      drawtext(str text)
      drawtext(str text, str text, ...)
      drawtext(list texts)
    Text position can be controlled in several ways
      drawlegend(text,position=position)
    where position is a string which can contain the horizontal position, e.g.
      'left', 'center', 'right', 'L', 'C', or 'R'
    The position string can also contain the vertical position as e.g.
      'top', 'middle', 'bottom', 'T', 'M', or 'B'
    Instead of the strings, the exact coordinates can be controlled with
    the keywords x and y:
      drawtext(x=0.2,y=0.8)
    These floats are normalized to the axis frame, ignoring the canvas margins:
    x=0 is the left, x=1 is the right, y=0 is the bottom and y=1 is the top side.
    Values less than 0, or larger than 1, will put the text outside the frame.
    """
        verbosity = LOG.getverbosity(self, kwargs)
        position = kwargs.get('pos', 'topleft')
        position = kwargs.get('position', position)  #.lower()
        tsize = kwargs.get('tsize', _lsize)  # text size
        theight = kwargs.get('theight', None) or 1
        bold = kwargs.get('bold', False)  # bold text
        dolatex = kwargs.get('latex',
                             True)  # automatically format strings as LaTeX
        xuser = kwargs.get('x', None)  # horizontal position
        yuser = kwargs.get('y', None)  # vertical position
        align_user = kwargs.get('align', None)  # text line
        panel = kwargs.get('panel', 1)  # panel (top=1, bottom=2)
        texts = unwraplistargs(texts)
        if not any(t != "" for t in texts):
            return None

        # CHECK
        LOG.insist(self.canvas, "Canvas does not exist!")
        self.canvas.cd(panel)
        scale = 485. / min(gPad.GetWh() * gPad.GetHNDC(),
                           gPad.GetWw() * gPad.GetWNDC())
        tsize *= scale  # text size

        # POSITION
        font = 62 if bold else 42
        align = 13
        position = position.replace('left', 'L').replace(
            'center', 'C').replace('right', 'R').replace(  #.lower()
                'top', 'T').replace('middle', 'M').replace('bottom', 'B')
        if 'R' in position:
            x, align = 0.95, 30  # right
        if 'C' in position:
            x, align = 0.50, 20  # center
        else:
            x, align = 0.05, 10  # left
        if 'B' in position:
            y = 0.05
            align += 1  # bottom
        if 'M' in position:
            y = 0.50
            align += 2  # middle
        else:
            y = 0.95
            align += 3  # top
        #x1 = float(re.findall(r"x=(\d\.\d+)",position)[0])
        #y2 = float(re.findall(r"y=(\d\.\d+)",position)[0]);
        if xuser != None: x = xuser
        if yuser != None: y = yuser
        if align_user != None: align = align_user
        L, R = gPad.GetLeftMargin(), gPad.GetRightMargin()
        T, B = gPad.GetTopMargin(), gPad.GetBottomMargin()
        x = L + (1 - L - R) * x  # convert frame to canvas coordinates
        y = B + (1 - T - B) * y  # convert frame to canvas coordinates

        # LATEX
        latex = TLatex()
        latex.SetTextSize(tsize)
        latex.SetTextAlign(align)
        latex.SetTextFont(font)
        #latex.SetTextColor(kRed)
        latex.SetNDC(True)
        for i, line in enumerate(texts):
            if dolatex:
                line = maketitle(line)
            yline = y - i * theight * 1.2 * tsize
            latex.DrawLatex(x, yline, line)
            LOG.verb(
                "Plot.drawcornertext: i=%d, x=%.2f, y=%.2f, text=%r" %
                (i, x, yline, line), verbosity, 2)
        self.texts.append(latex)

        return latex
Example #5
0
    def drawlegend(self, position=None, **kwargs):
        """Create and draw legend.
    Legend position can be controlled in several ways
      drawlegend(position)
      drawlegend(position=position)
    where position is a string which can contain the horizontal position, e.g.
      'left', 'center', 'right', 'L', 'C', 'R', 'x=0.3', ...
    where 'x' is the position (between 0 an 1) of the left side in the frame.
    The position string can also contain the vertical position as e.g.
      'top', 'middle', 'bottom', 'T', 'M', 'B', 'y=0.3', ...
    where 'y' is the position (between 0 an 1) of the top side in the frame.
    Instead of the strings, the exact legend coordinates can be controlled with
    the keywords x1, x2, y1 and y2, or, x1, y1, width and height:
      drawlegend(x1=0.2,width=0.4)
      drawlegend(x1=0.2,width=0.4,y1=0.9,height=0.4)
      drawlegend(x1=0.2,x2=0.6,y1=0.9,y2=0.4)
    These floats are normalized to the axis frame, ignoring the canvas margins:
    x=0 is the left, x=1 is the right, y=0 is the bottom and y=1 is the top side.
    Values less than 0, or larger than 1, will put the legend outside the frame.
    """
        #if not ratio:
        #  tsize *= 0.80
        #  signaltsize *= 0.80
        verbosity = LOG.getverbosity(self, kwargs)
        hists = self.hists
        errstyle = 'lep' if gStyle.GetErrorX() else 'ep'
        entries = kwargs.get('entries', [])
        bands = kwargs.get('band', [self.errband])  # error bands
        bands = ensurelist(bands, nonzero=True)
        bandentries = kwargs.get('bandentries', [])
        title = kwargs.get('header', None)
        title = kwargs.get('title', title)  # legend header/title
        latex = kwargs.get('latex',
                           True)  # automatically format strings as LaTeX
        style = kwargs.get('style', None)
        style0 = kwargs.get('style0', None)  # style of first histogram
        errstyle = kwargs.get('errstyle', errstyle)  # style for an error point
        styles = kwargs.get('styles', [])
        position = kwargs.get('pos', position)  # legend position
        position = kwargs.get('position', position) or self.position
        option = kwargs.get('option', '')
        border = kwargs.get('border', False)
        transparent = kwargs.get('transparent', True)
        x1_user = kwargs.get('x1', None)  # legend left side
        x2_user = kwargs.get('x2', None)  # legend right side
        y1_user = kwargs.get('y1', None)  # legend top side
        y2_user = kwargs.get('y2', None)  # legend bottom side
        width = kwargs.get('width', -1)  # legend width
        height = kwargs.get('height', -1)  # legend height
        tsize = kwargs.get('tsize', _lsize)  # text size
        twidth = kwargs.get('twidth',
                            None) or 1  # scalefactor for legend width
        theight = kwargs.get('theight',
                             None) or 1  # scalefactor for legend height
        texts = kwargs.get('text', [])  # extra text below legend
        ncols = kwargs.get('ncols',
                           self.ncols) or 1  # number of legend columns
        colsep = kwargs.get('colsep',
                            0.06)  # seperation between legend columns
        bold = kwargs.get('bold', True)  # bold legend header
        panel = kwargs.get('panel', 1)  # panel (top=1, bottom=2)
        texts = ensurelist(texts, nonzero=True)
        entries = ensurelist(entries, nonzero=False)
        bandentries = ensurelist(bandentries, nonzero=True)
        headerfont = 62 if bold else 42

        # CHECK
        LOG.insist(self.canvas, "Canvas does not exist!")
        self.canvas.cd(panel)
        scale = 485. / min(gPad.GetWh() * gPad.GetHNDC(),
                           gPad.GetWw() * gPad.GetWNDC())
        tsize *= scale  # text size

        # ENTRIES
        #if len(bandentries)==len(bands) and len(entries)>len(hists):
        #  for band, bandtitle in zip(band,bandentries):
        #    entries.insert(hists.index(band),bandtitle)
        while len(entries) < len(hists):
            entries.append(hists[len(entries)].GetTitle())
        while len(bandentries) < len(bands):
            bandentries.append(bands[len(bandentries)].GetTitle())
        hists = hists + bands
        entries = entries + bandentries
        if latex:
            title = maketitle(title)
            entries = [maketitle(e) for e in entries]
            texts = [maketitle(t) for t in texts]
        maxlen = estimatelen([title] + entries + texts)

        # STYLES
        if style0:
            styles[0] = style0
        while len(styles) < len(hists):
            hist = hists[len(styles)]
            if hist in bands:
                styles.append('f')
            elif style != None:
                styles.append(style)
            elif hasattr(hist, 'GetFillStyle') and hist.GetFillStyle() > 0:
                styles.append('f')
            elif 'E0' in hist.GetOption() or 'E1' in hist.GetOption():
                styles.append(errstyle)
            else:
                styles.append('lp')

        # NUMBER of LINES
        nlines = sum([1 + e.count('\n') for e in entries])
        #else:       nlines += 0.80
        if texts: nlines += sum([1 + t.count('\n') for t in texts])
        if ncols > 1: nlines /= float(ncols)
        if title: nlines += 1 + title.count('\n')

        # DIMENSIONS
        if width < 0:
            width = twidth * max(0.22, min(0.60, 0.036 + 0.016 * maxlen))
        if height < 0: height = theight * 1.34 * tsize * nlines
        if ncols > 1: width *= ncols / (1 - colsep)
        x2 = 0.90
        x1 = x2 - width
        y1 = 0.92
        y2 = y1 - height

        # POSITION
        if position == None:
            position = ""
        position = position.replace('left', 'L').replace(
            'center', 'C').replace('right', 'R').replace(  #.lower()
                'top', 'T').replace('middle', 'M').replace('bottom', 'B')
        if not any(c in position for c in 'TMBy'):  # set default vertical
            position += 'T'
        if not any(c in position for c in 'LCRx'):  # set default horizontal
            position += 'RR' if ncols > 1 else 'R'  # if title else 'L'

        if 'C' in position:
            if 'R' in position: center = 0.57
            elif 'L' in position: center = 0.43
            else: center = 0.50
            x1 = center - width / 2
            x2 = center + width / 2
        elif 'LL' in position:
            x1 = 0.03
            x2 = x1 + width
        elif 'L' in position:
            x1 = 0.08
            x2 = x1 + width
        elif 'RR' in position:
            x2 = 0.97
            x1 = x2 - width
        elif 'R' in position:
            x2 = 0.92
            x1 = x2 - width
        elif 'x=' in position:
            x1 = float(re.findall(r"x=(\d\.\d+)", position)[0])
            x2 = x1 + width
        if 'M' in position:
            if 'T' in position: middle = 0.57
            elif 'B' in position: middle = 0.43
            else: middle = 0.50
            y1 = middle - height / 2
            y2 = middle + height / 2
        elif 'TT' in position:
            y2 = 0.97
            y1 = y2 - height
        elif 'T' in position:
            y2 = 0.92
            y1 = y2 - height
        elif 'BB' in position:
            y1 = 0.03
            y2 = y1 + height
        elif 'B' in position:
            y1 = 0.08
            y2 = y1 + height
        elif 'y=' in position:
            y2 = float(re.findall(r"y=(\d\.\d+)", position)[0])
            y1 = y2 - height
        if x1_user != None:
            x1 = x1_user
            x2 = x1 + width if x2_user == None else x2_user
        if y1_user != None:
            y1 = y1_user
            y2 = y1 - height if y2_user == None else y2_user
        L, R = gPad.GetLeftMargin(), gPad.GetRightMargin()
        T, B = gPad.GetTopMargin(), gPad.GetBottomMargin()
        X1, X2 = L + (1 - L - R) * x1, L + (
            1 - L - R) * x2  # convert frame to canvas coordinates
        Y1, Y2 = B + (1 - T - B) * y1, B + (
            1 - T - B) * y2  # convert frame to canvas coordinates
        legend = TLegend(X1, Y1, X2, Y2)
        LOG.verb(
            "Plot.drawlegend: position=%r, height=%.3f, width=%.3f, (x1,y1,x2,y2)=(%.2f,%.2f,%.2f,%.2f), (X1,Y1,X2,Y2)=(%.2f,%.2f,%.2f,%.2f)"
            % (position, height, width, x1, y1, x2, y2, X1, Y1, X2, Y2),
            verbosity, 1)

        # MARGIN
        if ncols >= 2:
            margin = 0.090 / width
        else:
            margin = 0.044 / width
        legend.SetMargin(margin)

        # STYLE
        if transparent: legend.SetFillStyle(0)  # 0 = transparent
        else: legend.SetFillColor(0)
        legend.SetBorderSize(border)
        legend.SetTextSize(tsize)
        legend.SetTextFont(headerfont)  # bold for title
        if ncols > 1:
            legend.SetNColumns(ncols)
            legend.SetColumnSeparation(colsep)

        # HEADER
        if title:
            legend.SetHeader(title)
        legend.SetTextFont(42)  # no bold for entries

        # ENTRIES
        if hists:
            for hist1, entry1, style1 in columnize(zip(hists, entries, styles),
                                                   ncols):
                for entry in entry1.split('\n'):
                    legend.AddEntry(hist1, entry, style1)
                    hist1, style1 = 0, ''
        for line in texts:
            legend.AddEntry(0, line, '')

        if verbosity >= 2:
            print ">>> Plot.drawlegend: title=%r, texts=%s, latex=%s" % (
                title, texts, latex)
            print ">>> Plot.drawlegend: hists=%s" % (hists)
            print ">>> Plot.drawlegend: entries=%s" % (entries)
            print ">>> Plot.drawlegend: styles=%s" % (styles)
            print ">>> Plot.drawlegend: nlines=%s, len(hists)=%s, len(texts)=%s, ncols=%s, margin=%s" % (
                nlines, len(hists), len(texts), ncols, margin)

        legend.Draw(option)
        self.legends.append(legend)
        return legend
Example #6
0
 binwidths = []
 for i in range(0, unnormCMS.GetN()):
     if (i > 0):
         binwidths.append(bins[i] - bins[i - 1])
     else:
         binwidths.append(30.0)
 #print binwidths
 normCMS = normalizeGraph(unnormCMS, binwidths)
 normCMS.SetMarkerStyle(kFullCircle)
 normCMS.SetMarkerSize(1.4)
 normCMS.SetMarkerColor(kBlue + 2)
 normCMS.SetLineColor(kBlue + 2)
 normCMS.Draw('apz')
 normCMS.SetMaximum(0.3)
 leg = TLegend(0.4, 1. - gPad.GetTopMargin() - 0.03 - 0.18,
               1. - gPad.GetRightMargin() - 0.02,
               1. - gPad.GetTopMargin() - 0.03, '', 'NDC')
 leg.SetMargin(0.15)
 #leg.Dump()
 leg.SetFillStyle(0)
 leg.SetBorderSize(0)
 leg.AddEntry(normCMS, 'CMS, |y|<2, #sqrt{s}=7 TeV', 'pe')
 if (D0):
     D0.Draw('pz')
     leg.AddEntry(D0, 'D#oslash, |y|<1.8, #sqrt{s}=1.96 TeV', 'pe')
 else:
     leg.SetY1(1. - gPad.GetTopMargin() - 0.03 - 0.12)
 if (CDF):
     CDF.Draw('pz')
     leg.AddEntry(CDF, 'CDF, |y|<0.4, #sqrt{s}=1.8 TeV', 'pe')
 #leg.Dump()