CMS 3D CMS Logo

List of all members | Public Member Functions | Private Member Functions | Private Attributes
plotting.Plot Class Reference

Public Member Functions

def __init__ (self, name, kwargs)
 
def addToLegend (self, legend, legendLabels, denomUncertainty)
 
def clone (self, kwargs)
 
def create (self, tdirNEvents, requireAllHistograms=False)
 
def draw (self, pad, ratio, ratioFactor, nrows)
 
def drawRatioUncertainty (self)
 
def getName (self)
 
def getNumberOfHistograms (self)
 
def isEmpty (self)
 
def isRatio (self, ratio)
 
def isTGraph2D (self)
 
def setName (self, name)
 
def setProperties (self, kwargs)
 

Private Member Functions

def _createOne (self, name, index, tdir, nevents)
 
def _normalize (self)
 
def _setStats (self, histos, startingX, startingY)
 

Private Attributes

 _forLegend
 
 _frame
 
 _histograms
 
 _mainAdditional
 
 _name
 
 _ratioAdditional
 
 _ratios
 
 _tmp_histos
 
 _xtitle
 
 _ytitle
 

Detailed Description

Represents one plot, comparing one or more histograms.

Definition at line 1673 of file plotting.py.

Constructor & Destructor Documentation

◆ __init__()

def plotting.Plot.__init__ (   self,
  name,
  kwargs 
)
Constructor.

Arguments:
name -- String for name of the plot, or Efficiency object

Keyword arguments:
fallback     -- Dictionary for specifying fallback (default None)
outname      -- String for an output name of the plot (default None for the same as 'name')
title        -- String for a title of the plot (default None)
xtitle       -- String for x axis title (default None)
xtitlesize   -- Float for x axis title size (default None)
xtitleoffset -- Float for x axis title offset (default None)
xlabelsize   -- Float for x axis label size (default None)
ytitle       -- String for y axis title (default None)
ytitlesize   -- Float for y axis title size (default None)
ytitleoffset -- Float for y axis title offset (default None)
ztitle       -- String for z axis title (default None)
ztitleoffset -- Float for z axis title offset (default None)
xmin         -- Float for x axis minimum (default None, i.e. automatic)
xmax         -- Float for x axis maximum (default None, i.e. automatic)
ymin         -- Float for y axis minimum (default 0)
ymax         -- Float for y axis maximum (default None, i.e. automatic)
xlog         -- Bool for x axis log status (default False)
ylog         -- Bool for y axis log status (default False)
xgrid        -- Bool for x axis grid status (default True)
ygrid        -- Bool for y axis grid status (default True)
stat         -- Draw stat box? (default False)
fit          -- Do gaussian fit? (default False)
statx        -- Stat box x coordinate (default 0.65)
staty        -- Stat box y coordinate (default 0.8)
statyadjust  -- List of floats for stat box y coordinate adjustments (default None)
normalizeToUnitArea -- Normalize histograms to unit area? (default False)
normalizeToNumberOfEvents -- Normalize histograms to number of events? If yes, the PlotFolder needs 'numberOfEventsHistogram' set to a histogram filled once per event (default False)
profileX     -- Take histograms via ProfileX()? (default False)
fitSlicesY   -- Take histograms via FitSlicesY() (default False)
rebinX       -- rebin x axis (default None)
scale        -- Scale histograms by a number (default None)
xbinlabels   -- List of x axis bin labels (if given, default None)
xbinlabelsize -- Size of x axis bin labels (default None)
xbinlabeloption -- Option string for x axis bin labels (default None)
removeEmptyBins -- Bool for removing empty bins, but only if histogram has bin labels (default False)
printBins    -- Bool for printing bin values, but only if histogram has bin labels (default False)
drawStyle    -- If "hist", draw as line instead of points (default None)
drawCommand  -- Deliver this to Draw() (default: None for same as drawStyle)
lineWidth    -- If drawStyle=="hist", the width of line (default 2)
legendDx     -- Float for moving TLegend in x direction for separate=True (default None)
legendDy     -- Float for moving TLegend in y direction for separate=True (default None)
legendDw     -- Float for changing TLegend width for separate=True (default None)
legendDh     -- Float for changing TLegend height for separate=True (default None)
legend       -- Bool to enable/disable legend (default True)
adjustMarginLeft  -- Float for adjusting left margin (default None)
adjustMarginRight  -- Float for adjusting right margin (default None)
ratio        -- Possibility to disable ratio for this particular plot (default None)
ratioYmin    -- Float for y axis minimum in ratio pad (default: list of values)
ratioYmax    -- Float for y axis maximum in ratio pad (default: list of values)
ratioFit     -- Fit straight line in ratio? (default None)
ratioUncertainty -- Plot uncertainties on ratio? (default True)
ratioCoverageXrange -- Range of x axis values (xmin,xmax) to limit the automatic ratio y axis range calculation to (default None for disabled)
histogramModifier -- Function to be called in create() to modify the histograms (default None)

