Skip to content

Reference

This part of the project documentation focuses on an information-oriented approach. Use it as a reference for the technical implementation of the cmsstyle project code.

This python module contains the core methods for the usage of the CMSStyle tools.

The cmsstyle library provides a pyROOT-based implementation of the figure guidelines of the CMS Collaboration.

CMSCanvasManager

Bases: object

A manager of the different graphical parts of a canvas.

Source code in src/cmsstyle/cmsstyle.py
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
class CMSCanvasManager(object):
    """A manager of the different graphical parts of a canvas."""

    def __init__(self, canvas, pads=None, frames=None,
                 bottom_pad=None, top_pad=None, legendtextsize=None, cmslogotextsize=None, ipos=None, grid_metadata=None):
        """
        At minimum, a canvas manager needs a canvas to plot on. Optionally, it
        can manage different sub-components of a canvas:
        - A list of pads that will display subplots
        - A list of frames, one per subplot. The frame is an empty rt.TH1F which
          is only used to manage the graphical attributes of axes (range, labels, etc.)
        - A separate pad for the top part of the canvas. If this is not None, then
          the subplots will be contained below this pad.
        - A separate pad for the bottom part of the canvas. If this is not None,
          then the subplots will be contained above this pad.
        """
        self._canvas = canvas
        self._frames = frames
        self._legendtextsize = legendtextsize
        self._cmslogotextsize = cmslogotextsize
        self._ipos = ipos

        if self._frames is not None:
            if pads is None:
                raise RuntimeError(
                    "Received an input list of pad frames, but no pads associated with them."
                )
            if len(self._frames) != len(pads):
                raise RuntimeError(
                    "Received an input list of pad frames with wrong length: %d != %d" %
                    (len(self._frames), len(pads))
                )
            self._pads = [CMSPad(self, pad, True) for pad in pads]
        else:
            self._pads = [CMSPad(self, pad) for pad in pads] if pads is not None else None

        self._grid_metadata = grid_metadata
        if self._pads is not None:
            if self._grid_metadata is None:
                raise RuntimeError("Missing grid metadata in canvas manager.")
            npads = self._grid_metadata.ncolumns * self._grid_metadata.nrows
            if len(self._pads) != npads:
                raise RuntimeError(
                    "Number of pads passed to canvas manager (%d) is different from the expected number (%d)." %
                    (len(self._pads), npads)
                )

        self._bottom_pad = CMSPad(self, bottom_pad) if bottom_pad is not None else None
        self._top_pad = CMSPad(self, top_pad) if top_pad is not None else None

    @property
    def top_pad(self):
        if self._top_pad is None:
            raise RuntimeError("Trying to retrive top pad, but it is not present.")
        return self._top_pad

    @property
    def bottom_pad(self):
        if self._bottom_pad is None:
            raise RuntimeError("Trying to retrive bottom pad, but it is not present.")
        return self._bottom_pad

    @property
    def pads(self):
        if self._pads is None:
            raise RuntimeError("Trying to retrieve subplots, but they are not present.")
        return self._pads

    def plot_common_legend(self, pad, *args, **kwargs):
        xleft = kwargs.get("xleft", None)
        xright = kwargs.get("xright", None)
        ydown = kwargs.get("ydown", None)
        yup = kwargs.get("yup", None)
        title = kwargs.get("title", "CMS")
        titleFont = kwargs.get("titleFont", 62)
        titleSize = kwargs.get("titleSize", 50 * 0.75 / 0.6)
        subtitle = kwargs.get("subtitle", "Preliminary")
        subtitleFont = kwargs.get("subtitleFont", 52)
        textalign = kwargs.get("textalign", 13)
        ipos = kwargs.get("ipos", 0)
        legendtextSize = kwargs.get("legendtextSize", 30)

        pad._pad.cd()
        horizontal_margin = float(self._grid_metadata.pad_horizontal_margin) / self._grid_metadata.ncolumns
        xleft = xleft if xleft is not None else horizontal_margin
        xright = xright if xright is not None else 1 - horizontal_margin
        ydown = ydown if ydown is not None else 0
        yup = yup if yup is not None else 0.7

        leg = rt.TLegend(xleft, ydown, xright, yup)
        leg.SetTextAlign(textalign)
        leg.SetBorderSize(1)
        leg.SetMargin(0.5)

        # Have at most 5 items on the same row
        ndrawables = len(args)
        ncolumns = ndrawables + 1 if (ndrawables + 1) < 6 else 5
        leg.SetNColumns(ncolumns)

        if ipos != 0:
            n = 0
            for arg in args:
                if n % ncolumns == 0:
                    leg.AddEntry(0, "      ", "  ")
                    n += 1
                # leg.AddEntry(arg.obj, arg.name, arg.opt)
                leg.AddEntry(arg[0], arg[1], arg[2])
                n += 1
        else:
            for arg in args:
                leg.AddEntry(arg[0], arg[1], arg[2])

        pad.plot(leg)

        latex = rt.TLatex()
        latex.SetNDC()
        latex.SetTextFont(titleFont)

        canvas_height = pad._pad.GetWh()
        pad_ndc_height = pad._pad.GetHNDC()
        pad_pixel_height = canvas_height * pad_ndc_height
        titleSize = titleSize / pad_pixel_height
        subtitleSize = titleSize * 0.76

        latex.SetTextSize(titleSize)
        latex.SetTextAlign(13)

        leg.SetTextSize(legendtextSize / pad_pixel_height)

        if ipos != 0:
            latex.DrawLatex(0.105, 0.60, title)
        else:
            latex.DrawLatex(0.10, 0.97, title)

        latex.SetTextFont(subtitleFont)
        latex.SetTextSize(subtitleSize)

        if ipos != 0:
            latex.DrawLatex(0.105, 0.30, subtitle)
        else:
            latex.DrawLatex(0.17, 0.94, subtitle)

    def plot_text(
        self,
        pad,
        text,
        textsize=50,
        textfont=42,
        textalign=33,
        xcoord=None,
        ycoord=None
    ):
        # Plotting text is special, we need to be already inside the right pad
        # (i.e. `cd()` must have been called before the creation of the text)
        with _managed_tpad_context(self._canvas):
            pad._pad.cd()
            horizontal_margin = float(self._grid_metadata.pad_horizontal_margin) / self._grid_metadata.ncolumns
            xcoord = xcoord if xcoord is not None else 1 - horizontal_margin
            ycoord = ycoord if ycoord is not None else 1

            latex = rt.TLatex()
            latex.SetNDC()
            latex.SetTextAngle(0)
            latex.SetTextColor(rt.kBlack)

            latex.SetTextFont(textfont)
            latex.SetTextAlign(textalign)

            canvas_height = pad._pad.GetWh()
            pad_ndc_height = pad._pad.GetHNDC()
            pad_pixel_height = canvas_height * pad_ndc_height
            textsize = textsize / pad_pixel_height
            latex.SetTextSize(textsize)

            latex.DrawLatex(xcoord, ycoord, text)
            latex.Draw()
            pad._drawables.append(latex)

    def ylabel(self, label=None, labels=None):
        if label is not None and labels is not None:
            raise RuntimeError("Cannot set both global and per-frame Y labels.")

        if label is not None:
            for frame in self._frames:
                frame.GetYaxis().SetTitle(label)
        # If the dictionary is passed it must be of the form dict[int, str] where
        # the keys are the indexes of the pads in the canvas with the usual
        # convention left-right,top-bottom starting from 1.
        elif labels is not None:
            for nframe in labels:
                self._frames[nframe].GetYaxis().SetTitle(labels[nframe])

    def ylimits(self, limits=None):
        for nframe in limits:
            self._frames[nframe].SetMinimum(limits[nframe][0])
            self._frames[nframe].SetMaximum(limits[nframe][1])
            # self._frames[nframe].GetYaxis().SetLimits(limits[nframe][0], limits[nframe][1])

    def xlimits(self, limits=None):
        for nframe in limits:
            self._frames[nframe].GetXaxis().SetLimits(limits[nframe][0], limits[nframe][1])

    def save_figure(self, filename):
        self._canvas.SaveAs(filename)

__init__(canvas, pads=None, frames=None, bottom_pad=None, top_pad=None, legendtextsize=None, cmslogotextsize=None, ipos=None, grid_metadata=None)

At minimum, a canvas manager needs a canvas to plot on. Optionally, it can manage different sub-components of a canvas: - A list of pads that will display subplots - A list of frames, one per subplot. The frame is an empty rt.TH1F which is only used to manage the graphical attributes of axes (range, labels, etc.) - A separate pad for the top part of the canvas. If this is not None, then the subplots will be contained below this pad. - A separate pad for the bottom part of the canvas. If this is not None, then the subplots will be contained above this pad.

Source code in src/cmsstyle/cmsstyle.py
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
def __init__(self, canvas, pads=None, frames=None,
             bottom_pad=None, top_pad=None, legendtextsize=None, cmslogotextsize=None, ipos=None, grid_metadata=None):
    """
    At minimum, a canvas manager needs a canvas to plot on. Optionally, it
    can manage different sub-components of a canvas:
    - A list of pads that will display subplots
    - A list of frames, one per subplot. The frame is an empty rt.TH1F which
      is only used to manage the graphical attributes of axes (range, labels, etc.)
    - A separate pad for the top part of the canvas. If this is not None, then
      the subplots will be contained below this pad.
    - A separate pad for the bottom part of the canvas. If this is not None,
      then the subplots will be contained above this pad.
    """
    self._canvas = canvas
    self._frames = frames
    self._legendtextsize = legendtextsize
    self._cmslogotextsize = cmslogotextsize
    self._ipos = ipos

    if self._frames is not None:
        if pads is None:
            raise RuntimeError(
                "Received an input list of pad frames, but no pads associated with them."
            )
        if len(self._frames) != len(pads):
            raise RuntimeError(
                "Received an input list of pad frames with wrong length: %d != %d" %
                (len(self._frames), len(pads))
            )
        self._pads = [CMSPad(self, pad, True) for pad in pads]
    else:
        self._pads = [CMSPad(self, pad) for pad in pads] if pads is not None else None

    self._grid_metadata = grid_metadata
    if self._pads is not None:
        if self._grid_metadata is None:
            raise RuntimeError("Missing grid metadata in canvas manager.")
        npads = self._grid_metadata.ncolumns * self._grid_metadata.nrows
        if len(self._pads) != npads:
            raise RuntimeError(
                "Number of pads passed to canvas manager (%d) is different from the expected number (%d)." %
                (len(self._pads), npads)
            )

    self._bottom_pad = CMSPad(self, bottom_pad) if bottom_pad is not None else None
    self._top_pad = CMSPad(self, top_pad) if top_pad is not None else None

CMSPad

Bases: object

A pad, part of a canvas.

Source code in src/cmsstyle/cmsstyle.py
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
class CMSPad(object):
    """A pad, part of a canvas."""

    def __init__(self, manager, pad, has_frame=False):
        self._manager = manager
        self._pad = pad
        # The frame is a ROOT histogram (TH1F), only used in the pad to define
        # define the axis ranges and be able to modify them consistently
        self._has_frame = has_frame

        # Throughout the lifetime of this pad, many drawables might be drawn
        # onto it. Make sure to keep lifelines around to avoid early object
        # destruction
        self._drawables = []

    def plot(self, obj, opt="", **kwargs):
        # If a frame has been created for this pad, its axis must be respected.
        # Make sure of it by plotting every object on top of the existing frame.
        if self._has_frame and "same" not in opt.lower():
            opt += " SAME"

        with _managed_tpad_context(self._manager._canvas):
            self._pad.cd()
            setRootObjectProperties(obj, **kwargs)
            obj.Draw(opt)
            self._pad.RedrawAxis()
            self._drawables.append(obj)

GridMetaData

Bases: object

Metadata related to the grid layout of a cmsstyle canvas.

(ncolumns, nrows) is the grid disposition. Horizontal and vertical margins indicate the margin to use for a proper alignment of the graphical elements and they are used throughout different utilities in CMSCanvasManager.

Source code in src/cmsstyle/cmsstyle.py
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
class GridMetaData(object):
    """
    Metadata related to the grid layout of a cmsstyle canvas.

    (ncolumns, nrows) is the grid disposition. Horizontal and vertical margins
    indicate the margin to use for a proper alignment of the graphical elements
    and they are used throughout different utilities in CMSCanvasManager.
    """

    def __init__(self, ncolumns, nrows, pad_horizontal_margin, pad_vertical_margin):
        self.ncolumns = ncolumns
        self.nrows = nrows
        self.pad_horizontal_margin = pad_horizontal_margin
        self.pad_vertical_margin = pad_vertical_margin

p10

A class to represent the Petroff color scheme with 10 colors.

Attributes: kBlue (int): The color blue. kYellow (int): The color yellow. kRed (int): The color red. kGray (int): The color gray. kViolet (int): The color violet. kBrown (int): The color brown. kOrange (int): The color orange. kGreen (int): The color green.

Source code in src/cmsstyle/cmsstyle.py
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
class p10:
    """
    A class to represent the Petroff color scheme with 10 colors.

    Attributes:
    kBlue (int): The color blue.
    kYellow (int): The color yellow.
    kRed (int): The color red.
    kGray (int): The color gray.
    kViolet (int): The color violet.
    kBrown (int): The color brown.
    kOrange (int): The color orange.
    kGreen (int): The color green.
    """

    # ROOT may have defined the colors:
    try:
        kBlue = rt.kP10Blue
        kYellow = rt.kP10Yellow
        kRed = rt.kP10Red
        kGray = rt.kP10Gray
        kViolet = rt.kP10Violet
        kBrown = rt.kP10Brown
        kOrange = rt.kP10Orange
        kGreen = rt.kP10Green
        kAsh = rt.kP10Ash
        kCyan = rt.kP10Cyan
    except Exception:
        kBlue = rt.TColor.GetColor("#3f90da")
        kYellow = rt.TColor.GetColor("#ffa90e")
        kRed = rt.TColor.GetColor("#bd1f01")
        kGray = rt.TColor.GetColor("#94a4a2")
        kViolet = rt.TColor.GetColor("#832db6")
        kBrown = rt.TColor.GetColor("#a96b59")
        kOrange = rt.TColor.GetColor("#e76300")
        kGreen = rt.TColor.GetColor("#b9ac70")
        kAsh = rt.TColor.GetColor("#717581")
        kCyan = rt.TColor.GetColor("#92dadd")

p6

A class to represent the Petroff color scheme with 6 colors.

Attributes: kBlue (int): The color blue. kYellow (int): The color yellow. kRed (int): The color red. kGrape (int): The color grape. kGray (int): The color gray. kViolet (int): The color violet.

