コード例 #1
0
ファイル: Plot.py プロジェクト: fkrieter/mephisto
    def Print(self, path, **kwargs):
        r"""Print the plot to a file.

        Creates a :class:`.Canvas` and draws all registered objects into their
        associated :class:`Pad`. The canvas is saved as a PDF/PNG/... file with the
        absolute path defined by **path**. If a file with the same name already exists
        it will be overwritten (can be changed  with the **overwrite** keyword
        argument). If **mkdir** is set to ``True`` (default: ``False``) directories in
        **path** with do not yet exist will be created automatically.

        The properties of the of the plot and canvas can be configured via their
        respective properties passed as keyword arguments.

        :param path: path of the output file (must end with '.pdf', '.png', ...)
        :type path: ``str``

        :param \**kwargs: :class:`.Plot` and :class:`.Canvas` properties + additional
            properties (see below)

        Keyword Arguments:

            * **inject<N>** (``list``, ``tuple``, ``ROOT.TObject``) -- inject a (list
              of) *drawable* :class:`ROOT` object(s) to pad **<N>** (default: 0), object
              properties can be specified by passing instead a ``tuple`` of the format
              :code:`(obj, props)` where :code:`props` is a ``dict`` holding the object
              properties (default: \[\])

            * **overwrite** (``bool``) -- overwrite an existing file located at **path**
              (default: ``True``)

            * **mkdir** (``bool``) -- create non-existing directories in **path**
              (default: ``False``)

        """
        for idx, injections in {
                int(k[6:]) if len(k) > 6 else 0: kwargs.pop(k)
                for k in dict(kwargs.items()) if k.startswith("inject")
        }.items():
            if not isinstance(injections, list):
                injections = [injections]
            self.Inject(idx, *injections)
        properties = DissectProperties(kwargs, [Plot, Canvas])
        ROOT.gStyle.SetOptStat(0)
        ROOT.gStyle.SetPaintTextFormat("4.2f")
        canvas = Canvas("{}_Canvas".format(self._name),
                        template=str(self._npads),
                        **properties["Canvas"])
        legend = {}
        self.DeclareProperties(**properties["Plot"])
        self.AddPlotDecorations()
        for i, store in self._store.items():
            pad = Pad("{}_Pad-{}".format(canvas.GetName(), i),
                      **self._padproperties[i])
            pad.Draw()
            pad.cd()
            legend[i] = Legend(
                "{}_Legend".format(pad.GetName()),
                xshift=pad.GetLegendXShift(),
                yshift=pad.GetLegendYShift(),
            )
            canvas.SetSelectedPad(pad)
            for obj, objprops in store:
                with UsingProperties(obj, **objprops):
                    if any([
                            obj.InheritsFrom(tcls)
                            for tcls in ["TH1", "THStack"]
                    ]):
                        legend[i].Register(obj)
                    suffix = "SAME" if pad.GetDrawFrame() else ""
                    obj.Draw(obj.GetDrawOption() + suffix)
            if pad.GetDrawFrame():
                pad.RedrawAxis()
            if pad.GetDrawLegend():
                legend[i].Draw("SAME")
            canvas.cd()
        canvas.Print(path)
        if os.path.isfile(path):
            logger.info("Created plot: '{}'".format(path))
        canvas.Delete()