Definition at line 1675 of file plotting.py.

1675  def __init__(self, name, **kwargs):
1676  """ Constructor.
1677 
1678  Arguments:
1679  name -- String for name of the plot, or Efficiency object
1680 
1681  Keyword arguments:
1682  fallback -- Dictionary for specifying fallback (default None)
1683  outname -- String for an output name of the plot (default None for the same as 'name')
1684  title -- String for a title of the plot (default None)
1685  xtitle -- String for x axis title (default None)
1686  xtitlesize -- Float for x axis title size (default None)
1687  xtitleoffset -- Float for x axis title offset (default None)
1688  xlabelsize -- Float for x axis label size (default None)
1689  ytitle -- String for y axis title (default None)
1690  ytitlesize -- Float for y axis title size (default None)
1691  ytitleoffset -- Float for y axis title offset (default None)
1692  ztitle -- String for z axis title (default None)
1693  ztitleoffset -- Float for z axis title offset (default None)
1694  xmin -- Float for x axis minimum (default None, i.e. automatic)
1695  xmax -- Float for x axis maximum (default None, i.e. automatic)
1696  ymin -- Float for y axis minimum (default 0)
1697  ymax -- Float for y axis maximum (default None, i.e. automatic)
1698  xlog -- Bool for x axis log status (default False)
1699  ylog -- Bool for y axis log status (default False)
1700  xgrid -- Bool for x axis grid status (default True)
1701  ygrid -- Bool for y axis grid status (default True)
1702  stat -- Draw stat box? (default False)
1703  fit -- Do gaussian fit? (default False)
1704  statx -- Stat box x coordinate (default 0.65)
1705  staty -- Stat box y coordinate (default 0.8)
1706  statyadjust -- List of floats for stat box y coordinate adjustments (default None)
1707  normalizeToUnitArea -- Normalize histograms to unit area? (default False)
1708  normalizeToNumberOfEvents -- Normalize histograms to number of events? If yes, the PlotFolder needs 'numberOfEventsHistogram' set to a histogram filled once per event (default False)
1709  profileX -- Take histograms via ProfileX()? (default False)
1710  fitSlicesY -- Take histograms via FitSlicesY() (default False)
1711  rebinX -- rebin x axis (default None)
1712  scale -- Scale histograms by a number (default None)
1713  xbinlabels -- List of x axis bin labels (if given, default None)
1714  xbinlabelsize -- Size of x axis bin labels (default None)
1715  xbinlabeloption -- Option string for x axis bin labels (default None)
1716  removeEmptyBins -- Bool for removing empty bins, but only if histogram has bin labels (default False)
1717  printBins -- Bool for printing bin values, but only if histogram has bin labels (default False)
1718  drawStyle -- If "hist", draw as line instead of points (default None)
1719  drawCommand -- Deliver this to Draw() (default: None for same as drawStyle)
1720  lineWidth -- If drawStyle=="hist", the width of line (default 2)
1721  legendDx -- Float for moving TLegend in x direction for separate=True (default None)
1722  legendDy -- Float for moving TLegend in y direction for separate=True (default None)
1723  legendDw -- Float for changing TLegend width for separate=True (default None)
1724  legendDh -- Float for changing TLegend height for separate=True (default None)
1725  legend -- Bool to enable/disable legend (default True)
1726  adjustMarginLeft -- Float for adjusting left margin (default None)
1727  adjustMarginRight -- Float for adjusting right margin (default None)
1728  ratio -- Possibility to disable ratio for this particular plot (default None)
1729  ratioYmin -- Float for y axis minimum in ratio pad (default: list of values)
1730  ratioYmax -- Float for y axis maximum in ratio pad (default: list of values)
1731  ratioFit -- Fit straight line in ratio? (default None)
1732  ratioUncertainty -- Plot uncertainties on ratio? (default True)
1733  ratioCoverageXrange -- Range of x axis values (xmin,xmax) to limit the automatic ratio y axis range calculation to (default None for disabled)
1734  histogramModifier -- Function to be called in create() to modify the histograms (default None)
1735  """
1736  self._name = name
1737 
1738  def _set(attr, default):
1739  setattr(self, "_"+attr, kwargs.get(attr, default))
1740 
1741  _set("fallback", None)
1742  _set("outname", None)
1743 
1744  _set("title", None)
1745  _set("xtitle", None)
1746  _set("xtitlesize", None)
1747  _set("xtitleoffset", None)
1748  _set("xlabelsize", None)
1749  _set("ytitle", None)
1750  _set("ytitlesize", None)
1751  _set("ytitleoffset", None)
1752  _set("ztitle", None)
1753  _set("ztitleoffset", None)
1754 
1755  _set("xmin", None)
1756  _set("xmax", None)
1757  _set("ymin", 0.)
1758  _set("ymax", None)
1759 
1760  _set("xlog", False)
1761  _set("ylog", False)
1762  _set("xgrid", True)
1763  _set("ygrid", True)
1764 
1765  _set("stat", False)
1766  _set("fit", False)
1767 
1768  _set("statx", 0.65)
1769  _set("staty", 0.8)
1770  _set("statyadjust", None)
1771 
1772  _set("normalizeToUnitArea", False)
1773  _set("normalizeToNumberOfEvents", False)
1774  _set("profileX", False)
1775  _set("fitSlicesY", False)
1776  _set("rebinX", None)
1777 
1778  _set("scale", None)
1779  _set("xbinlabels", None)
1780  _set("xbinlabelsize", None)
1781  _set("xbinlabeloption", None)
1782  _set("removeEmptyBins", False)
1783  _set("printBins", False)
1784 
1785  _set("drawStyle", "EP")
1786  _set("drawCommand", None)
1787  _set("lineWidth", 2)
1788 
1789  _set("legendDx", None)
1790  _set("legendDy", None)
1791  _set("legendDw", None)
1792  _set("legendDh", None)
1793  _set("legend", True)
1794 
1795  _set("adjustMarginLeft", None)
1796  _set("adjustMarginRight", None)
1797 
1798  _set("ratio", None)
1799  _set("ratioYmin", [0, 0.2, 0.5, 0.7, 0.8, 0.9, 0.95])
1800  _set("ratioYmax", [1.05, 1.1, 1.2, 1.3, 1.5, 1.8, 2, 2.5, 3, 4, 5])
1801  _set("ratioFit", None)
1802  _set("ratioUncertainty", True)
1803  _set("ratioCoverageXrange", None)
1804 
1805  _set("histogramModifier", None)
1806 
1807  self._histograms = []
1808 
def __init__(self, dataset, job_number, job_id, job_name, isDA, isMC, applyBOWS, applyEXTRACOND, extraconditions, runboundary, lumilist, intlumi, maxevents, gt, allFromGT, alignmentDB, alignmentTAG, apeDB, apeTAG, bowDB, bowTAG, vertextype, tracktype, refittertype, ttrhtype, applyruncontrol, ptcut, CMSSW_dir, the_dir)