Source code in src/cmsstyle/cmsstyle.py
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
class p6:
    """
    A class to represent the Petroff color scheme with 6 colors.

    Attributes:
    kBlue (int): The color blue.
    kYellow (int): The color yellow.
    kRed (int): The color red.
    kGrape (int): The color grape.
    kGray (int): The color gray.
    kViolet (int): The color violet.
    """

    # ROOT may have defined the colors:
    try:
        kBlue = rt.kP6Blue
        kYellow = rt.kP6Yellow
        kRed = rt.kP6Red
        kGrape = rt.kP6Grape
        kGray = rt.kP6Gray
        if (
            rt.gROOT.GetColor(rt.kP6Violet).GetTitle == "#7a21dd"
        ):  # There was a bug in the first implementation in ROOT
            # (I think no "released" version is affected. 6.34.00 is already OK)
            kViolet = rt.kP6Violet
        else:
            kViolet = rt.TColor.GetColor("#7a21dd")
    except Exception:  # Defining the color scheme by hand
        kBlue = rt.TColor.GetColor("#5790fc")
        kYellow = rt.TColor.GetColor("#f89c20")
        kRed = rt.TColor.GetColor("#e42536")
        kGrape = rt.TColor.GetColor("#964a8b")
        kGray = rt.TColor.GetColor("#9c9ca1")
        kViolet = rt.TColor.GetColor("#7a21dd")

p8

A class to represent the Petroff color scheme with 8 colors.

Attributes: kBlue (int): The color blue. kOrange (int): The color orange. kRed (int): The color red. kPink (int): The color pink. kGreen (int): The color green. kCyan (int): The color cyan. kAzure (int): The color azure. kGray (int): The color gray.

Source code in src/cmsstyle/cmsstyle.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
class p8:
    """
    A class to represent the Petroff color scheme with 8 colors.

    Attributes:
    kBlue (int): The color blue.
    kOrange (int): The color orange.
    kRed (int): The color red.
    kPink (int): The color pink.
    kGreen (int): The color green.
    kCyan (int): The color cyan.
    kAzure (int): The color azure.
    kGray (int): The color gray.
    """

    # ROOT may have defined the colors:
    try:
        kBlue = rt.kP8Blue
        kOrange = rt.kP8Orange
        kRed = rt.kP8Red
        kPink = rt.kP8Pink
        kGreen = rt.kP8Green
        kCyan = rt.kP8Cyan
        kAzure = rt.kP8Azure
        kGray = rt.kP8Gray
    except Exception:  # Defining the color scheme by hand
        kBlue = rt.TColor.GetColor("#1845fb")
        kOrange = rt.TColor.GetColor("#ff5e02")
        kRed = rt.TColor.GetColor("#c91f16")
        kPink = rt.TColor.GetColor("#c849a9")
        kGreen = rt.TColor.GetColor("#adad7d")
        kCyan = rt.TColor.GetColor("#86c8dd")
        kAzure = rt.TColor.GetColor("#578dff")
        kGray = rt.TColor.GetColor("#656364")

AppendAdditionalInfo(text)

Append additional information to be displayed, e.g. a string identifying a region, or selection cuts.

Parameters:

Name Type Description Default
text str

The additional information text.

required
Source code in src/cmsstyle/cmsstyle.py
245
246
247
248
249
250
251
252
253
def AppendAdditionalInfo(text):
    """
    Append additional information to be displayed, e.g. a string identifying a region, or selection cuts.

    Args:
        text (str): The additional information text.
    """
    global additionalInfo
    additionalInfo.append(text)

CMS_lumi(pad, iPosX=11, scaleLumi=1)

Draw the CMS text and luminosity information on the specified pad.

Parameters:

Name Type Description Default
pad TPad

The pad to draw on.

required
iPosX int

The position of the CMS logo. Defaults to 11 (top-left, left-aligned). Set it to 0 to put it outside the box (top left)

11
scaleLumi float

Scale factor for the luminosity text size (default is 1, no scaling).

1
Source code in src/cmsstyle/cmsstyle.py
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
def CMS_lumi(pad, iPosX=11, scaleLumi=1):
    """
    Draw the CMS text and luminosity information on the specified pad.

    Args:
        pad (ROOT.TPad): The pad to draw on.
        iPosX (int, optional): The position of the CMS logo. Defaults to 11 (top-left, left-aligned).
                               Set it to 0 to put it outside the box (top left)
        scaleLumi (float, optional): Scale factor for the luminosity text size (default is 1, no scaling).
    """
    relPosX = 0.035
    relPosY = 0.035
    relExtraDY = 1.2
    outOfFrame = int(iPosX / 10) == 0
    alignX_ = max(int(iPosX / 10), 1)
    alignY_ = 1 if iPosX == 0 else 3
    align_ = 10 * alignX_ + alignY_
    H = pad.GetWh() * pad.GetHNDC()
    W = pad.GetWw() * pad.GetWNDC()
    L = pad.GetLeftMargin()
    t = pad.GetTopMargin()
    r = pad.GetRightMargin()
    b = pad.GetBottomMargin()
    outOfFrame_posY = 1 - t + lumiTextOffset * t
    pad.cd()

    lumiText = cms_lumi
    if cms_energy != "":
        lumiText += " (" + cms_energy + ")"

    drawText(
        text=lumiText,
        posX=1 - r,
        posY=outOfFrame_posY,
        font=42,
        align=31,
        size=lumiTextSize * t * scaleLumi,
    )

    # Now we go to the CMS message:

    posX_ = 0
    if iPosX % 10 <= 1:
        posX_ = L + relPosX * (1 - L - r)
    elif iPosX % 10 == 2:
        posX_ = L + 0.5 * (1 - L - r)
    elif iPosX % 10 == 3:
        posX_ = 1 - r - relPosX * (1 - L - r)

    posY_ = 1 - t - relPosY * (1 - t - b)

    if outOfFrame:  # CMS logo and extra text out of the frame
        if (
            len(useCmsLogo) > 0
        ):  # Using CMS Logo instead of the text label (uncommon and discouraged!)
            print(
                "WARNING: Usage of (graphical) CMS-logo outside the frame is not currently supported!"
            )
        #        else {
        if len(cmsText) > 0:
            drawText(cmsText, L, outOfFrame_posY, cmsTextFont, 11, cmsTextSize * t)

            # Checking position of the extraText after the CMS logo text.
            scale = 1
            if W > H:
                scale = H / float(W)  # For a rectangle
            L += 0.043 * (extraTextFont * t * cmsTextSize) * scale

        if len(extraText) > 0:  # Only if something to write
            drawText(
                extraText,
                L,
                outOfFrame_posY,
                extraTextFont,
                align_,
                extraOverCmsTextSize * cmsTextSize * t,
            )

        if len(additionalInfo) > 0:  # This is currently not supported!
            print(
                "WARNING: Additional Info for the CMS-info part outside the frame is not currently supported!"
            )

    else:  # In the frame!
        if len(useCmsLogo) > 0:  # Using CMS Logo instead of the text label
            posX_ = L + 0.045 * (1 - L - r) * W / H
            posY_ = 1 - t - 0.045 * (1 - t - b)
            # Note this is only for TCanvas!
            addCmsLogo(pad, posX_, posY_ - 0.15, posX_ + 0.15 * H / W, posY_)

        else:
            if len(cmsText) > 0:
                drawText(cmsText, posX_, posY_, cmsTextFont, align_, cmsTextSize * t)
                # Checking position of the extraText after the CMS logo text.
                posY_ -= relExtraDY * cmsTextSize * t

            if len(extraText) > 0:  # Only if something to write
                drawText(
                    extraText,
                    posX_,
                    posY_,
                    extraTextFont,
                    align_,
                    extraOverCmsTextSize * cmsTextSize * t,
                )
            else:
                posY_ += relExtraDY * cmsTextSize * t  # Preparing for additional text!

            for ind, tt in enumerate(additionalInfo):
                drawText(
                    tt,
                    posX_,
                    posY_
                    - 0.004
                    - (relExtraDY * extraOverCmsTextSize * cmsTextSize * t / 2 + 0.02)
                    * (ind + 1),
                    additionalInfoFont,
                    align_,
                    extraOverCmsTextSize * cmsTextSize * t,
                )

    UpdatePad(pad)

CreateAlternativePalette(alpha=1)

Create an alternative color palette for 2D histograms.

Parameters:

Name Type Description Default
alpha float

The transparency value for the palette colors. Defaults to 1 (opaque).

1
Source code in src/cmsstyle/cmsstyle.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
def CreateAlternativePalette(alpha=1):
    """
    Create an alternative color palette for 2D histograms.

    Args:
        alpha (float, optional): The transparency value for the palette colors. Defaults to 1 (opaque).
    """
    red_values = array("d", [0.00, 0.00, 1.00, 0.70])
    green_values = array("d", [0.30, 0.50, 0.70, 0.00])
    blue_values = array("d", [0.50, 0.40, 0.20, 0.15])
    length_values = array("d", [0.00, 0.15, 0.70, 1.00])
    num_colors = 200
    color_table = rt.TColor.CreateGradientColorTable(
        len(length_values),
        length_values,
        red_values,
        green_values,
        blue_values,
        num_colors,
        alpha,
    )
    global usingPalette2D
    usingPalette2D = [color_table + i for i in range(num_colors)]

GetCmsCanvasHist(canv)

Get the histogram frame object from a canvas created with cmsCanvas (or any TPad).

Parameters:

Name Type Description Default
canv TCanvas

The canvas to get the histogram frame from (that can be any TPad).

required

Returns:

Type Description

ROOT.TH1: The histogram frame object.

Source code in src/cmsstyle/cmsstyle.py
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
def GetCmsCanvasHist(canv):
    """
    Get the histogram frame object from a canvas created with cmsCanvas (or any TPad).

    Args:
        canv (ROOT.TCanvas): The canvas to get the histogram frame from (that can be any TPad).

    Returns:
        ROOT.TH1: The histogram frame object.
    """
    frame = canv.GetListOfPrimitives().FindObject("hframe")

    if not frame:   # Just returning the frame of the first Pad!
        return canv.cd(1).GetListOfPrimitives().FindObject("hframe")
    return frame

GetPalette(hist)

Get the colour palette object associated with a histogram.

Parameters:

Name Type Description Default
hist TH1 or TH2

The histogram to get the palette from.

required

Returns:

Type Description

ROOT.TPaletteAxis: The colour palette object.

Source code in src/cmsstyle/cmsstyle.py
536
537
538
539
540
541
542
543
544
545
546
547
548
def GetPalette(hist):
    """
    Get the colour palette object associated with a histogram.

    Args:
        hist (ROOT.TH1 or ROOT.TH2): The histogram to get the palette from.

    Returns:
        ROOT.TPaletteAxis: The colour palette object.
    """
    UpdatePad()  # Must update the pad to access the palette
    palette = hist.GetListOfFunctions().FindObject("palette")
    return palette

ResetAdditionalInfo()

Reset the additional information to be displayed.

Source code in src/cmsstyle/cmsstyle.py
237
238
239
240
241
242
def ResetAdditionalInfo():
    """
    Reset the additional information to be displayed.
    """
    global additionalInfo
    additionalInfo = []

SaveCanvas(canv, path, close=True)

Save a canvas to a file and optionally close it. Takes care of fixing overlay and closing objects.

Parameters:

Name Type Description Default
canv TCanvas

The canvas to save.

required
path str

The path to save the canvas to.

required
close bool

Whether to close the canvas after saving. Defaults to True.

True
Source code in src/cmsstyle/cmsstyle.py
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
def SaveCanvas(canv, path, close=True):
    """
    Save a canvas to a file and optionally close it. Takes care of fixing overlay and closing objects.

    Args:
        canv (ROOT.TCanvas): The canvas to save.
        path (str): The path to save the canvas to.
        close (bool, optional): Whether to close the canvas after saving. Defaults to True.
    """
    UpdatePad(canv)
    canv.SaveAs(path)
    if close:
        canv.Close()

SetAlternative2DColor(hist=None, style=None, alpha=1)

Set an alternative colour palette for a 2D histogram.

Parameters:

Name Type Description Default
hist TH2

The 2D histogram to set the colour palette for.

None
style TStyle

The style object to use for setting the palette.

None
alpha float

The transparency value for the palette colours. Defaults to 1 (opaque).

1
Source code in src/cmsstyle/cmsstyle.py
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
def SetAlternative2DColor(hist=None, style=None, alpha=1):
    """
    Set an alternative colour palette for a 2D histogram.

    Args:
        hist (ROOT.TH2, optional): The 2D histogram to set the colour palette for.
        style (ROOT.TStyle, optional): The style object to use for setting the palette.
        alpha (float, optional): The transparency value for the palette colours. Defaults to 1 (opaque).
    """
    global usingPalette2D
    if usingPalette2D is None:
        CreateAlternativePalette(alpha=alpha)
    if style is None:  # Using the cmsStyle or, if not set the current style.
        global cmsStyle
        if cmsStyle is not None:
            style = cmsStyle
        else:
            style = rt.gStyle

    style.SetPalette(len(usingPalette2D), array("i", usingPalette2D))

    if hist is not None:
        hist.SetContour(len(usingPalette2D))

SetCMSPalette()

Set the official CMS colour palette for 2D histograms directly.

Source code in src/cmsstyle/cmsstyle.py
527
528
529
530
531
def SetCMSPalette():
    """
    Set the official CMS colour palette for 2D histograms directly.
    """
    cmsStyle.SetPalette(rt.kViridis)

SetCmsText(text, font=None, size=None)

Function that allows to edit the default "CMS" string

Parameters:

Name Type Description Default
text str

The CMS text.

required
font Font_t

Font of the CMS Text. If None or 0, it is not changed.

None
size float

Size of the CMS Text. If None or 0, it is not changed.

None
Source code in src/cmsstyle/cmsstyle.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def SetCmsText(text, font=None, size=None):
    """
    Function that allows to edit the default
    "CMS" string

    Args:
        text (str): The CMS text.
        font (ROOT.Font_t, optional): Font of the CMS Text. If None or 0, it is not changed.
        size (float, optional): Size of the CMS Text. If None or 0, it is not changed.
    """
    global cmsText
    global cmsTextFont
    global cmsTextSize
    cmsText = text

    if font is not None and font != 0:
        cmsTextFont = font

    if size is not None and size != 0:
        cmsTextSize = size

SetEnergy(energy, unit='TeV')

Set the centre-of-mass energy value and unit to be displayed.

Parameters:

Name Type Description Default
energy float

The centre-of-mass energy value. If it is 0, the string for the energy is set to the value of unit.

required
unit str

The energy unit. Defaults to "TeV".