Member Function Documentation

◆ _createOne()

def plotting.Plot._createOne (   self,
  name,
  index,
  tdir,
  nevents 
)
private
Create one histogram from a TDirectory.

Definition at line 1856 of file plotting.py.

References plotting._getOrCreateObject().

Referenced by plotting.Plot.create().

1856  def _createOne(self, name, index, tdir, nevents):
1857  """Create one histogram from a TDirectory."""
1858  if tdir == None:
1859  return None
1860 
1861  # If name is a list, pick the name by the index
1862  if isinstance(name, list):
1863  name = name[index]
1864 
1865  h = _getOrCreateObject(tdir, name)
1866  if h is not None and self._normalizeToNumberOfEvents and nevents is not None and nevents != 0:
1867  h.Scale(1.0/nevents)
1868  return h
1869 
def _getOrCreateObject(tdirectory, nameOrCreator)
Definition: plotting.py:57

◆ _normalize()

def plotting.Plot._normalize (   self)
private
Normalise histograms to unit area

Definition at line 1962 of file plotting.py.

References RunHistogramManager._histograms, and plotting.Plot._histograms.

Referenced by plotting.Plot.draw().

1962  def _normalize(self):
1963  """Normalise histograms to unit area"""
1964 
1965  for h in self._histograms:
1966  if h is None:
1967  continue
1968  i = h.Integral()
1969  if i == 0:
1970  continue
1971  if h.GetSumw2().fN <= 0: # to suppress warning
1972  h.Sumw2()
1973  h.Scale(1.0/i)
1974 

◆ _setStats()

def plotting.Plot._setStats (   self,
  histos,
  startingX,
  startingY 
)
private
Set stats box.

Definition at line 1920 of file plotting.py.

References DTSC._stat, and DTTrigGeom._stat.

1920  def _setStats(self, histos, startingX, startingY):
1921  """Set stats box."""
1922  if not self._stat:
1923  for h in histos:
1924  if h is not None and hasattr(h, "SetStats"):
1925  h.SetStats(0)
1926  return
1927 
1928  def _doStats(h, col, dy):
1929  if h is None:
1930  return
1931  h.SetStats(True)
1932 
1933  if self._fit and h.GetEntries() > 0.5:
1934  h.Fit("gaus", "Q")
1935  f = h.GetListOfFunctions().FindObject("gaus")
1936  if f == None:
1937  h.SetStats(0)
1938  return
1939  f.SetLineColor(col)
1940  f.SetLineWidth(1)
1941  h.Draw()
1942  ROOT.gPad.Update()
1943  st = h.GetListOfFunctions().FindObject("stats")
1944  if self._fit:
1945  st.SetOptFit(0o010)
1946  st.SetOptStat(1001)
1947  st.SetOptStat(1110)
1948  st.SetX1NDC(startingX)
1949  st.SetX2NDC(startingX+0.3)
1950  st.SetY1NDC(startingY+dy)
1951  st.SetY2NDC(startingY+dy+0.12)
1952  st.SetTextColor(col)
1953 
1954  dy = 0.0
1955  for i, h in enumerate(histos):
1956  if self._statyadjust is not None and i < len(self._statyadjust):
1957  dy += self._statyadjust[i]
1958 
1959  _doStats(h, _plotStylesColor[i], dy)
1960  dy -= 0.16
1961 

◆ addToLegend()

def plotting.Plot.addToLegend (   self,
  legend,
  legendLabels,
  denomUncertainty 
)
Add histograms to a legend.

Arguments:
legend       -- TLegend
legendLabels -- List of strings for the legend labels

Definition at line 2208 of file plotting.py.

References RunHistogramManager._histograms, plotting.Plot._histograms, and ComparisonHelper.zip().

2208  def addToLegend(self, legend, legendLabels, denomUncertainty):
2209  """Add histograms to a legend.
2210 
2211  Arguments:
2212  legend -- TLegend
2213  legendLabels -- List of strings for the legend labels
2214  """
2215  first = denomUncertainty
2216  for h, label in zip(self._histograms, legendLabels):
2217  if h is None:
2218  first = False
2219  continue
2220  if first:
2221  self._forLegend = h.Clone()
2222  self._forLegend.SetFillStyle(1001)
2223  self._forLegend.SetFillColor(ROOT.kGray)
2224  entry = legend.AddEntry(self._forLegend, label, "lpf")
2225  first = False
2226  else:
2227  legend.AddEntry(h, label, "LP")
2228 
OutputIterator zip(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)

◆ clone()

def plotting.Plot.clone (   self,
  kwargs 
)

◆ create()

def plotting.Plot.create (   self,
  tdirNEvents,
  requireAllHistograms = False 
)
Create histograms from list of TDirectories

Definition at line 1870 of file plotting.py.

References plotting.Plot._createOne(), RunHistogramManager._histograms, plotting.Plot._histograms, FP420HitsObject._name, TrackerHitsObject._name, PGeometricDet::Item._name, TrackingRecHitAlgorithm._name, Logger._name, hcaldqm::DQModule._name, citk::IsolationConeDefinitionBase._name, condhdf5tohdf5.H5DataProduct._name, WValidation._name, DrellYanValidation._name, hcaldqm::flag::Flag._name, hcaldqm::quantity::Quantity._name, HistoParams< T >._name, condhdf5tohdf5.H5Tag._name, CutApplicatorBase._name, condhdf5tohdf5.H5GlobalTag._name, HistoParams< TH2F >._name, HistoParams< TProfile2D >._name, conddb2hdf5.DBGlobalTag._name, SequenceTypes.SequencePlaceholder._name, plotting.Subtract._name, plotting.Transform._name, plotting.FakeDuplicate._name, plotting.CutEfficiency._name, plotting.AggregateBins._name, plotting.AggregateHistos._name, plotting.ROC._name, SequenceTypes._TaskBasePlaceholder._name, plotting.Plot._name, plotting.AggregateBins._scale, HistoParams< T >._title, HistoParams< TH1F >._title, HistoParams< TProfile >._title, HistoParams< TH2F >._title, HistoParams< TProfile2D >._title, html.PageSet._title, plotting.Subtract._title, html.HtmlReport._title, plotting.Transform._title, plotting.FakeDuplicate._title, plotting.CutEfficiency._title, genParticles_cff.map, and FastTimerService_cff.range.