'TeV'
Source code in src/cmsstyle/cmsstyle.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def SetEnergy(energy, unit="TeV"):
    """
    Set the centre-of-mass energy value and unit to be displayed.

    Args:
        energy (float): The centre-of-mass energy value. If it is 0, the
                        string for the energy is set to the value of unit.

        unit (str, optional): The energy unit. Defaults to "TeV".
    """
    global cms_energy
    if energy is None or energy == 0:
        cms_energy = unit
    else:
        if abs(energy - 13) < 0.001:
            cms_energy = "13 "
        elif abs(energy - 13.6) < 0.001:
            cms_energy = "13.6 "
        elif abs(energy - 7) < 0.001:
            cms_energy = "7"
        elif abs(energy - 5.02) < 0.001:
            cms_energy = "5.02"
        elif abs(energy - 0.9) < 0.001:
            cms_energy = "0.9"
        elif abs(energy - 2.4) < 0.001:
            cms_energy = "2.4"
        else:
            print("ERROR: Provided energy is not recognized! {}".format(energy))
            cms_energy = "??? "
        cms_energy += unit

SetExtraText(text, font=None)

Set extra text to be displayed next to "CMS", e.g. "Preliminary". If set to an empty string, nothing extra is written.

Parameters:

Name Type Description Default
text str

The extra text. It should be noted that some special nicknames are allowed.

required
font Font_t

Font of the extra text. If None or 0, it is not changed.

None