1870  def create(self, tdirNEvents, requireAllHistograms=False):
1871  """Create histograms from list of TDirectories"""
1872  self._histograms = [self._createOne(self._name, i, tdirNEvent[0], tdirNEvent[1]) for i, tdirNEvent in enumerate(tdirNEvents)]
1873 
1874  if self._fallback is not None:
1875  profileX = [self._profileX]*len(self._histograms)
1876  for i in range(0, len(self._histograms)):
1877  if self._histograms[i] is None:
1878  self._histograms[i] = self._createOne(self._fallback["name"], i, tdirNEvents[i][0], tdirNEvents[i][1])
1879  profileX[i] = self._fallback.get("profileX", self._profileX)
1880 
1881  if self._histogramModifier is not None:
1882  self._histograms = self._histogramModifier(self._histograms)
1883 
1884  if len(self._histograms) > len(_plotStylesColor):
1885  raise Exception("More histograms (%d) than there are plot styles (%d) defined. Please define more plot styles in this file" % (len(self._histograms), len(_plotStylesColor)))
1886 
1887  # Modify histograms here in case self._name returns numbers
1888  # and self._histogramModifier creates the histograms from
1889  # these numbers
1890  def _modifyHisto(th1, profileX):
1891  if th1 is None:
1892  return None
1893 
1894  if profileX:
1895  th1 = th1.ProfileX()
1896 
1897  if self._fitSlicesY:
1898  ROOT.TH1.AddDirectory(True)
1899  th1.FitSlicesY()
1900  th1 = ROOT.gDirectory.Get(th1.GetName()+"_2")
1901  th1.SetDirectory(None)
1902  #th1.SetName(th1.GetName()+"_ref")
1903  ROOT.TH1.AddDirectory(False)
1904 
1905  if self._title is not None:
1906  th1.SetTitle(self._title)
1907 
1908  if self._scale is not None:
1909  th1.Scale(self._scale)
1910 
1911  return th1
1912 
1913  if self._fallback is not None:
1914  self._histograms = list(map(_modifyHisto, self._histograms, profileX))
1915  else:
1916  self._histograms = list(map(lambda h: _modifyHisto(h, self._profileX), self._histograms))
1917  if requireAllHistograms and None in self._histograms:
1918  self._histograms = [None]*len(self._histograms)
1919 
def create(alignables, pedeDump, additionalData, outputFile, config)

◆ draw()

def plotting.Plot.draw (   self,
  pad,
  ratio,
  ratioFactor,
  nrows 
)
Draw the histograms using values for a given algorithm.

Definition at line 1975 of file plotting.py.

References RunHistogramManager._histograms, plotting.Plot._histograms, plotting._mergeBinLabelsX(), plotting._mergeBinLabelsY(), plotting.Plot._normalize(), plotting._th1IncludeOnlyBins(), HistoData.getName(), MaterialInformation.getName(), trklet::MemoryBase.getName(), EcalLogicID.getName(), PCaloHit.getName(), emtf::Node.getName(), trklet::ProcessBase.getName(), CocoaMaterialElementary.getName(), ecaldqm::DBReaderWorker.getName(), ParticleFlux.getName(), FittedEntry.getName(), hcaldqm::mapper::Mapper.getName(), ecaldqm::DBWriterWorker.getName(), FieldHandlerBase< TOutput >.getName(), IdealResult.getName(), TrackingRecHitAlgorithm.getName(), PassiveHit.getName(), jsoncollector::JsonMonitorable.getName(), QCriterion.getName(), hcaldqm::mapper::HashMapper.getName(), CSGAction.getName(), MVAVariableManager< ParticleType >.getName(), AnyMVAEstimatorRun2Base.getName(), DTTPGLutFile.getName(), AlignmentAlgorithm.getName(), L1TUtmCondition.getName(), L1TriggerLutFile.getName(), TkOfflineVariables.getName(), fastsim::InteractionModel.getName(), L1MuGMTReg.getName(), GenericMVAComputer::TaggingVariableIterator< Iter_t >::Value.getName(), pos::PixelPortcardMap.getName(), GEMStation.getName(), PhysicsTools::Variable::Value.getName(), edm::messagelogger::ELseverityLevel.getName(), edm::ELseverityLevel.getName(), RPCDCCLink.getName(), RPCAMCLink.getName(), L1TUtmAlgorithm.getName(), L1TUtmScale.getName(), L1MuGMTRegMMConfig.getName(), L1TUtmCut.getName(), JanAlignmentAlgorithm.getName(), L1TUtmObject.getName(), cscdqm::HistoDef.getName(), FourVectorHLT::PathInfo.getName(), jsoncollector::DataPoint.getName(), L1TUtmTriggerMenu.getName(), RPCLBLink.getName(), ecaldqm::DQWorker.getName(), PhysicsTools::Variable.getName(), PrepareDMRTrends.getName(), dqm::impl::MonitorElement.getName(), L1MuGMTRegSortRankOffset.getName(), L1MuGMTRegCDLConfig.getName(), cscdqm::CSCHistoDef.getName(), plotting.PlotEmpty.getName(), plotting.Plot.getName(), plotting.Plot.isTGraph2D(), and print().