The nicknames that could be used take info account the most relevant case (as seen in https://cms-analysis.docs.cern.ch/guidelines/plotting/general/#cms-label-requirements "p" -> "Preliminary" "s" -> "Simulation" "su" -> "Supplementary" "wip" -> "Work in progress "pw" -> "Private work (CMS data)"

Source code in src/cmsstyle/cmsstyle.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def SetExtraText(text, font=None):
    """
    Set extra text to be displayed next to "CMS", e.g. "Preliminary". If set to an empty string, nothing
    extra is written.

    Args:
        text (str): The extra text. It should be noted that some special nicknames
                    are allowed.
        font (ROOT.Font_t, optional): Font of the extra text. If None or 0, it is not changed.

    The nicknames that could be used take info account the most relevant case (as seen in
    https://cms-analysis.docs.cern.ch/guidelines/plotting/general/#cms-label-requirements
        "p"   -> "Preliminary"
        "s"   -> "Simulation"
        "su"  -> "Supplementary"
        "wip" -> "Work in progress
        "pw"  -> "Private work (CMS data)"
    """
    global extraText
    extraText = text

    if extraText == "p":
        extraText = "Preliminary"
    elif extraText == "s":
        extraText = "Simulation"
    elif extraText == "su":
        extraText = "Supplementary"
    elif extraText == "wip":
        extraText = "Work in progress"
    elif extraText == "pw":
        extraText = "Private work (CMS data)"

    # Now, if the extraText does contain the word "Private", the CMS logo is not DRAWN/WRITTEN

    if "Private" in extraText:
        global cmsText
        global useCmsLogo

        cmsText = ""
        useCmsLogo = ""

    # For the font:
    global extraTextFont
    if font is not None and font != 0:
        extraTextFont = font

SetLumi(lumi, unit='fb', run='Run 2', round_lumi=-1)

Set the integrated luminosity value and unit to be displayed.

Parameters:

Name Type Description Default
lumi float

The integrated luminosity value. May be skipped if set to None.

required
unit str

The integrated luminosity unit. Defaults to "fb".

'fb'
run str

The LHC run to which the sample refers to.

'Run 2'
round_lumi int

Number of decimal digits to present the number. If no 0,1 nor 2, no rounding is done

-1
Source code in src/cmsstyle/cmsstyle.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def SetLumi(lumi, unit="fb", run="Run 2", round_lumi=-1):
    """
    Set the integrated luminosity value and unit to be displayed.

    Args:
        lumi (float): The integrated luminosity value. May be skipped if set to None.
        unit (str, optional): The integrated luminosity unit. Defaults to "fb".
        run (str, optional): The LHC run to which the sample refers to.
        round_lumi (int, optional): Number of decimal digits to present the number. If no 0,1 nor 2, no rounding is done
    """
    global cms_lumi

    cms_lumi = ""
    if run is not None and len(run) > 0:  # There is an indication about the run period
        cms_lumi += run

    # The lumi value is the most complicated thing

    if lumi is not None and lumi >= 0:
        if len(cms_lumi) > 0:
            cms_lumi += ", "

        if round_lumi == 0:
            cms_lumi += "{:.0f}".format(lumi)
        elif round_lumi == 1:
            cms_lumi += "{:.1f}".format(lumi)
        elif round_lumi == 2:
            cms_lumi += "{:.2f}".format(lumi)
        else:
            cms_lumi += "{}".format(lumi)

        cms_lumi += " {unit}^{{#minus1}}".format(unit=unit)

UpdatePad(pad=None)

Update the indicated pad. If none is provided, update the currently active Pad.

Parameters:

Name Type Description Default
pad TPad or TCanvas

Pad or Canvas to be updated (gPad if none provided)

None
Source code in src/cmsstyle/cmsstyle.py
623
624
625
626
627
628
629
630
631
632
633
634
635
636
def UpdatePad(pad=None):
    """Update the indicated pad. If none is provided, update the currently active Pad.

    Args:
        pad (TPad or TCanvas, optional): Pad or Canvas to be updated (gPad if none provided)
    """
    if pad is not None:
        pad.RedrawAxis()
        pad.Modified()
        pad.Update()
    else:
        rt.gPad.RedrawAxis()
        rt.gPad.Modified()
        rt.gPad.Update()

UpdatePalettePosition(hist, canv=None, X1=None, X2=None, Y1=None, Y2=None, isNDC=True)

Adjust the position of the color palette for a 2D histogram.

Parameters:

Name Type Description Default
hist TH2

The 2D histogram to adjust the palette for.

required
canv TCanvas

The canvas containing the histogram. If provided, the palette position will be adjusted based on the canvas margins.

None
X1 float

The left position of the palette in NDC (0-1) or absolute coordinates.

None
X2 float

The right position of the palette in NDC (0-1) or absolute coordinates.

None
Y1 float

The bottom position of the palette in NDC (0-1) or absolute coordinates.

None
Y2 float

The top position of the palette in NDC (0-1) or absolute coordinates.

None
isNDC bool

Whether the provided coordinates are in NDC (True) or absolute coordinates (False). Defaults to True.

True
Source code in src/cmsstyle/cmsstyle.py
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
def UpdatePalettePosition(
    hist, canv=None, X1=None, X2=None, Y1=None, Y2=None, isNDC=True
):
    """
    Adjust the position of the color palette for a 2D histogram.

    Args:
        hist (ROOT.TH2): The 2D histogram to adjust the palette for.
        canv (ROOT.TCanvas, optional): The canvas containing the histogram. If provided, the palette position will be adjusted based on the canvas margins.
        X1 (float, optional): The left position of the palette in NDC (0-1) or absolute coordinates.
        X2 (float, optional): The right position of the palette in NDC (0-1) or absolute coordinates.
        Y1 (float, optional): The bottom position of the palette in NDC (0-1) or absolute coordinates.
        Y2 (float, optional): The top position of the palette in NDC (0-1) or absolute coordinates.
        isNDC (bool, optional): Whether the provided coordinates are in NDC (True) or absolute coordinates (False). Defaults to True.
    """
    palette = GetPalette(hist)
    if canv is not None and isNDC:  # Ignoring the provided camvas if units are not NDC!
        # If we provide a TPad/Canvas we use the values for it, EXCEPT if explicit
        # values are provided!
        _ = GetCmsCanvasHist(canv)

        if X1 is None:
            X1 = 1 - canv.GetRightMargin() * 0.95
        if X2 is None:
            X2 = 1 - canv.GetRightMargin() * 0.70
        if Y1 is None:
            Y1 = canv.GetBottomMargin()
        if Y2 is None:
            Y2 = 1 - canv.GetTopMargin()

    suffix = ""
    if isNDC:
        suffix = "NDC"

    if X1 is not None:
        getattr(palette, "SetX1" + suffix)(X1)
    if X2 is not None:
        getattr(palette, "SetX2" + suffix)(X2)
    if Y1 is not None:
        getattr(palette, "SetY1" + suffix)(Y1)
    if Y2 is not None:
        getattr(palette, "SetY2" + suffix)(Y2)

This is a method to draw the CMS logo (that should be set using the corresponding method or on the fly) in a TPad set at the indicated location of the currently used TPad.

Parameters:

Name Type Description Default
canv TCanvas

CMSCanvas that needs to be used to plot the CMSLogo.

required
x0 float

X position (in relative dimensions) of the lower-left corner of the logo

required
y0 float

Y position (in relative dimensions) of the lower-left corner of the logo.

required
x1 float

X position (in relative dimensions) of the upper-left corner of the logo.

required
y1 floar

Y position (in relative dimensions) of the upper-left corner of the logo.

required
logofile (str, optional)

filename (with path) for the logo picture (see SetCmsLogoFilename for details)

None
Source code in src/cmsstyle/cmsstyle.py
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
def addCmsLogo(canv, x0, y0, x1, y1, logofile=None):
    """This is a method to draw the CMS logo (that should be set using the
    corresponding method or on the fly) in a TPad set at the indicated location
    of the currently used TPad.

    Args:
        canv (TCanvas): CMSCanvas that needs to be used to plot the CMSLogo.
        x0 (float): X position (in relative dimensions) of the lower-left corner of the logo
        y0 (float): Y position (in relative dimensions) of the lower-left corner of the logo.
        x1 (float): X position (in relative dimensions) of the upper-left corner of the logo.
        y1 (floar): Y position (in relative dimensions) of the upper-left corner of the logo.
        logofile (str,optional): filename (with path) for the logo picture (see SetCmsLogoFilename for details)
    """

    if logofile is not None:
        SetCmsLogoFilename(logofile)  # Trying to load the picture file!

    if len(useCmsLogo) == 0:
        print(
            "ERROR: Not possible to add the CMS Logo as the file is not properly defined (not found?)"
        )
        return

    # Checking we actually have a TCanvas:

    if canv.Class().GetName() != "TCanvas":  # For now reporting an error!
        print(
            "ERROR: You cannot use a picture for the CMS logo if you do not provide a TCanvas for the plot"
        )
        return

    # Addint a TPad with the picture!

    CMS_logo = rt.TASImage(useCmsLogo)

    oldpad = rt.gPad

    pad_logo = rt.TPad("logo", "logo", x0, y0, x1, y1)
    pad_logo.Draw()
    pad_logo.cd()
    CMS_logo.Draw("X")
    pad_logo.Modified()

    oldpad.cd()
    UpdatePad()  # For gPad

addToLegend(leg, *objs)

Add to the given TLegend the indicated elements (tuples or lists with references to ROOT TObjects and the information required by the TLegend).

Written by O. Gonzalez. Args: leg (ROOT.TLegend): The legend to add the elements to. *objs: any number of arguments with a tuple or list with three elements each, being (ROOT.TObject,str,str) where the first is the TObject to add, the second the label for the TLegend and the third the identifier for the legend.

Source code in src/cmsstyle/cmsstyle.py
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
def addToLegend(leg, *objs):
    """
    Add to the given TLegend the indicated elements (tuples or lists with references to ROOT
    TObjects and the information required by the TLegend).

    Written by O. Gonzalez.
    Args:
        leg (ROOT.TLegend): The legend to add the elements to.
        *objs: any number of arguments with a tuple or list with three elements each,
               being (ROOT.TObject,str,str) where the first is the TObject to add,
               the second the label for the TLegend and the third the identifier for the legend.
    """

    # We simply loop over the elements to

    for xobj in objs:
        leg.AddEntry(*xobj)  # Same as leg.AddEntry(xobj[0],xobj[1],xobj[2])

buildAndDrawTHStack(objs, leg, reverseleg=True, colorlist=None, stackopt='STACK', **kwargs)

This method allows to build and draw a THStack with a single command.

Basically it reduces to a single command the calls to buildTHStack, to addToLegend and to cmsObjectDraw for the most common case.

Examples of use:

hs = cmsstyle.buildAndDrawTHStack([(h2,"Sample 2",'f'),
                                    (h1,"Sample 1",'f'),
                                   (hg,"Sample G",'f')],
                                  plotlegend,True,[cmsstyle.p10.kBrown,cmsstyle.p10.kBlue,cmsstyle.p10.kOrange],"STACK")

Written by O. Gonzalez.

Parameters:

Name Type Description Default
objs list/tuple of (ROOT.TH1,str,str) tuples

list of objects, organized as tuples containing each of histograms to be added to the THStack with its label and option for the legend.

required
leg TLegend

legend to which the THStack members may be added.

required
reverseleg bool

whether elements should be added to the legend in reverse order.

True
colorlist list / tuple

list of colors to be used as the color for each histogram.

None
stackopt (str, optional)

option to define the THStack.

'STACK'
**kwargs ROOT styling object

Parameter names correspond to object styling method and arguments correspond to stilying ROOT objects: e.g. SetLineColor=ROOT.kRed. A method starting with "Set" may omite the "Set" part: i.e. LineColor=ROOT.kRed.

{}

Returns:

Type Description

ROOT.THStack: the created THStack.

Source code in src/cmsstyle/cmsstyle.py
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
def buildAndDrawTHStack(
    objs, leg, reverseleg=True, colorlist=None, stackopt="STACK", **kwargs
):
    """This method allows to build and draw a THStack with a single command.

    Basically it reduces to a single command the calls to buildTHStack, to
    addToLegend and to cmsObjectDraw for the most common case.

    Examples of use:

        hs = cmsstyle.buildAndDrawTHStack([(h2,"Sample 2",'f'),
                                            (h1,"Sample 1",'f'),
                                           (hg,"Sample G",'f')],
                                          plotlegend,True,[cmsstyle.p10.kBrown,cmsstyle.p10.kBlue,cmsstyle.p10.kOrange],"STACK")


    Written by O. Gonzalez.

    Args:
        objs (list/tuple of (ROOT.TH1,str,str) tuples): list of objects, organized as
             tuples containing each of histograms to be added to the THStack with its
             label and option for the legend.
        leg (ROOT.TLegend): legend to which the THStack members may be added.
        reverseleg (bool, optional): whether elements should be added to the legend in reverse order.
        colorlist (list/tuple, optional): list of colors to be used as the color for each histogram.
        stackopt (str,optional): option to define the THStack.
        **kwargs (ROOT styling object, optional): Parameter names correspond to
                  object styling method and arguments correspond to stilying ROOT objects:
                  e.g. `SetLineColor=ROOT.kRed`. A method starting with "Set" may omite the
                  "Set" part: i.e. `LineColor=ROOT.kRed`.

    Returns:
        ROOT.THStack: the created THStack.
    """

    # We get a list with the histogram!
    histlist = [x[0] for x in objs]

    hs = buildTHStack(histlist, colorlist, stackopt, **kwargs)

    # We add the histograms to the legend... perhaps looping in reverse order!
    if reverseleg:
        for xobj in reversed(objs):
            leg.AddEntry(*xobj)
    else:
        for xobj in objs:
            leg.AddEntry(*xobj)

    cmsObjectDraw(hs, "")  # Also drawing it!

    return hs

buildTHStack(histlist, colorlist=None, opt='STACK', **kwargs)

This method allows to build a THStack out of a list of histograms and configure at the same time the colors to be used with each histogram and some possible general configurations.

Examples of use:

hs = cmsstyle.buildTHStack([h1,h2,hg])

hs = cmsstyle.buildTHStack([h1,h2,hg],[cmsstyle.p10.kBrown,cmsstyle.p10.kBlue,cmsstyle.p10.kOrange],"STACK",FillStyle=3005,FillColor=-1,LineColor=-1)

Written by O. Gonzalez.

Parameters:

Name Type Description Default
histlist list / tuple

list of histograms to add in order to the THStack to be built!

required
colorlist list / tuple

list of colors to be used as the color for each histogram

None
opt (str, optional)

option to be used to create the THStack.

'STACK'
**kwargs ROOT styling object

Parameter names correspond to object styling method and arguments correspond to stilying ROOT objects: e.g. SetLineColor=ROOT.kRed. A method starting with "Set" may omite the "Set" part: i.e. LineColor=ROOT.kRed. Note that any color style that is to be changed is adapted in a "per-histogram" mode. Also check the default below! (to avois the default, use NoDefault=None)

{}

Returns:

Type Description

ROOT.THStack: the created THStack.

Source code in src/cmsstyle/cmsstyle.py
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
def buildTHStack(histlist, colorlist=None, opt="STACK", **kwargs):
    """This method allows to build a THStack out of a list of histograms and
    configure at the same time the colors to be used with each histogram and
    some possible general configurations.

    Examples of use:

        hs = cmsstyle.buildTHStack([h1,h2,hg])

        hs = cmsstyle.buildTHStack([h1,h2,hg],[cmsstyle.p10.kBrown,cmsstyle.p10.kBlue,cmsstyle.p10.kOrange],"STACK",FillStyle=3005,FillColor=-1,LineColor=-1)

    Written by O. Gonzalez.

    Args:
        histlist (list/tuple): list of histograms to add in order to the THStack to be built!
        colorlist (list/tuple, optional): list of colors to be used as the color for each histogram
        opt (str,optional): option to be used to create the THStack.

        **kwargs (ROOT styling object, optional): Parameter names correspond to
                  object styling method and arguments correspond to stilying ROOT objects:
                  e.g. `SetLineColor=ROOT.kRed`. A method starting with "Set" may omite the
                  "Set" part: i.e. `LineColor=ROOT.kRed`.
                  Note that any color style that is to be changed is adapted in a "per-histogram"
                  mode. Also check the default below! (to avois the default, use NoDefault=None)

    Returns:
        ROOT.THStack: the created THStack.
    """

    if opt is None or len(opt) == 0:
        opt = "STACK"  # The default for using "" or None!

    hstack = rt.THStack("hstack", opt)

    if len(kwargs) == 0:  # If no configuration arguments, we use a default!
        kwargs["FillColor"] = -1  # The colors list is used!
        kwargs["FillStyle"] = 1001

    elif "NoDefault" in kwargs:
        kwargs.clear()  # Nothing is used!

    # If the provided color list is not useful, we get one from Pettroff's sets
    ncolors = 0 if colorlist is None else len(colorlist)
    if ncolors == 0 and len(histlist) > 0:
        # Need to build a set of colors from Petroff's sets!
        ncolors = len(histlist)
        colorlist = getPettroffColorSet(ncolors)

    # Looping over the histograms to generate the THStack

    ihst = 0
    for xhst in histlist:
        # We may modify the histogram... indeed it should be given! When no
        # argument is given, we use FillColor by default for stack histograms
        # (see values for default above inb the code!)

        for xcnf in kwargs.items():
            if xcnf[0] == "SetLineColor" or xcnf[0] == "LineColor":
                xhst.SetLineColor(
                    colorlist[ihst]
                )  # NOTE: FOR THE COLOR WE USE THE VECTOR!
            elif xcnf[0] == "SetFillColor" or xcnf[0] == "FillColor":
                xhst.SetFillColor(colorlist[ihst])
            elif xcnf[0] == "SetMarkerColor" or xcnf[0] == "MarkerColor":
                xhst.SetMarkerColor(colorlist[ihst])

            else:
                setRootObjectProperties(xhst, **{xcnf[0]: xcnf[1]})

        # Adding it!
        hstack.Add(xhst)
        ihst += 1

    return hstack

changeStatsBox(canv, ipos_x1=None, y1pos=None, x2pos=None, y2pos=None, **kwargs)

This method allows to obtain the StatsBox from the given Canvas and modify its position and, additionally, modify its properties using named keywords arguments.

Written by O. Gonzalez.

The ipos_x0 may be set to a numeric value in NDC coordinates OR a predefined position using a string of the following:

    'tr' -> Drawn in the Top-Right part of the frame including the plot.
    'tl' -> Drawn in the Top-Left part of the frame including the plot.
    'br' -> Drawn in the Bottom-Right part of the frame including the plot.
    'bl' -> Drawn in the Bottom-Left part of the frame including the plot.

In this case the second coordinate may be used to scale the x-dimension (for readability), and the third may be used to scale the y-dimension (usually not needed)

Examples of use:

    cmsstyle.changeStatsBox(canv,'tr',FillColor=ROOT.kRed,FillStyle=3555)
    cmsstyle.changeStatsBox(canv,'tl',SetTextColor=ROOT.kRed,SetFontSize=0.03)
    cmsstyle.changeStatsBox(canv,'tl',1.2,SetTextColor=ROOT.kRed,SetFontSize=0.03)

(A method starting with "Set" may omite the "Set" part)

Parameters:

Name Type Description Default
canv TCanvas or TPaveStats

canvas to which we modify the stats box (or directly the TPaveStats to change)

required
ipos_x1 str or float

position for the stats box. Use a predefined string of a location or an NDC x coordinate number

None
y1pos float

NDC y coordinate number or a factor to scale the width of the box when using a predefined location.

None
x2pos float

NDC x coordinate number or a factor to scale the height of the box when using a predefined location.

None
y2pos float

NDC y coordinate number or ignored value.

None
**kwargs

Arbitrary keyword arguments for mofifying the properties of the stats box using Set methods or similar.

{}

Returns:

Type Description

The Stats Box so it may be access externally.

Source code in src/cmsstyle/cmsstyle.py
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
def changeStatsBox(canv, ipos_x1=None, y1pos=None, x2pos=None, y2pos=None, **kwargs):
    """This method allows to obtain the StatsBox from the given Canvas and modify
    its position and, additionally, modify its properties using named keywords
    arguments.

    Written by O. Gonzalez.

    The ipos_x0 may be set to a numeric value in NDC coordinates OR a
    predefined position using a string of the following:

            'tr' -> Drawn in the Top-Right part of the frame including the plot.
            'tl' -> Drawn in the Top-Left part of the frame including the plot.
            'br' -> Drawn in the Bottom-Right part of the frame including the plot.
            'bl' -> Drawn in the Bottom-Left part of the frame including the plot.

    In this case the second coordinate may be used to scale the x-dimension
    (for readability), and the third may be used to scale the y-dimension (usually not needed)

    Examples of use:

            cmsstyle.changeStatsBox(canv,'tr',FillColor=ROOT.kRed,FillStyle=3555)
            cmsstyle.changeStatsBox(canv,'tl',SetTextColor=ROOT.kRed,SetFontSize=0.03)
            cmsstyle.changeStatsBox(canv,'tl',1.2,SetTextColor=ROOT.kRed,SetFontSize=0.03)

    (A method starting with "Set" may omite the "Set" part)

    Args:
        canv (ROOT.TCanvas or ROOT.TPaveStats): canvas to which we modify the stats box (or directly the TPaveStats to change)
        ipos_x1 (str or float): position for the stats box. Use a predefined string of a location or an NDC x coordinate number
        y1pos (float): NDC y coordinate number or a factor to scale the width of the box when using a predefined location.
        x2pos (float): NDC x coordinate number or a factor to scale the height of the box when using a predefined location.
        y2pos (float): NDC y coordinate number or ignored value.
        **kwargs: Arbitrary keyword arguments for mofifying the properties of the stats box using Set methods or similar.

    Returns:
        The Stats Box so it may be access externally.
    """

    stbox = canv
    if canv.Class().GetName() != "TPaveStats":  # Very likely a TPad or TCanvas
        canv.Update()  # To be sure we have created the statistic box
        stbox = canv.GetPrimitive("stats")

        if stbox.Class().GetName() != "TPaveStats":
            raise ReferenceError(
                'ERROR: Trying to change the StatsBox when it has not been enabled... activate it with SetOptStat (and use "SAMES" or equivalent)'
            )

    setRootObjectProperties(stbox, **kwargs)

    # We may change the position... first chosing how:
    if isinstance(ipos_x1, str):
        # When we deal with a TPaveStats directly we should have real coordinates, not the predefined strings.
        if canv.Class().GetName() == "TPaveStats":
            raise TypeError(
                "ERROR: When proving a TPaveStats to changeStatsBox the coordinates should be numbers"
            )

        a = ipos_x1.lower()
        x = None
        # The size may be modified depending on the text size. Note that the text
        # size is 0, it is adapted to the box size (I think)
        textsize = (
            0 if (stbox.GetTextSize() == 0) else 6 * (stbox.GetTextSize() - 0.025)
        )
        xsize = (1 - canv.GetRightMargin() - canv.GetLeftMargin()) * (
            1 if y1pos is None else y1pos
        )  # Note these parameters looses their "x"-"y" nature.
        ysize = (1 - canv.GetBottomMargin() - canv.GetTopMargin()) * (
            1 if x2pos is None else x2pos
        )

        yfactor = 0.05 + 0.05 * stbox.GetListOfLines().GetEntries()

        if a == "tr":
            x = {
                "SetX1NDC": 1 - canv.GetRightMargin() - xsize * 0.33 - textsize,
                "SetY1NDC": 1 - canv.GetTopMargin() - ysize * yfactor - textsize,
                "SetX2NDC": 1 - canv.GetRightMargin() - xsize * 0.03,
                "SetY2NDC": 1 - canv.GetTopMargin() - ysize * 0.03,
            }
        elif a == "tl":
            x = {
                "SetX1NDC": canv.GetLeftMargin() + xsize * 0.03,
                "SetY1NDC": 1 - canv.GetTopMargin() - ysize * yfactor - textsize,
                "SetX2NDC": canv.GetLeftMargin() + xsize * 0.33 + textsize,
                "SetY2NDC": 1 - canv.GetTopMargin() - ysize * 0.03,
            }
        elif a == "bl":
            x = {
                "SetX1NDC": canv.GetLeftMargin() + xsize * 0.03,
                "SetY1NDC": canv.GetBottomMargin() + ysize * 0.03,
                "SetX2NDC": canv.GetLeftMargin() + xsize * 0.33 + textsize,
                "SetY2NDC": canv.GetBottomMargin() + ysize * yfactor + textsize,
            }
        elif a == "br":
            x = {
                "SetX1NDC": 1 - canv.GetRightMargin() - xsize * 0.33 - textsize,
                "SetY1NDC": canv.GetBottomMargin() + ysize * 0.03,
                "SetX2NDC": 1 - canv.GetRightMargin() - xsize * 0.03,
                "SetY2NDC": canv.GetBottomMargin() + ysize * yfactor + textsize,
            }

        if x is None:
            print(
                "ERROR: Invalid code provided to position the statistics box: {ipos_x1}".format(
                    ipos_x1=ipos_x1
                )
            )
        else:
            for xkey, xval in x.items():
                getattr(stbox, xkey)(xval)

    else:  # We change the values that are not None
        for xkey, xval in {
            "ipos_x1": "SetX1NDC",
            "y1pos": "SetY1NDC",
            "x2pos": "SetX2NDC",
            "y2pos": "SetY2NDC",
        }.items():
            x = locals()[xkey]
            if x is not None:
                getattr(stbox, xval)(x)

    UpdatePad(canv)  # To update the TCanvas or TPad.

    return stbox

cmsCanvas(canvName, x_min, x_max, y_min, y_max, nameXaxis, nameYaxis, square=True, iPos=11, extraSpace=0, with_z_axis=False, scaleLumi=1, yTitOffset=None)

Create a canvas with CMS style and predefined axis labels.

Parameters:

Name Type Description Default
canvName str

The name of the canvas.

required
x_min float

The minimum value of the x-axis.

required
x_max float

The maximum value of the x-axis.

required
y_min float

The minimum value of the y-axis.

required
y_max float

The maximum value of the y-axis.

required
nameXaxis str

The label for the x-axis.

required
nameYaxis str

The label for the y-axis.

required
square bool

Whether to create a square canvas. Defaults to True.

True
iPos int

The position of the CMS logo. Defaults to 11 (top-left, left-aligned). Alternatives are 33 (top-right, right-aligned), 22 (center, centered) and 0 (out of frame, in exceptional cases). Position is calculated as 10*(alignment 1/2/3) + position (1/2/3 = l/c/r).

11
extraSpace float

Additional space to add to the left margin to fit labels. Defaults to 0.

0
with_z_axis bool

Whether to include a z-axis for 2D histograms. Defaults to False.

False
scaleLumi float

Scale factor for the luminosity text size. Default is 1.0 indicating no scale

1
yTitOffset float

Set the value for the Y-axis title offset in case default is not good. [Added by O. Gonzalez]

None

Returns:

Type Description

ROOT.TCanvas (ROOT.TCanvas): The created canvas.

Source code in src/cmsstyle/cmsstyle.py
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
def cmsCanvas(
    canvName,
    x_min,
    x_max,
    y_min,
    y_max,
    nameXaxis,
    nameYaxis,
    square=True,
    iPos=11,
    extraSpace=0,
    with_z_axis=False,
    scaleLumi=1,
    yTitOffset=None,
):
    """
    Create a canvas with CMS style and predefined axis labels.

    Args:
        canvName (str): The name of the canvas.
        x_min (float): The minimum value of the x-axis.
        x_max (float): The maximum value of the x-axis.
        y_min (float): The minimum value of the y-axis.
        y_max (float): The maximum value of the y-axis.
        nameXaxis (str): The label for the x-axis.
        nameYaxis (str): The label for the y-axis.
        square (bool, optional): Whether to create a square canvas. Defaults to True.
        iPos (int, optional): The position of the CMS logo. Defaults to 11 (top-left, left-aligned). Alternatives are 33 (top-right, right-aligned), 22 (center, centered) and 0 (out of frame, in exceptional cases). Position is calculated as 10*(alignment 1/2/3) + position (1/2/3 = l/c/r).
        extraSpace (float, optional): Additional space to add to the left margin to fit labels. Defaults to 0.
        with_z_axis (bool, optional): Whether to include a z-axis for 2D histograms. Defaults to False.
        scaleLumi (float, optional): Scale factor for the luminosity text size. Default is 1.0 indicating no scale
        yTitOffset (float, optional): Set the value for the Y-axis title offset in case default is not good. [Added by O. Gonzalez]

    Returns:
        ROOT.TCanvas (ROOT.TCanvas): The created canvas.
    """

    # Set CMS style if not set already.
    if cmsStyle is None:
        setCMSStyle()

    # Set canvas dimensions and margins
    W_ref = 600 if square else 800
    H_ref = 600 if square else 600

    W = W_ref
    H = H_ref
    T = 0.07 * H_ref
    B = 0.125 * H_ref  # Changing this to allow more space in X-title (i.e. subscripts)
    L = 0.145 * H_ref   # Changing this to leave more space to the title
    R = 0.05 * H_ref  # Changing this to leave more space

    # The position of the y-axis title may also change a bit the plot:
    if yTitOffset is None:
        y_offset = 1.2 if square else 0.78  # Changed to fitting larger font
    else:
        y_offset = yTitOffset

    if (y_offset < 1.5):
        L += y_offset*50-60  # Some adjustment
    elif (y_offset < 1.8):
        L += (y_offset - 1.4)*35+25

    canv = rt.TCanvas(canvName, canvName, 50, 50, W, H)
    canv.SetFillColor(0)
    canv.SetBorderMode(0)
    canv.SetFrameFillStyle(0)
    canv.SetFrameBorderMode(0)
    canv.SetLeftMargin(L / W + extraSpace)
    canv.SetRightMargin(R / W)
    if with_z_axis:
        canv.SetRightMargin(B / W + 0.03)
    canv.SetTopMargin(T / H)
    canv.SetBottomMargin(B / H + 0.02)

    # Draw frame and set axis labels
    h = canv.DrawFrame(x_min, y_min, x_max, y_max)

    h.GetYaxis().SetTitleOffset(y_offset)
    h.GetXaxis().SetTitleOffset(1.05)  # Changed to fitting larger font
    h.GetXaxis().SetTitle(nameXaxis)
    h.GetYaxis().SetTitle(nameYaxis)
    h.Draw("AXIS")

    # Draw CMS logo and update canvas
    CMS_lumi(canv, iPos, scaleLumi=scaleLumi)
    UpdatePad(canv)
    canv.RedrawAxis()
    canv.GetFrame().Draw()
    return canv

cmsCanvasResetAxes(canv, x_min, x_max, y_min, y_max)

Reset the axis ranges of a canvas created with cmsCanvas.

Parameters:

Name Type Description Default
canv TCanvas

The canvas to reset the axis ranges for.

required
x_min float

The minimum value of the x-axis.

required
x_max float

The maximum value of the x-axis.

required
y_min float

The minimum value of the y-axis.

required
y_max float

The maximum value of the y-axis.

required
Source code in src/cmsstyle/cmsstyle.py
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
def cmsCanvasResetAxes(canv, x_min, x_max, y_min, y_max):
    """
    Reset the axis ranges of a canvas created with cmsCanvas.

    Args:
        canv (ROOT.TCanvas): The canvas to reset the axis ranges for.
        x_min (float): The minimum value of the x-axis.
        x_max (float): The maximum value of the x-axis.
        y_min (float): The minimum value of the y-axis.
        y_max (float): The maximum value of the y-axis.
    """
    GetCmsCanvasHist(canv).GetXaxis().SetRangeUser(x_min, x_max)
    GetCmsCanvasHist(canv).GetYaxis().SetRangeUser(y_min, y_max)

cmsDiCanvas(canvName, x_min, x_max, y_min, y_max, r_min, r_max, nameXaxis, nameYaxis, nameRatio, square=True, iPos=11, extraSpace=0, scaleLumi=1)

Create a canvas with CMS style and predefined axis labels, with a ratio pad.

Parameters:

Name Type Description Default
canvName str

The name of the canvas.

required
x_min float

The minimum value of the x-axis.

required
x_max float

The maximum value of the x-axis.

required
y_min float

The minimum value of the y-axis.

required
y_max float

The maximum value of the y-axis.

required
r_min float

The minimum value of the ratio axis.

required
r_max float

The maximum value of the ratio axis.

required
nameXaxis str

The label for the x-axis.

required
nameYaxis str

The label for the y-axis.

required
nameRatio str

The label for the ratio axis.

required
square bool

Whether to create a square canvas. Defaults to True.

True
iPos int

The position of the CMS text. Defaults to 11 (top-left, left-aligned).

11
extraSpace float

Additional space to add to the left margin to fit labels. Defaults to 0.

0
scaleLumi float

Scale factor for the luminosity text size. Default is 1 that means no scaling.

1

Returns:

Type Description

ROOT.TCanvas: The created canvas.

Source code in src/cmsstyle/cmsstyle.py
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
def cmsDiCanvas(
    canvName,
    x_min,
    x_max,
    y_min,
    y_max,
    r_min,
    r_max,
    nameXaxis,
    nameYaxis,
    nameRatio,
    square=True,
    iPos=11,
    extraSpace=0,
    scaleLumi=1,
):
    """
    Create a canvas with CMS style and predefined axis labels, with a ratio pad.

    Args:
        canvName (str): The name of the canvas.
        x_min (float): The minimum value of the x-axis.
        x_max (float): The maximum value of the x-axis.
        y_min (float): The minimum value of the y-axis.
        y_max (float): The maximum value of the y-axis.
        r_min (float): The minimum value of the ratio axis.
        r_max (float): The maximum value of the ratio axis.
        nameXaxis (str): The label for the x-axis.
        nameYaxis (str): The label for the y-axis.
        nameRatio (str): The label for the ratio axis.
        square (bool, optional): Whether to create a square canvas. Defaults to True.
        iPos (int, optional): The position of the CMS text. Defaults to 11 (top-left, left-aligned).
        extraSpace (float, optional): Additional space to add to the left margin to fit labels. Defaults to 0.
        scaleLumi (float, optional): Scale factor for the luminosity text size. Default is 1 that means no scaling.

    Returns:
        ROOT.TCanvas: The created canvas.
    """

    # Set CMS style if not set
    if cmsStyle is None:
        setCMSStyle()

    # Set canvas dimensions and margins
    W_ref = 700 if square else 800
    H_ref = 600 if square else 500
    # Set bottom pad relative height and relative margin
    F_ref = 1.0 / 3.0
    M_ref = 0 # 0.03
    # Set reference margins
    T_ref = 0.07
    B_ref = 0.13
    L = 0.15 if square else 0.12
    R = 0.05
    # Calculate total canvas size and pad heights
    W = W_ref
    H = int(H_ref * (1 + (1 - T_ref - B_ref) * F_ref + M_ref))
    Hup = H_ref * (1 - B_ref)
    Hdw = H - Hup
    # references for T, B, L, R
    Tup = T_ref * H_ref / Hup
    Tdw = M_ref * H_ref / Hdw
    Bup = 0.015 # 0.022
    Bdw = 0.365 # B_ref * H_ref / Hdw

    canv = rt.TCanvas(canvName, canvName, 50, 50, W, H)
    canv.SetFillColor(0)
    canv.SetBorderMode(0)
    canv.SetFrameFillStyle(0)
    canv.SetFrameBorderMode(0)
    canv.SetFrameLineColor(0)
    canv.SetFrameLineWidth(0)
    canv.Divide(1, 2)

    canv.cd(1)
    rt.gPad.SetPad(0, Hdw / H, 1, 1)
    rt.gPad.SetLeftMargin(L)
    rt.gPad.SetRightMargin(R)
    rt.gPad.SetTopMargin(Tup)
    rt.gPad.SetBottomMargin(Bup)

    hup = canv.cd(1).DrawFrame(x_min, y_min, x_max, y_max)
    hup.GetYaxis().SetTitleOffset(extraSpace + (1.1 if square else 0.9) * Hup / H_ref)
    hup.GetXaxis().SetTitleOffset(999)
    hup.GetXaxis().SetLabelOffset(999)
    hup.SetTitleSize(hup.GetTitleSize("Y") * H_ref / Hup, "Y")
    hup.SetLabelSize(hup.GetLabelSize("Y") * H_ref / Hup, "Y")
    hup.GetYaxis().SetTitle(nameYaxis)

    CMS_lumi(rt.gPad, iPos, scaleLumi=scaleLumi)

    canv.cd(2)
    rt.gPad.SetPad(0, 0, 1, Hdw / H)
    rt.gPad.SetLeftMargin(L)
    rt.gPad.SetRightMargin(R)
#    rt.gPad.SetTopMargin(Tdw)
    rt.gPad.SetBottomMargin(Bdw)
    rt.gPad.SetTopMargin(0)

    hdw = canv.cd(2).DrawFrame(x_min, r_min, x_max, r_max)
    # Scale text sizes and margins to match normal size
    hdw.GetYaxis().SetTitleOffset(extraSpace + (1.0 if square else 0.8) * Hdw / H_ref)
    hdw.GetXaxis().SetTitleOffset(1.1)
    hdw.SetTitleSize(hdw.GetTitleSize("Y") * H_ref / Hdw, "Y")
    hdw.SetLabelSize(hdw.GetLabelSize("Y") * H_ref / Hdw, "Y")
    hdw.SetTitleSize(hdw.GetTitleSize("X") * H_ref / Hdw, "X")
    hdw.SetLabelSize(hdw.GetLabelSize("X") * H_ref / Hdw, "X")
    hdw.SetLabelOffset(hdw.GetLabelOffset("X") * H_ref / Hdw, "X")
    hdw.GetXaxis().SetTitle(nameXaxis)
    hdw.GetYaxis().SetTitle(nameRatio)

    # Set tick lengths to match original (these are fractions of axis length)
    hdw.SetTickLength(hdw.GetTickLength("Y") * H_ref / Hup, "Y")  # ?? ok if 1/3
    hdw.SetTickLength(hdw.GetTickLength("X") * H_ref / Hdw, "X")

    # Reduce divisions to match smaller height (default n=510, optim=kTRUE)
    hdw.GetYaxis().SetNdivisions(505)
    hdw.Draw("AXIS")
    canv.cd(1)
    UpdatePad(canv.cd(1))
    canv.cd(1).RedrawAxis()
    canv.cd(1).GetFrame().Draw()
    return canv

cmsDraw(h, style, marker=rt.kFullCircle, msize=1.0, mcolor=rt.kBlack, lstyle=rt.kSolid, lwidth=1, lcolor=-1, fstyle=1001, fcolor=rt.kYellow + 1, alpha=-1)

Draw a histogram with CMS style.

Parameters:

Name Type Description Default
h TH1 or TH2

The histogram to draw.

required
style str

The drawing style (e.g., "HIST", "P", etc.).

required
marker int

The marker style. Defaults to kFullCircle.

kFullCircle
msize float

The marker size. Defaults to 1.0.

1.0
mcolor int

The marker color. Defaults to kBlack.

kBlack
lstyle int

The line style. Defaults to kSolid.

kSolid
lwidth int

The line width. Defaults to 1.

1
lcolor int

The line color. If -1, uses the marker color. Defaults to -1.

-1
fstyle int

The fill style. Defaults to 1001 (solid).

1001
fcolor int

The fill color. Defaults to kYellow+1.

kYellow + 1
alpha float

The transparency value for the fill color (0-1). If -1, uses the default transparency. Defaults to -1.

-1
Source code in src/cmsstyle/cmsstyle.py
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
def cmsDraw(
    h,
    style,
    marker=rt.kFullCircle,
    msize=1.0,
    mcolor=rt.kBlack,
    lstyle=rt.kSolid,
    lwidth=1,
    lcolor=-1,
    fstyle=1001,
    fcolor=rt.kYellow + 1,
    alpha=-1,
):
    """
    Draw a histogram with CMS style.

    Args:
        h (ROOT.TH1 or ROOT.TH2): The histogram to draw.
        style (str): The drawing style (e.g., "HIST", "P", etc.).
        marker (int, optional): The marker style. Defaults to kFullCircle.
        msize (float, optional): The marker size. Defaults to 1.0.
        mcolor (int, optional): The marker color. Defaults to kBlack.
        lstyle (int, optional): The line style. Defaults to kSolid.
        lwidth (int, optional): The line width. Defaults to 1.
        lcolor (int, optional): The line color. If -1, uses the marker color. Defaults to -1.
        fstyle (int, optional): The fill style. Defaults to 1001 (solid).
        fcolor (int, optional): The fill color. Defaults to kYellow+1.
        alpha (float, optional): The transparency value for the fill color (0-1). If -1, uses the default transparency. Defaults to -1.
    """
    h.SetMarkerStyle(marker)
    h.SetMarkerSize(msize)
    h.SetMarkerColor(mcolor)
    h.SetLineStyle(lstyle)
    h.SetLineWidth(lwidth)
    h.SetLineColor(mcolor if lcolor == -1 else lcolor)
    h.SetFillStyle(fstyle)
    h.SetFillColor(fcolor)
    if alpha > 0:
        h.SetFillColorAlpha(fcolor, alpha)

    # We expect this command to be used with an alreasdy-defined canvas.
    prefix = "SAME"
    if "SAME" in style:
        prefix = ""

    h.Draw(prefix + style)

cmsDrawLine(line, lcolor=rt.kRed, lstyle=rt.kSolid, lwidth=2)

Draw a line with CMS style.

Parameters:

Name Type Description Default
line TLine

The line to draw.

required
lcolor int

The line color. Defaults to kRed.

kRed
lstyle int

The line style. Defaults to kSolid.

kSolid
lwidth int

The line width. Defaults to 2.

2
Source code in src/cmsstyle/cmsstyle.py
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
def cmsDrawLine(line, lcolor=rt.kRed, lstyle=rt.kSolid, lwidth=2):
    """
    Draw a line with CMS style.

    Args:
        line (ROOT.TLine): The line to draw.
        lcolor (int, optional): The line color. Defaults to kRed.
        lstyle (int, optional): The line style. Defaults to kSolid.
        lwidth (int, optional): The line width. Defaults to 2.
    """
    line.SetLineStyle(lstyle)
    line.SetLineColor(lcolor)
    line.SetLineWidth(lwidth)
    line.Draw("SAME")

cmsGrid(gridOn)

Enable or disable the grid mode in the CMSStyle. It could also be done by calling the corresponding methods for ROOT.gStyle after setting the style.

Parameters:

Name Type Description Default
gridOn bool

To indicate whether to sets or unset the Grid on the CMSStyle.

required
Source code in src/cmsstyle/cmsstyle.py
606
607
608
609
610
611
612
613
614
615
616
617
618
619
def cmsGrid(gridOn):
    """
    Enable or disable the grid mode in the CMSStyle. It could also be done by
    calling the corresponding methods for ROOT.gStyle after setting the style.

    Args:
        gridOn (bool): To indicate whether to sets or unset the Grid on the CMSStyle.
    """

    if cmsStyle is not None:
        cmsStyle.SetPadGridX(gridOn)
        cmsStyle.SetPadGridY(gridOn)
    else:
        print("ERROR: You should set the CMS Style before calling cmsGrid")

cmsHeader(leg, legTitle, textAlign=12, textSize=0.04, textFont=42, textColor=rt.kBlack, isToRemove=True)

Add a header to a legend with CMS style.

Parameters:

Name Type Description Default
leg TLegend

The legend to add the header to.

required
legTitle str

The title of the header.

required
textAlign int

The alignment of the header text. Defaults to 12 (centered).

12
textSize float

The text size of the header. Defaults to 0.04.

0.04
textFont int

The font of the header. Defaults to 42 (helvetica).

42
textColor int

The color of the header. Defaults to kBlack.

kBlack
isToRemove bool

Whether to remove the default header and replace it with the new one. Defaults to True.

True
Source code in src/cmsstyle/cmsstyle.py
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
def cmsHeader(
    leg,
    legTitle,
    textAlign=12,
    textSize=0.04,
    textFont=42,
    textColor=rt.kBlack,
    isToRemove=True,
):
    """
    Add a header to a legend with CMS style.

    Args:
        leg (ROOT.TLegend): The legend to add the header to.
        legTitle (str): The title of the header.
        textAlign (int, optional): The alignment of the header text. Defaults to 12 (centered).
        textSize (float, optional): The text size of the header. Defaults to 0.04.
        textFont (int, optional): The font of the header. Defaults to 42 (helvetica).
        textColor (int, optional): The color of the header. Defaults to kBlack.
        isToRemove (bool, optional): Whether to remove the default header and replace it with the new one. Defaults to True.
    """
    header = rt.TLegendEntry(0, legTitle, "h")
    header.SetTextFont(textFont)
    header.SetTextSize(textSize)
    header.SetTextAlign(textAlign)
    header.SetTextColor(textColor)
    if isToRemove:
        leg.SetHeader(legTitle, "C")
        leg.GetListOfPrimitives().Remove(leg.GetListOfPrimitives().At(0))
        leg.GetListOfPrimitives().AddAt(header, 0)
    else:
        leg.GetListOfPrimitives().AddLast(header)
    # ROOT >= 6.40 no longer drops Python ownership automatically for this case.
    # The entry is stored in the TLegend primitive list, so avoid Python GC deleting it.
    rt.SetOwnership(header, False)

cmsLeg(x1, y1, x2, y2, textSize=0.04, textFont=42, textColor=rt.kBlack, columns=None)

Create a legend with CMS style.

Parameters:

Name Type Description Default
x1 float

The left position of the legend in NDC (0-1).

required
y1 float

The bottom position of the legend in NDC (0-1).

required
x2 float

The right position of the legend in NDC (0-1).

required
y2 float

The top position of the legend in NDC (0-1).

required
textSize float

The text size of the legend entries. Defaults to 0.04.

0.04
textFont int

The font of the legend entries. Defaults to 42 (helvetica).

42
textColor int

The color of the legend entries. Defaults to kBlack.

kBlack
columns int

The number of columns in the legend.

None

Returns:

Type Description

ROOT.TLegend: The created legend.

Source code in src/cmsstyle/cmsstyle.py
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
def cmsLeg(
    x1, y1, x2, y2, textSize=0.04, textFont=42, textColor=rt.kBlack, columns=None
):
    """
    Create a legend with CMS style.

    Args:
        x1 (float): The left position of the legend in NDC (0-1).
        y1 (float): The bottom position of the legend in NDC (0-1).
        x2 (float): The right position of the legend in NDC (0-1).
        y2 (float): The top position of the legend in NDC (0-1).
        textSize (float, optional): The text size of the legend entries. Defaults to 0.04.
        textFont (int, optional): The font of the legend entries. Defaults to 42 (helvetica).
        textColor (int, optional): The color of the legend entries. Defaults to kBlack.
        columns (int, optional): The number of columns in the legend.

    Returns:
        ROOT.TLegend: The created legend.
    """
    leg = rt.TLegend(x1, y1, x2, y2, "", "brNDC")
    leg.SetTextSize(textSize)
    leg.SetTextFont(textFont)
    leg.SetTextColor(textColor)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    if columns:
        leg.SetNColumns(columns)
    leg.Draw()
    return leg

cmsMultiCanvas(canvName, nColumns, nRows, Xlimits, Ylimits, nameXaxis, nameYaxis, labelTextSize=50 * 0.8, titleTextSize=50, lumiTextSize=50, logoTextSize=50 * 0.75 / 0.6, legendTextSize=30, heightRatios=None, widthRatios=None, canvasTopMargin=0.1, canvasBottomMargin=0.03, canvasWidth=2000, canvasHeight=2000, iPos=0)

Create a plot with multiple pads arranged in a grid, with shared axes, common legend and CMS styling.

Parameters:

Name Type Description Default
canvName str

The name of the canvas.

required
nColumns int

number of columns in the grid

required
nRows int

number of rows in the grid

required
XLimits dict

dictionary containing X axis limits for all plots, with integer keys corresponding to left-to-right top-to-bottom numbering scheme, starting from 0, and a 2-element iterable value, containing x_min and x_max. e.g. {0: [0, 50000], 1: [1, 50000]}.

required
YLimits dict

dictionary containing Y axis limits for all plots, with integer keys corresponding to left-to-right top-to-bottom numbering scheme, starting from 0, and a 2-element iterable value, containing y_min and y_max. e.g. {0: [0, 50000], 1: [1, 50000]}.

required
nameXaxis str

the label for the x-axis.

required
nameYaxis dict

the label for the y-axis, in the form of a dict int:str with integer keys corresponding to left-to-right top-to-bottom numbering scheme, starting from 0. e.g. {0: "Y Label for 1st plot", 4: "Y Label for 5th plot"}

required
labelTextSize float

absolute value of textSize of axis labels (same for X and Y). Defaults to 50*0.8.

50 * 0.8
titleTextSize float

absolute value for textSize of axis titles (same for X and Y). Defaults to 50.

50
lumiTextSize float

absolute value for textSize of lumi text. Defaults to 50.

50
logoTextSize float

absolute value for textSize of CMS Logo, extraText is scaled accordingly. Defaults to 50 * 0.75 / 0.6.

50 * 0.75 / 0.6
legendTextSize float

Absolute value for text size of legend. Defaults to 30.

30
heightRatios list

list of weights for the relative heights of the pads along the columns. Length must be equal to nrows. Defaults to None, which means each plot gets the same height.

None
widthRatios list

list of weights for the relative widths of the pads along the rows. Length must be equal to ncolumns. Defaults to None, which means each plot gets the same width.

None
canvasTopMargin float

margin to remove starting from the top of the canvas to make space for the top pad. Defaults to 0.1.

0.1
canvasBottomMargin float

margin to remove starting from the bottom of the canvas to make space for the bottom pad. Defaults to 0.03.

0.03
canvasWidth float

total width of the canvas. Defaults to 2000.

2000
canvasHeight float

total height of the canvas. Defaults to 2000.

2000
iPos int

The position of the CMS text. 0 (outside of legend box) or 11 (top-left left-aligned inside legend box). Defaults to 11.

0

Returns:

Name Type Description
CMSCanvasManager

A object to handle the multipad grid.

Source code in src/cmsstyle/cmsstyle.py
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
def cmsMultiCanvas(
        canvName,
        nColumns,
        nRows,
        Xlimits,
        Ylimits,
        nameXaxis,
        nameYaxis,
        labelTextSize=50*0.8,
        titleTextSize=50,
        lumiTextSize=50,
        logoTextSize=50 * 0.75 / 0.6,
        legendTextSize=30,
        heightRatios=None,
        widthRatios=None,
        canvasTopMargin=0.1,
        canvasBottomMargin=0.03,
        canvasWidth=2000,
        canvasHeight=2000,
        iPos=0
):
    """
    Create a plot with multiple pads arranged in a grid, with shared axes, common legend and CMS styling.

    Args:
        canvName (str): The name of the canvas.
        nColumns (int): number of columns in the grid
        nRows (int): number of rows in the grid
        XLimits (dict): dictionary containing X axis limits for all plots, with integer keys corresponding to left-to-right top-to-bottom numbering scheme, starting from 0, and a 2-element iterable value, containing x_min and x_max. e.g. {0: [0, 50000], 1: [1, 50000]}.
        YLimits (dict): dictionary containing Y axis limits for all plots, with integer keys corresponding to left-to-right top-to-bottom numbering scheme, starting from 0, and a 2-element iterable value, containing y_min and y_max. e.g. {0: [0, 50000], 1: [1, 50000]}.
        nameXaxis (str): the label for the x-axis.
        nameYaxis (dict): the label for the y-axis, in the form of a dict int:str with integer keys corresponding to left-to-right top-to-bottom numbering scheme, starting from 0. e.g. {0: "Y Label for 1st plot", 4: "Y Label for 5th plot"}
        labelTextSize (float, optional): absolute value of textSize of axis labels (same for X and Y). Defaults to 50*0.8.
        titleTextSize (float, optional): absolute value for textSize of axis titles (same for X and Y). Defaults to 50.
        lumiTextSize (float, optional): absolute value for textSize of lumi text. Defaults to 50.
        logoTextSize (float, optional): absolute value for textSize of CMS Logo, extraText is scaled accordingly. Defaults to 50 * 0.75 / 0.6.
        legendTextSize (float, optional): Absolute value for text size of legend. Defaults to 30.
        heightRatios (list, optional): list of weights for the relative heights of the pads along the columns. Length must be equal to nrows. Defaults to None, which means each plot gets the same height.
        widthRatios (list, optional): list of weights for the relative widths of the pads along the rows. Length must be equal to ncolumns. Defaults to None, which means each plot gets the same width.
        canvasTopMargin (float, optional): margin to remove starting from the top of the canvas to make space for the top pad. Defaults to 0.1.
        canvasBottomMargin (float, optional): margin to remove starting from the bottom of the canvas to make space for the bottom pad. Defaults to 0.03.
        canvasWidth (float, optional): total width of the canvas. Defaults to 2000.
        canvasHeight (float, optional): total height of the canvas. Defaults to 2000.
        iPos (int, optional): The position of the CMS text. 0 (outside of legend box) or 11 (top-left left-aligned inside legend box). Defaults to 11.

    Returns:
        CMSCanvasManager: A object to handle the multipad grid.
    """
    cvm = subplots(
        ncolumns=nColumns,
        nrows=nRows,
        height_ratios=heightRatios,
        width_ratios=widthRatios,
        canvas_top_margin=canvasTopMargin,
        canvas_bottom_margin=canvasBottomMargin,
        axis_label_size=labelTextSize,
        axis_title_size=titleTextSize,
        canvas_height=canvasHeight,
        canvas_width=canvasWidth,
        logotextsize=logoTextSize,
        legendtextsize=legendTextSize,
        ipos=iPos
        )

    cvm.plot_text(
        cvm.top_pad,
        cms_lumi,
        textsize=lumiTextSize
        )

    cvm.plot_text(
        cvm.bottom_pad,
        nameXaxis,
        textsize=titleTextSize,
        )

    cvm.ylabel(labels=nameYaxis)
    cvm.ylimits(limits=Ylimits)
    cvm.xlimits(limits=Xlimits)

    return cvm

cmsMultiCanvasLeg(cvm, *legend_items)

Create, fill and draw the common legend of a cmsMultiCanvas.

Parameters:

Name Type Description Default
cvm CMSCanvasManager

A CMSCanvasManager object returned by cmsMultiCanvas() method.

required
*legend_items list

list of tuples in the form [(ROOTobject1, name for ROOTobject1 as a string, print option for ROOTObject1 as a string), (ROOTobject2, name for ROOTobject2 as a string, print option for ROOTObject2 as a string), ...]

()

Returns:

Type Description

None

Source code in src/cmsstyle/cmsstyle.py
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
def cmsMultiCanvasLeg(cvm, *legend_items):
    """
    Create, fill and draw the common legend of a cmsMultiCanvas.

    Args:
        cvm (CMSCanvasManager): A CMSCanvasManager object returned by cmsMultiCanvas() method.
        *legend_items (list): list of tuples in the form [(ROOTobject1, name for ROOTobject1 as a string, print option for ROOTObject1 as a string), (ROOTobject2, name for ROOTobject2 as a string, print option for ROOTObject2 as a string), ...]

    Returns:
        None
    """
    cvm.plot_common_legend(
      cvm.top_pad,
      *legend_items,
      textalign=12,
      legendtextSize=cvm._legendtextsize,
      title=cmsText,
      subtitle=extraText,
      titleSize=cvm._cmslogotextsize,
      ipos=cvm._ipos
    )

cmsObjectDraw(obj, opt='', **kwargs)

This method allows to plot the indicated object by modifying optionally the configuration of the object itself using named parameters referring to the methods to call.

Examples of use:

    cmsstyle.cmsObjectDraw(hist,'HISTSAME',LineColor=ROOT.kRed,FillColor=ROOT.kRed,FillStyle=3555)
    cmsstyle.cmsObjectDraw(hist,'E',SetLineColor=ROOT.kRed,MarkerStyle=ROOT.kFullCircle)
    cmsstyle.cmsObjectDraw(hist,'SE',SetLineColor=cmsstyle.p6.kBlue,MarkerStyle=ROOT.kFullCircle)

    cmsstyle.cmsObjectDraw(hist,'SCATSAME')  # Just 'SCAT' does not work, for some reason... "SCAT" is considered obsolete (?)

Written by O. Gonzalez.

Parameters:

Name Type Description Default
obj ROOT object

Any drawable ROOT object.

required
opt str

The plotting option. It does not need to include SAME as it is prefixed to it. Starting that opt with "S" converts that "SAME" in "SAMES" (e.g. to include the stats box). Using "SAMES" or "SAME" in opt makes the prefix not being used.

''
**kwargs ROOT styling object

Parameter names correspond to object styling method and arguments correspond to stilying ROOT objects: e.g. SetLineColor=ROOT.kRed. A method starting with "Set" may omite the "Set" part: i.e. LineColor=ROOT.kRed.

{}

Also, "Color" will be interpreted as a value applicable to SetLineColor, SetFillColor and SetMarkerColor.

Source code in src/cmsstyle/cmsstyle.py
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
def cmsObjectDraw(obj, opt="", **kwargs):
    """This method allows to plot the indicated object by modifying optionally the
    configuration of the object itself using named parameters referring to the
    methods to call.

    Examples of use:

            cmsstyle.cmsObjectDraw(hist,'HISTSAME',LineColor=ROOT.kRed,FillColor=ROOT.kRed,FillStyle=3555)
            cmsstyle.cmsObjectDraw(hist,'E',SetLineColor=ROOT.kRed,MarkerStyle=ROOT.kFullCircle)
            cmsstyle.cmsObjectDraw(hist,'SE',SetLineColor=cmsstyle.p6.kBlue,MarkerStyle=ROOT.kFullCircle)

            cmsstyle.cmsObjectDraw(hist,'SCATSAME')  # Just 'SCAT' does not work, for some reason... "SCAT" is considered obsolete (?)

    Written by O. Gonzalez.

    Args:
        obj (ROOT object): Any drawable ROOT object.
        opt (str, optional): The plotting option. It does not need to include SAME as it is prefixed to it. Starting that opt with "S" converts that "SAME" in "SAMES" (e.g. to include the stats box). Using "SAMES" or "SAME" in opt makes the prefix not being used.
        **kwargs (ROOT styling object, optional): Parameter names correspond to object styling method and arguments correspond to stilying ROOT objects: e.g. `SetLineColor=ROOT.kRed`. A method starting with "Set" may omite the "Set" part: i.e. `LineColor=ROOT.kRed`.

    Also, "Color" will be interpreted as a value applicable to SetLineColor, SetFillColor and SetMarkerColor.
    """

    setRootObjectProperties(obj, **kwargs)

    prefix = "SAME"
    if "SAME" in opt:
        prefix = ""
    obj.Draw(prefix + opt)

cmsReturnMaxY(*args)

This routine returns the recommended value for the maximum of the Y axis given a set of ROOT Object.

Parameters:

Name Type Description Default
*args

list of ROOT objects for which we need the maximum value on Y axis.

()

Returns:

Name Type Description
float

recommended value to be used in a Y axis for plotting those objects.

Source code in src/cmsstyle/cmsstyle.py
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
def cmsReturnMaxY(*args):
    """This routine returns the recommended value for the maximum of the Y axis
    given a set of ROOT Object.

    Args:
      *args: list of ROOT objects for which we need the maximum value on Y axis.

    Returns:
      float: recommended value to be used in a Y axis for plotting those objects.
    """

    maxval = 0

    for xobj in args:
        if (xobj.Class().GetName() == 'TEfficiency'):  # For efficiencies, we just put 1.2 as maximum!
            maxval = 1.19
        elif (
            xobj.Class().GetName() == "THStack"
        ):  # For the THStack it is assumed that we will print the sum!
            value = xobj.GetMaximum()*1.15 # Not sure it is really needed)
            if value>maxval:
                maxval = value

        elif hasattr(xobj, "GetMaximumBin"):  # Probably an histogram!
            value = xobj.GetBinContent(xobj.GetMaximumBin())

            # We are going to take the maximum of 120% scale and the error:
            if (xobj.GetBinError(xobj.GetMaximumBin())>0.15*value):
                value += xobj.GetBinError(xobj.GetMaximumBin())
            else:
                value *= 1.15  # It is the minimum space!

            if maxval < value:
                maxval = value

        elif hasattr(
            xobj, "GetErrorYhigh"
        ):  # TGraph are special as GetMaximum exists but it is a bug value.
            value = 0

            i = xobj.GetN()
            y = xobj.GetY()
            ey = xobj.GetEY()

            while i > 0:
                i -= 1  # Fortrans convention -> C convention

                ivalue = y[i]
                try:
                    ivalue2 = ivalue+max(ey[i], xobj.GetErrorYhigh(i))
                except ReferenceError:
                    ivalue2 = 0

                ivalue *= 1.15  # Using a minimum value for very small errors.

                if ivalue<ivalue2:  # We use the error to indicate the maximum value for the plot!
                    ivalue=ivalue2

                if value < ivalue:  # Looking for the maximum value in all the TGraph.
                    value = ivalue

            if maxval < value:
                maxval = value

        elif hasattr(
            xobj, "GetMaximum"
        ):  # Note that histograms may also have a "maximum" set.
            value = xobj.GetMaximum()*1.15 # Not sure it is really needed)
            if maxval < value:
                maxval = value

        # Other classes are for now ignored.

    return maxval

copyRootObjectProperties(obj, srcobj, proplist, **kwargs)

This method allows to copy the properties of a ROOT object from a reference source (another ROOT object) using a list of named keyword arguments to call the associated methods.

The optional kwargs part is used to call the routine setRootObjectProperties for the objects, reducing the amount of calls.

Written by O. Gonzalez.

This allows to make very efficient the synchronization of the properties between related objects so they appear similar in the plots.

cmsstyle.setRootObjectProperties(tgraph,hist,['FillColor','FillStyle','SetLineColor'])

(The keyword is obtaining by removing the "Set"/"Get" part of the name of the corresponding methods)

Parameters:

Name Type Description Default
obj ROOT TObject

ROOT object to which we want to change the properties

required
srcobj ROOT TObject

ROOT object from which we are copying the indicated properties

required
proplist list of strings

Names of the properties to be copied.

required
**kwargs

Arbitrary keyword arguments for mofifying the properties of the object using Set methods or similar.

{}
Source code in src/cmsstyle/cmsstyle.py
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
def copyRootObjectProperties(obj, srcobj, proplist, **kwargs):
    """This method allows to copy the properties of a ROOT object from a reference
    source (another ROOT object) using a list of named keyword arguments to
    call the associated methods.

    The optional kwargs part is used to call the routine
    setRootObjectProperties for the objects, reducing the amount of calls.

    Written by O. Gonzalez.

    This allows to make very efficient the synchronization of the properties
    between related objects so they appear similar in the plots.

    cmsstyle.setRootObjectProperties(tgraph,hist,['FillColor','FillStyle','SetLineColor'])

    (The keyword is obtaining by removing the "Set"/"Get" part of the name of the corresponding methods)

    Args:
        obj (ROOT TObject): ROOT object to which we want to change the properties
        srcobj (ROOT TObject): ROOT object from which we are copying the indicated properties
        proplist (list of strings): Names of the properties to be copied.
        **kwargs: Arbitrary keyword arguments for mofifying the properties of the object using Set methods or similar.

    """

    for xprp in proplist:   # Just proceding with the copy!
        getattr(obj, 'Set'+xprp)(getattr(srcobj, 'Get'+xprp)())

    # If we indicated some additional arguments, we use them to further
    # configure the object.
    if len(kwargs) > 0:
        setRootObjectProperties(obj, **kwargs)

drawText(text, posX, posY, font, align, size)

This method allows to draw a given text with all the provided characteristics.

Parameters:

Name Type Description Default
text str

text to be written in the Current TPad/TCanvas.

required
posX float

position in X (using NDC) where to place the text.

required
posY float

poisition in Y (using NDC) where to place the text.

required
font Font_t

Font to be used.

required
align int

Alignment code for the text.

required
size float

Size of the text.

required
Source code in src/cmsstyle/cmsstyle.py
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
def drawText(text, posX, posY, font, align, size):
    """This method allows to draw a given text with all the provided characteristics.

    Args:
        text (str): text to be written in the Current TPad/TCanvas.
        posX (float): position in X (using NDC) where to place the text.
        posY (float): poisition in Y (using NDC) where to place the text.
        font (Font_t): Font to be used.
        align (int): Alignment code for the text.
        size (float): Size of the text.
    """
    latex = rt.TLatex()
    latex.SetNDC()
    latex.SetTextAngle(0)
    latex.SetTextColor(rt.kBlack)

    latex.SetTextFont(font)
    latex.SetTextAlign(align)
    latex.SetTextSize(size)
    latex.DrawLatex(posX, posY, text)

getCMSStyle()

This returns the CMSStyle variable, in case it is required externally, although usually it should be accessed via ROOT.gStyle after setting it.

Source code in src/cmsstyle/cmsstyle.py
762
763
764
765
766
def getCMSStyle():
    """This returns the CMSStyle variable, in case it is required externally,
    although usually it should be accessed via ROOT.gStyle after setting it.
    """
    return cmsStyle

getPettroffColor(color)

This method returns the object (EColor) associated to a given color in the previous sets from a given string to identify it.

Parameters:

Name Type Description Default
color str

Name of the color given as a string, e.g. 'p8.kBlue' Note: If the color name does not contain a "dot" it is assumed to be a ROOT color by name!

required

Returns:

Name Type Description
EColor

color associated to the requested color name.

Source code in src/cmsstyle/cmsstyle.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
def getPettroffColor(color):  # -> EColor
    """This method returns the object (EColor) associated to a given color in the
    previous sets from a given string to identify it.

    Args:
        color (str): Name of the color given as a string, e.g. 'p8.kBlue'
                     Note: If the color name does not contain a "dot" it is assumed to
                     be a ROOT color by name!

    Returns:
        EColor: color associated to the requested color name.
    """

    if (color[0:5]=="ROOT."): # Other convention is ROOT.color...
        color=color[5:]
    elif (color[0:9]=="cmsstyle."):  # Other convention is cmsstyle.
        color=color[9:]

    if "." in color:
        x = color.split(".")
        return getattr(getattr(sys.modules[__name__], x[0]), x[1])

    # Possible standard color
    if color in (
        "kWhite",
        "kBlack",
        "kGray",
        "kRed",
        "kGreen",
        "kBlue",
        "kYellow",
        "kMagenta",
        "kCyan",
        "kOrange",
        "kSpring",
        "kTeal",
        "kAzure",
        "kViolet",
        "kPink",
    ):
        return getattr(rt, color)

    # We try to identify a ROOT color...
    try:  # Some versions don't identify GetColorByName as a valid method (still used in CMSSW)
        val = rt.TColor.GetColorByName(color)
        if (val >= 0):
            return rt.TColor.GetColorByName(color)
    except Exception:  # We keep for others some basic/common color names
        pass

    return None   # Not valid color!

getPettroffColorSet(ncolors)

This method returns a list of colors for the given number of colors based on the previous sets.

Parameters:

Name Type Description Default
ncolors int

Number of colors to be set for the list of colors (as a minimum!)

required

Returns:

Name Type Description
list

list of colors (using the keywords above!)

Source code in src/cmsstyle/cmsstyle.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
def getPettroffColorSet(ncolors):
    """This method returns a list of colors for the given number of colors based on
    the previous sets.

    Args:
        ncolors (int): Number of colors to be set for the list of colors (as a minimum!)

    Returns:
        list: list of colors (using the keywords above!)
    """

    print(ncolors)

    if ncolors < 7:  # Using the collection of P6.
        return [p6.kBlue, p6.kYellow, p6.kRed, p6.kGrape, p6.kGray, p6.kViolet]
    elif ncolors < 9:  # Using the collection of P8.
        return [
            p8.kBlue,
            p8.kOrange,
            p8.kRed,
            p8.kPink,
            p8.kGreen,
            p8.kCyan,
            p8.kAzure,
            p8.kGray,
        ]

    # Using the collection of P10... repeating as needed

    dev = [
        p10.kBlue,
        p10.kYellow,
        p10.kRed,
        p10.kGray,
        p10.kViolet,
        p10.kBrown,
        p10.kOrange,
        p10.kGreen,
        p10.kAsh,
        p10.kCyan,
    ]

    i = 10
    while i < ncolors:
        dev.append(dev[i % 10])
        i += 1
    return dev

is_valid_hex_color(hexcolor)

Check if a string represents a valid hexadecimal color code. It also allows other

Parameters:

Name Type Description Default
hex_color str / int / TColor

The hexadecimal color code to check... or a TColor or intenger value

required

Returns:

Name Type Description
bool

True if the string is a valid hexadecimal color code, False otherwise.

Source code in src/cmsstyle/cmsstyle.py
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
def is_valid_hex_color(hexcolor):
    """
    Check if a string represents a valid hexadecimal color code. It also allows other

    Args:
        hex_color (str/int/ROOT.TColor): The hexadecimal color code to check... or a TColor or intenger value

    Returns:
        bool: True if the string is a valid hexadecimal color code, False otherwise.
    """

    if isinstance(hexcolor, str):
        hex_color_pattern = re.compile(r"^#(?:[0-9a-fA-F]{3}){1,2}$")
        return bool(hex_color_pattern.match(hexcolor))

    if isinstance(hexcolor, int):  # Identifying the color by the index (probably)
        if rt.gROOT.GetColor(hexcolor) is None:
            return False  # nullptr...
        return True

    try:
        if hexcolor.Class().GetName() == "TColor":
            if rt.gROOT.GetColor(hexcolor) is None:
                return False  # nullptr...
            return True
    except Exception:
        pass

    return False  # Not clear what format was provided

setCMSStyle(force=rt.kTRUE)

This method allows to define the CMSStyle defaults.

Parameters:

Name Type Description Default
force ROOT boolean

boolean passed to the application of the Style in ROOT to force to objects loaded after setting the style.

kTRUE
Source code in src/cmsstyle/cmsstyle.py
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
def setCMSStyle(force=rt.kTRUE):
    """This method allows to define the CMSStyle defaults.

    Args:
        force (ROOT boolean): boolean passed to the application of the Style in ROOT to force to objects loaded after setting the style.
    """
    global cmsStyle
    if cmsStyle is not None:
        del cmsStyle
    cmsStyle = rt.TStyle("cmsStyle", "Style for P-CMS")
    rt.gROOT.SetStyle(cmsStyle.GetName())
    rt.gROOT.ForceStyle(force)
    # for the canvas:
    cmsStyle.SetCanvasBorderMode(0)
    cmsStyle.SetCanvasColor(rt.kWhite)
    cmsStyle.SetCanvasDefH(600)  # Height of canvas
    cmsStyle.SetCanvasDefW(600)  # Width of canvas
    cmsStyle.SetCanvasDefX(0)  # Position on screen
    cmsStyle.SetCanvasDefY(0)
    cmsStyle.SetPadBorderMode(0)
    cmsStyle.SetPadColor(rt.kWhite)
    cmsStyle.SetPadGridX(False)
    cmsStyle.SetPadGridY(False)
    cmsStyle.SetGridColor(0)
    cmsStyle.SetGridStyle(3)
    cmsStyle.SetGridWidth(1)
    # For the frame:
    cmsStyle.SetFrameBorderMode(0)
    cmsStyle.SetFrameBorderSize(1)
    cmsStyle.SetFrameFillColor(0)
    cmsStyle.SetFrameFillStyle(0)
    cmsStyle.SetFrameLineColor(1)
    cmsStyle.SetFrameLineStyle(1)
    cmsStyle.SetFrameLineWidth(1)
    # For the histo:
    cmsStyle.SetHistLineColor(1)
    cmsStyle.SetHistLineStyle(0)
    cmsStyle.SetHistLineWidth(1)
    cmsStyle.SetEndErrorSize(2)
    cmsStyle.SetMarkerStyle(20)
    cmsStyle.SetMarkerSize(
        1
    )  # Not actually set by the TDR Style, but useful to fix default!
    # For the fit/function:
    cmsStyle.SetOptFit(1)
    cmsStyle.SetFitFormat("5.4g")
    cmsStyle.SetFuncColor(2)
    cmsStyle.SetFuncStyle(1)
    cmsStyle.SetFuncWidth(1)
    # For the date:
    cmsStyle.SetOptDate(0)
    # For the TLegend (added by O. Gonzalez, in case people do not/cannot use cmsLeg)
    cmsStyle.SetLegendTextSize(0.04)
    cmsStyle.SetLegendFont(42)
    # Not avaiable    cmsStyle.SetLegendTextColor(rt.kBlack)
    # Not available for now   cmsStyle.SetLegendFillStyle(0)
    cmsStyle.SetLegendBorderSize(0)
    cmsStyle.SetLegendFillColor(0)
    # For the statistics box:
    cmsStyle.SetOptFile(0)
    cmsStyle.SetOptStat(0)  # To display the mean and RMS:   SetOptStat('mr')
    cmsStyle.SetStatColor(rt.kWhite)
    cmsStyle.SetStatFont(42)
    cmsStyle.SetStatFontSize(0.025)
    cmsStyle.SetStatTextColor(1)
    cmsStyle.SetStatFormat("6.4g")
    cmsStyle.SetStatBorderSize(1)
    cmsStyle.SetStatH(0.1)
    cmsStyle.SetStatW(0.15)
    # Margins:
    cmsStyle.SetPadTopMargin(0.05)
    cmsStyle.SetPadBottomMargin(0.13)
    cmsStyle.SetPadLeftMargin(0.16)
    cmsStyle.SetPadRightMargin(0.02)
    # For the Global title:
    cmsStyle.SetOptTitle(0)
    cmsStyle.SetTitleFont(42)
    cmsStyle.SetTitleColor(1)
    cmsStyle.SetTitleTextColor(1)
    cmsStyle.SetTitleFillColor(10)
    cmsStyle.SetTitleFontSize(0.05)
    # For the axis titles:
    cmsStyle.SetTitleColor(1, "XYZ")
    cmsStyle.SetTitleFont(42, "XYZ")
    cmsStyle.SetTitleSize(0.06, "XYZ")
    cmsStyle.SetTitleXOffset(1.1)  # Changed to fitting larger font
    cmsStyle.SetTitleYOffset(1.35)  # Changed to fitting larger font
    # For the axis labels:
    cmsStyle.SetLabelColor(1, "XYZ")
    cmsStyle.SetLabelFont(42, "XYZ")
    cmsStyle.SetLabelOffset(0.012, "XYZ")
    cmsStyle.SetLabelSize(0.05, "XYZ")
    # For the axis:
    cmsStyle.SetAxisColor(1, "XYZ")
    cmsStyle.SetStripDecimals(True)
    cmsStyle.SetTickLength(0.03, "XYZ")
    cmsStyle.SetNdivisions(510, "XYZ")
    cmsStyle.SetPadTickX(1)  # To get tick marks on the opposite side of the frame
    cmsStyle.SetPadTickY(1)
    # Change for log plots:
    cmsStyle.SetOptLogx(0)
    cmsStyle.SetOptLogy(0)
    cmsStyle.SetOptLogz(0)
    # Postscript options:
    cmsStyle.SetPaperSize(20.0, 20.0)
    cmsStyle.SetHatchesLineWidth(2)  # These numbers were preventing hatched histograms!
    cmsStyle.SetHatchesSpacing(1.3)

    # Some additional parameters we need to set as "style"
    if env_type() != "jupyter":  # Snippet below crashes in jupyter as late as 6.36. Issue reproted to ROOT
        if (
            float(".".join(re.split("\\.|/", rt.__version__)[0:2])) >= 6.32
        ):  # Not available before!
            # This change by O. Gonzalez allows to save inside the canvas the
            # informnation about the defined colours.
            rt.TColor.DefinedColors(1)

    # Using the Style.
    cmsStyle.cd()

setRootObjectProperties(obj, **kwargs)

This method allows to modify the properties of a ROOT object using a list of named keyword arguments to call the associated methods.

Written by O. Gonzalez.

Mostly intended to be called from other routines within the project, but it can be used externally with a call like e.g.

cmsstyle.setRootObjectProperties(hist,FillColor=ROOT.kRed,FillStyle=3555,SetLineColor=cmsstyle.p6.kBlue)

(A method starting with "Set" may omite the "Set" part)

Parameters:

Name Type Description Default
obj ROOT TObject

ROOT object to which we want to change the properties

required
**kwargs

Arbitrary keyword arguments for mofifying the properties of the object using Set methods or similar.

{}
Source code in src/cmsstyle/cmsstyle.py
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
def setRootObjectProperties(obj, **kwargs):
    """This method allows to modify the properties of a ROOT object using a list of
    named keyword arguments to call the associated methods.

    Written by O. Gonzalez.

    Mostly intended to be called from other routines within the project, but it
    can be used externally with a call like e.g.

    cmsstyle.setRootObjectProperties(hist,FillColor=ROOT.kRed,FillStyle=3555,SetLineColor=cmsstyle.p6.kBlue)

    (A method starting with "Set" may omite the "Set" part)

    Args:
        obj (ROOT TObject): ROOT object to which we want to change the properties
        **kwargs: Arbitrary keyword arguments for mofifying the properties of the object using Set methods or similar.
    """

    arguments = {}
    for xkey, xval in kwargs.items():
        if (xkey=='Color'):   # This applies to SetLineColor, SetFillColor and SetMarkerColor.
            for xopt in ('SetLineColor','SetMarkerColor','SetFillColor'):
                if hasattr(obj,xopt): arguments[xopt] = xval
        else:
            arguments[xkey] = xval
    #
    for xkey, xval in arguments.items():
        if hasattr(obj, "Set" + xkey):  # Note!
            method = "Set" + xkey
        elif hasattr(obj, xkey):
            method = xkey
        else:
            print(
                "Indicated argument for configuration is invalid: {} {} {}".format(
                    xkey, xval, type(obj)
                )
            )
            raise AttributeError("Invalid argument " + str(xkey) + " " + str(xval))

        try:
            if xval is None:
                getattr(obj, method)()
            elif type(xval) in (tuple,list):
                getattr(obj, method)(*xval)
            else:
                getattr(obj, method)(xval)
        except TypeError:
            if 'Color' in xkey:  # The string may be just a color indicated as a name
                if type(xval) in (list,tuple):
                    getattr(obj,method)(getPettroffColor(xval[0]),*xval[1:])
                else:
                    getattr(obj,method)(getPettroffColor(xval))
            elif (type(xval) in (str,) and xval[0:5]=='ROOT.' ):
                getattr(obj, method)(getattr(rt,xval[5:]))   # e.g. to use "ROOT.kFullcircle"
            else:
                raise

subplots(ncolumns, nrows, height_ratios=None, width_ratios=None, canvas_top_margin=None, canvas_bottom_margin=None, shared_x_axis=True, shared_y_axis=True, canvas_width=2000, canvas_height=2000, axis_title_size=50, axis_label_size=50 * 0.8, logotextsize=50, legendtextsize=30, ipos=0)

Creates multiple pads in a canvas according to the input configuration, then returns an object to help manage the canvas and all its graphical parts.

Parameters:

Name Type Description Default
ncolumns int

number of columns in the grid

required
nrows int

number of rows in the grid

required
height_ratios list

list of weights for the relative heights of the pads along the columns. Length must be equal to nrows

None
width_ratios list

list of weights for the relative widths of the pads along the rows. Length must be equal to ncolumns

None
canvas_top_margin float

margin to remove starting from the top of the canvas to make space for the top pad

None
canvas_bottom_margin float

margin to remove starting from the bottom of the canvas to make space for the bottom pad

None
shared_x_axis (bool, optional)

whether the x axis of all columns should be shared

required
shared_y_axis bool

whether the y axis of all columns should be shared

True
canvas_width float

total width of the canvas

2000
canvas_height float

total height of the canvas

2000
axis_title_size float

reference absolute size for axis titles

50
axis_label_size float

reference absolute size for axis labels

50 * 0.8
logotextsize float

absolute text size of experiment logo

50
legendtextsize float

absolute text size of legend

30
ipos int

position of experiment logo

0
Source code in src/cmsstyle/cmsstyle.py
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
def subplots(
    ncolumns,
    nrows,
    height_ratios=None,
    width_ratios=None,
    canvas_top_margin=None,
    canvas_bottom_margin=None,
    shared_x_axis=True,
    shared_y_axis=True,
    canvas_width=2000,
    canvas_height=2000,
    axis_title_size=50,
    axis_label_size=50 * 0.8,
    logotextsize=50,
    legendtextsize=30,
    ipos=0
):
    """
    Creates multiple pads in a canvas according to the input configuration, then
    returns an object to help manage the canvas and all its graphical parts.

    Args:
      ncolumns (int): number of columns in the grid
      nrows (int): number of rows in the grid
      height_ratios (list, optional): list of weights for the relative heights of the pads along the columns. Length must be equal to nrows
      width_ratios (list, optional): list of weights for the relative widths of the pads along the rows. Length must be equal to ncolumns
      canvas_top_margin (float, optional): margin to remove starting from the top of the canvas to make space for the top pad
      canvas_bottom_margin (float, optional): margin to remove starting from the bottom of the canvas to make space for the bottom pad
      shared_x_axis (bool, optional) : whether the x axis of all columns should be shared
      shared_y_axis (bool, optional): whether the y axis of all columns should be shared
      canvas_width (float, optional): total width of the canvas
      canvas_height (float, optional): total height of the canvas
      axis_title_size (float, optional): reference absolute size for axis titles
      axis_label_size (float, optional): reference absolute size for axis labels
      logotextsize (float, optional): absolute text size of experiment logo
      legendtextsize (float, optional): absolute text size of legend
      ipos (int): position of experiment logo
    """

    top_pad = None
    bottom_pad = None
    canvas = rt.TCanvas("CMS_canvas", "CMS_canvas", canvas_width, canvas_height)
    with _managed_tpad_context(canvas):
        # Gather the raw coordinates for all the pads
        pads_coords, top_pad_coords, bottom_pad_coords = _subplots_coordinates(
            ncolumns,
            nrows,
            height_ratios=height_ratios,
            width_ratios=width_ratios,
            canvas_top_margin=canvas_top_margin,
            canvas_bottom_margin=canvas_bottom_margin,
        )
        # Create the pads manually using the coordinates from above, and some adjustments
        listofpads = []
        pad_horizontal_margin = 0.2
        pad_vertical_margin = 0.4
        epsilon_height = 0.07
        epsilon_width = 0.01
        row_index = -1
        for i, coords in enumerate(pads_coords):
            xleft, ylow, xright, yup = coords
            pad = rt.TPad("pad_%d" % (i + 1), "pad_%d" % (i + 1), xleft, ylow, xright, yup)

            # The next lines adjust the relative margins (vertically and horizontally)
            # of the pads so that the final plots will always be consistent
            if i % ncolumns == 0:
                row_index += 1
                pad.SetLeftMargin(pad_horizontal_margin)
                pad.SetRightMargin(epsilon_width)
            elif i % ncolumns == (ncolumns - 1):
                pad.SetRightMargin(pad_horizontal_margin)
                pad.SetLeftMargin(epsilon_width)
            else:
                pad.SetRightMargin(pad_horizontal_margin / 2)
                pad.SetLeftMargin(pad_horizontal_margin / 2)

            if row_index == 0:
                pad.SetTopMargin(
                    pad_vertical_margin * (1.0 / height_ratios[i // ncolumns]) - epsilon_height
                )
                pad.SetBottomMargin(epsilon_height)
            elif row_index == nrows - 1:
                margin = pad_vertical_margin * (1.0 / height_ratios[i // ncolumns]) / 2
                pad.SetTopMargin(margin)
                pad.SetBottomMargin(margin)
            else:
                pad.SetTopMargin(
                    pad_vertical_margin / 2 * (1.0 / height_ratios[i // ncolumns])
                )
                pad.SetBottomMargin(
                    pad_vertical_margin / 2 * (1.0 / height_ratios[i // ncolumns])
                )

            # The pad *must* be drawn once before being used for any other plotting
            pad.Draw()
            listofpads.append(pad)

        if top_pad_coords is not None:
            xleft, ylow, xright, yup = top_pad_coords
            pad = rt.TPad("top_pad", "top_pad", xleft, ylow, xright, yup)
            pad.Draw()
            top_pad = pad

        if bottom_pad_coords is not None:
            xleft, ylow, xright, yup = bottom_pad_coords
            pad = rt.TPad("bottom_pad", "bottom_pad", xleft, ylow, xright, yup)
            pad.Draw()
            bottom_pad = pad

        canvas.Modified()

    # After creating the pads, we create one frame per pad. These will be used
    # to manage the axis range, labels etc.
    listofframes = []
    row_index = -1
    for i, pad in enumerate(listofpads):
        with _managed_tpad_context(canvas):
            pad.cd()
            if i % ncolumns == 0:
                row_index += 1

            # This part here is still custom, needs an abstract definition in
            # the function signature to provide the ranges of all the axes
            if row_index % 2 == 0:
                ymin = 0
                ymax = 400
            else:
                ymin = 0
                ymax = 2

            frame = pad.DrawFrame(-2, ymin, 2, ymax)
            xaxis = frame.GetXaxis()
            yaxis = frame.GetYaxis()
            yaxis.SetNdivisions(3, 5, 0, True)
            xaxis.SetLabelSize(0)
            yaxis.SetLabelSize(0)
            xaxis.SetTitleSize(0)
            yaxis.SetTitleSize(0)
            listofframes.append(frame)

    if shared_x_axis:
        for i in range(ncolumns):
            frame = listofframes[-ncolumns + i]
            pad = listofpads[-ncolumns + i]
            with _managed_tpad_context(canvas):
                pad.cd()
                canvas_height = pad.GetWh()
                pad_ndc_height = pad.GetHNDC()
                pad_pixel_height = canvas_height * pad_ndc_height
                labeltextsize = axis_label_size / pad_pixel_height
                frame.GetXaxis().SetLabelSize(labeltextsize)
                frame.GetXaxis().SetNdivisions(5, 5, 0, True)

    if shared_y_axis:
        for i in range(0, len(listofframes), ncolumns):
            pad = listofpads[i]
            frame = listofframes[i]
            with _managed_tpad_context(canvas):
                pad.cd()
                canvas_height = pad.GetWh()
                pad_ndc_height = pad.GetHNDC()
                pad_pixel_height = canvas_height * pad_ndc_height
                labeltextsize = axis_label_size / pad_pixel_height
                frame.GetYaxis().SetLabelSize(labeltextsize)
                frame.GetYaxis().SetNdivisions(3, 5, 0, True)
                titletextsize = axis_title_size / pad_pixel_height
                frame.GetYaxis().SetTitleSize(titletextsize)
                frame.GetYaxis().SetTitleOffset(0)

    return CMSCanvasManager(
        canvas,
        pads=listofpads,
        frames=listofframes,
        bottom_pad=bottom_pad,
        top_pad=top_pad,
        cmslogotextsize=logotextsize,
        legendtextsize=legendtextsize,
        ipos=ipos,
        grid_metadata=GridMetaData(
            ncolumns, nrows, pad_horizontal_margin, pad_vertical_margin
        ),
    )