1975  def draw(self, pad, ratio, ratioFactor, nrows):
1976  """Draw the histograms using values for a given algorithm."""
1977 # if len(self._histograms) == 0:
1978 # print "No histograms for plot {name}".format(name=self._name)
1979 # return
1980 
1981  isTGraph2D = self.isTGraph2D()
1982  if isTGraph2D:
1983  # Ratios for the TGraph2Ds is not that interesting
1984  ratioOrig = ratio
1985  ratio = False
1986 
1987  if self._normalizeToUnitArea:
1988  self._normalize()
1989 
1990  if self._rebinX is not None:
1991  for h in self._histograms:
1992  h.Rebin(self._rebinX)
1993 
1994  def _styleMarker(h, msty, col):
1995  h.SetMarkerStyle(msty)
1996  h.SetMarkerColor(col)
1997  h.SetMarkerSize(0.7)
1998  h.SetLineColor(1)
1999  h.SetLineWidth(1)
2000 
2001  def _styleHist(h, msty, col):
2002  _styleMarker(h, msty, col)
2003  h.SetLineColor(col)
2004  h.SetLineWidth(self._lineWidth)
2005 
2006  # Use marker or hist style
2007  style = _styleMarker
2008  if "hist" in self._drawStyle.lower():
2009  style = _styleHist
2010  if len(self._histograms) > 0 and isinstance(self._histograms[0], ROOT.TGraph):
2011  if "l" in self._drawStyle.lower():
2012  style = _styleHist
2013 
2014  # Apply style to histograms, filter out Nones
2015  histos = []
2016  for i, h in enumerate(self._histograms):
2017  if h is None:
2018  continue
2019  style(h, _plotStylesMarker[i], _plotStylesColor[i])
2020  histos.append(h)
2021  if len(histos) == 0:
2022  if verbose:
2023  print("No histograms for plot {name}".format(name=self.getName()))
2024  return
2025 
2026  # Extract x bin labels, make sure that only bins with same
2027  # label are compared with each other
2028  histosHaveBinLabels = len(histos[0].GetXaxis().GetBinLabel(1)) > 0
2029  xbinlabels = self._xbinlabels
2030  ybinlabels = None
2031  if xbinlabels is None:
2032  if histosHaveBinLabels:
2033  xbinlabels = _mergeBinLabelsX(histos)
2034  if isinstance(histos[0], ROOT.TH2):
2035  ybinlabels = _mergeBinLabelsY(histos)
2036 
2037  if len(histos) > 1: # don't bother if only one histogram
2038  # doing this for TH2 is pending for use case, for now there is only 1 histogram/plot for TH2
2039  histos = _th1IncludeOnlyBins(histos, xbinlabels)
2040  self._tmp_histos = histos # need to keep these in memory too ...
2041 
2042  # Remove empty bins, but only if histograms have bin labels
2043  if self._removeEmptyBins and histosHaveBinLabels:
2044  # at this point, all histograms have been "equalized" by their x binning and labels
2045  # therefore remove bins which are empty in all histograms
2046  if isinstance(histos[0], ROOT.TH2):
2047  (histos, xbinlabels, ybinlabels) = _th2RemoveEmptyBins(histos, xbinlabels, ybinlabels)
2048  else:
2049  (histos, xbinlabels) = _th1RemoveEmptyBins(histos, xbinlabels)
2050  self._tmp_histos = histos # need to keep these in memory too ...
2051  if len(histos) == 0:
2052  if verbose:
2053  print("No histograms with non-empty bins for plot {name}".format(name=self.getName()))
2054  return
2055 
2056  if self._printBins and histosHaveBinLabels:
2057  print("####################")
2058  print(self._name)
2059  width = max([len(l) for l in xbinlabels])
2060  tmp = "%%-%ds " % width
2061  for b in range(1, histos[0].GetNbinsX()+1):
2062  s = tmp % xbinlabels[b-1]
2063  for h in histos:
2064  s += "%.3f " % h.GetBinContent(b)
2065  print(s)
2066  print()
2067 
2068  bounds = _findBounds(histos, self._ylog,
2069  xmin=self._xmin, xmax=self._xmax,
2070  ymin=self._ymin, ymax=self._ymax)
2071  zmax = None
2072  if isinstance(histos[0], ROOT.TH2):
2073  zmax = max([h.GetMaximum() for h in histos])
2074 
2075  # need to keep these in memory
2076  self._mainAdditional = []
2077  self._ratioAdditional = []
2078 
2079  if ratio:
2080  self._ratios = _calculateRatios(histos, self._ratioUncertainty) # need to keep these in memory too ...
2081  ratioHistos = [h for h in [r.getRatio() for r in self._ratios[1:]] if h is not None]
2082 
2083  if len(ratioHistos) > 0:
2084  ratioBoundsY = _findBoundsY(ratioHistos, ylog=False, ymin=self._ratioYmin, ymax=self._ratioYmax, coverage=0.68, coverageRange=self._ratioCoverageXrange)
2085  else:
2086  ratioBoundsY = (0.9, 1,1) # hardcoded default in absence of valid ratio calculations
2087 
2088  if self._ratioFit is not None:
2089  for i, rh in enumerate(ratioHistos):
2090  tf_line = ROOT.TF1("line%d"%i, "[0]+x*[1]")
2091  tf_line.SetRange(self._ratioFit["rangemin"], self._ratioFit["rangemax"])
2092  fitres = rh.Fit(tf_line, "RINSQ")
2093  tf_line.SetLineColor(rh.GetMarkerColor())
2094  tf_line.SetLineWidth(2)
2095  self._ratioAdditional.append(tf_line)
2096  box = PlotTextBox(xmin=self._ratioFit.get("boxXmin", 0.14), ymin=None, # None for automatix
2097  xmax=self._ratioFit.get("boxXmax", 0.35), ymax=self._ratioFit.get("boxYmax", 0.09),
2098  color=rh.GetMarkerColor(), font=43, size=11, lineheight=0.02)
2099  box.move(dx=(box.width()+0.01)*i)
2100  #box.addText("Const: %.4f" % fitres.Parameter(0))
2101  #box.addText("Slope: %.4f" % fitres.Parameter(1))
2102  box.addText("Const: %.4f#pm%.4f" % (fitres.Parameter(0), fitres.ParError(0)))
2103  box.addText("Slope: %.4f#pm%.4f" % (fitres.Parameter(1), fitres.ParError(1)))
2104  self._mainAdditional.append(box)
2105 
2106 
2107  # Create bounds before stats in order to have the
2108  # SetRangeUser() calls made before the fit
2109  #
2110  # stats is better to be called before frame, otherwise get
2111  # mess in the plot (that frame creation cleans up)
2112  if ratio:
2113  pad.cd(1)
2114  self._setStats(histos, self._statx, self._staty)
2115 
2116  # Create frame
2117  if isTGraph2D:
2118  frame = FrameTGraph2D(pad, bounds, histos, ratioOrig, ratioFactor)
2119  else:
2120  if ratio:
2121  ratioBounds = (bounds[0], ratioBoundsY[0], bounds[2], ratioBoundsY[1])
2122  frame = FrameRatio(pad, bounds, zmax, ratioBounds, ratioFactor, nrows, xbinlabels, self._xbinlabelsize, self._xbinlabeloption)
2123  else:
2124  frame = Frame(pad, bounds, zmax, nrows, xbinlabels, self._xbinlabelsize, self._xbinlabeloption, ybinlabels=ybinlabels)
2125 
2126  # Set log and grid
2127  frame.setLogx(self._xlog)
2128  frame.setLogy(self._ylog)
2129  frame.setGridx(self._xgrid)
2130  frame.setGridy(self._ygrid)
2131 
2132  # Construct draw option string
2133  opt = "sames" # s for statbox or something?
2134  ds = ""
2135  if self._drawStyle is not None:
2136  ds = self._drawStyle
2137  if self._drawCommand is not None:
2138  ds = self._drawCommand
2139  if len(ds) > 0:
2140  opt += " "+ds
2141 
2142  # Set properties of frame
2143  frame.setTitle(histos[0].GetTitle())
2144  if self._xtitle == 'Default':
2145  frame.setXTitle( histos[0].GetXaxis().GetTitle() )
2146  elif self._xtitle is not None:
2147  frame.setXTitle(self._xtitle)
2148  if self._xtitlesize is not None:
2149  frame.setXTitleSize(self._xtitlesize)
2150  if self._xtitleoffset is not None:
2151  frame.setXTitleOffset(self._xtitleoffset)
2152  if self._xlabelsize is not None:
2153  frame.setXLabelSize(self._xlabelsize)
2154  if self._ytitle == 'Default':
2155  frame.setYTitle( histos[0].GetYaxis().GetTitle() )
2156  elif self._ytitle is not None:
2157  frame.setYTitle(self._ytitle)
2158  if self._ytitlesize is not None:
2159  frame.setYTitleSize(self._ytitlesize)
2160  if self._ytitleoffset is not None:
2161  frame.setYTitleOffset(self._ytitleoffset)
2162  if self._ztitle is not None:
2163  frame.setZTitle(self._ztitle)
2164  if self._ztitleoffset is not None:
2165  frame.setZTitleOffset(self._ztitleoffset)
2166  if self._adjustMarginLeft is not None:
2167  frame.adjustMarginLeft(self._adjustMarginLeft)
2168  if self._adjustMarginRight is not None:
2169  frame.adjustMarginRight(self._adjustMarginRight)
2170  elif "z" in opt:
2171  frame.adjustMarginLeft(0.03)
2172  frame.adjustMarginRight(0.08)
2173 
2174  # Draw histograms
2175  if ratio:
2176  frame._pad.cd()
2177 
2178  for i, h in enumerate(histos):
2179  o = opt
2180  if isTGraph2D and i == 0:
2181  o = o.replace("sames", "")
2182  h.Draw(o)
2183 
2184  for addl in self._mainAdditional:
2185  addl.Draw("same")
2186 
2187  # Draw ratios
2188  if ratio and len(self._ratios) > 0:
2189  frame._padRatio.cd()
2190  firstRatio = self._ratios[0].getRatio()
2191  if self._ratioUncertainty and firstRatio is not None:
2192  firstRatio.SetFillStyle(1001)
2193  firstRatio.SetFillColor(ROOT.kGray)
2194  firstRatio.SetLineColor(ROOT.kGray)
2195  firstRatio.SetMarkerColor(ROOT.kGray)
2196  firstRatio.SetMarkerSize(0)
2197  self._ratios[0].draw("E2")
2198  frame._padRatio.RedrawAxis("G") # redraw grid on top of the uncertainty of denominator
2199  for r in self._ratios[1:]:
2200  r.draw()
2201 
2202  for addl in self._ratioAdditional:
2203  addl.Draw("same")
2204 
2205  frame.redrawAxis()
2206  self._frame = frame # keep the frame in memory for sure
2207 
std::bitset< TTBV::S_ > Frame
Definition: TTTypes.h:58
def _findBoundsY(th1s, ylog, ymin=None, ymax=None, coverage=None, coverageRange=None)
Definition: plotting.py:527
def _findBounds(th1s, ylog, xmin=None, xmax=None, ymin=None, ymax=None)
Definition: plotting.py:459
def _calculateRatios(histos, ratioUncertainty=False)
Definition: plotting.py:148
def draw(name, histos, styles=_defaultStyles, legendLabels=[], kwargs)
Definition: style.py:1
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def _mergeBinLabelsY(histos)
Definition: plotting.py:710
def _th1RemoveEmptyBins(histos, xbinlabels)
Definition: plotting.py:607
def _th2RemoveEmptyBins(histos, xbinlabels, ybinlabels)
Definition: plotting.py:647
def _mergeBinLabelsX(histos)
Definition: plotting.py:707
def _th1IncludeOnlyBins(histos, xbinlabels)
Definition: plotting.py:744

◆ drawRatioUncertainty()

def plotting.Plot.drawRatioUncertainty (   self)
Return true if the ratio uncertainty should be drawn

Definition at line 1852 of file plotting.py.

1852  def drawRatioUncertainty(self):
1853  """Return true if the ratio uncertainty should be drawn"""
1854  return self._ratioUncertainty
1855 

◆ getName()

def plotting.Plot.getName (   self)

◆ getNumberOfHistograms()

def plotting.Plot.getNumberOfHistograms (   self)
Return number of existing histograms.

Definition at line 1822 of file plotting.py.

References RunHistogramManager._histograms, and plotting.Plot._histograms.

Referenced by plotting.Plot.isEmpty().

1822  def getNumberOfHistograms(self):
1823  """Return number of existing histograms."""
1824  return len([h for h in self._histograms if h is not None])
1825 

◆ isEmpty()

def plotting.Plot.isEmpty (   self)
Return true if there are no histograms created for the plot

Definition at line 1826 of file plotting.py.

References plotting.PlotEmpty.getNumberOfHistograms(), and plotting.Plot.getNumberOfHistograms().

Referenced by plotting.Plot.clone().

1826  def isEmpty(self):
1827  """Return true if there are no histograms created for the plot"""
1828  return self.getNumberOfHistograms() == 0
1829 

◆ isRatio()

def plotting.Plot.isRatio (   self,
  ratio 
)

Definition at line 1836 of file plotting.py.

1836  def isRatio(self, ratio):
1837  if self._ratio is None:
1838  return ratio
1839  return ratio and self._ratio
1840 

◆ isTGraph2D()

def plotting.Plot.isTGraph2D (   self)

Definition at line 1830 of file plotting.py.

References RunHistogramManager._histograms, and plotting.Plot._histograms.

Referenced by plotting.Plot.draw().

1830  def isTGraph2D(self):
1831  for h in self._histograms:
1832  if isinstance(h, ROOT.TGraph2D):
1833  return True
1834  return False
1835 

◆ setName()

def plotting.Plot.setName (   self,
  name 
)

◆ setProperties()

def plotting.Plot.setProperties (   self,
  kwargs 
)

Definition at line 1809 of file plotting.py.

1809  def setProperties(self, **kwargs):
1810  for name, value in kwargs.items():
1811  if not hasattr(self, "_"+name):
1812  raise Exception("No attribute '%s'" % name)
1813  setattr(self, "_"+name, value)
1814 

Member Data Documentation

◆ _forLegend

plotting.Plot._forLegend
private

Definition at line 2221 of file plotting.py.

◆ _frame

plotting.Plot._frame
private

Definition at line 2206 of file plotting.py.

◆ _histograms

plotting.Plot._histograms
private

◆ _mainAdditional

plotting.Plot._mainAdditional
private

Definition at line 2076 of file plotting.py.

◆ _name

plotting.Plot._name
private

◆ _ratioAdditional

plotting.Plot._ratioAdditional
private

Definition at line 2077 of file plotting.py.

◆ _ratios

plotting.Plot._ratios
private

Definition at line 2080 of file plotting.py.

◆ _tmp_histos

plotting.Plot._tmp_histos
private

Definition at line 2040 of file plotting.py.

◆ _xtitle

plotting.Plot._xtitle
private

Definition at line 2144 of file plotting.py.

◆ _ytitle

plotting.Plot._ytitle
private

Definition at line 2154 of file plotting.py.