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 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
 

Detailed Description

Represents one plot, comparing one or more histograms.

Definition at line 1692 of file plotting.py.

Constructor & Destructor Documentation

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 1694 of file plotting.py.

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

Member Function Documentation

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

Definition at line 1872 of file plotting.py.

References plotting._getOrCreateObject().

Referenced by plotting.Plot.create().

1872  def _createOne(self, name, index, tdir, nevents):
1873  """Create one histogram from a TDirectory."""
1874  if tdir == None:
1875  return None
1876 
1877  # If name is a list, pick the name by the index
1878  if isinstance(name, list):
1879  name = name[index]
1880 
1881  h = _getOrCreateObject(tdir, name)
1882  if h is not None and self._normalizeToNumberOfEvents and nevents is not None and nevents != 0:
1883  h.Scale(1.0/nevents)
1884  return h
1885 
def _getOrCreateObject(tdirectory, nameOrCreator)
Definition: plotting.py:56
def _createOne(self, name, index, tdir, nevents)
Definition: plotting.py:1872
def plotting.Plot._normalize (   self)
private
Normalise histograms to unit area

Definition at line 1977 of file plotting.py.

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

Referenced by plotting.Plot.draw().

1977  def _normalize(self):
1978  """Normalise histograms to unit area"""
1979 
1980  for h in self._histograms:
1981  if h is None:
1982  continue
1983  i = h.Integral()
1984  if i == 0:
1985  continue
1986  if h.GetSumw2().fN <= 0: # to suppress warning
1987  h.Sumw2()
1988  h.Scale(1.0/i)
1989 
def _normalize(self)
Definition: plotting.py:1977
def plotting.Plot._setStats (   self,
  histos,
  startingX,
  startingY 
)
private
Set stats box.

Definition at line 1936 of file plotting.py.

References DTSC._stat, and DTTrigGeom._stat.

1936  def _setStats(self, histos, startingX, startingY):
1937  """Set stats box."""
1938  if not self._stat:
1939  for h in histos:
1940  if h is not None and hasattr(h, "SetStats"):
1941  h.SetStats(0)
1942  return
1943 
1944  def _doStats(h, col, dy):
1945  if h is None:
1946  return
1947  h.SetStats(True)
1948 
1949  if self._fit and h.GetEntries() > 0.5:
1950  h.Fit("gaus", "Q")
1951  f = h.GetListOfFunctions().FindObject("gaus")
1952  if f == None:
1953  h.SetStats(0)
1954  return
1955  f.SetLineColor(col)
1956  f.SetLineWidth(1)
1957  h.Draw()
1958  ROOT.gPad.Update()
1959  st = h.GetListOfFunctions().FindObject("stats")
1960  if self._fit:
1961  st.SetOptFit(0o010)
1962  st.SetOptStat(1001)
1963  st.SetX1NDC(startingX)
1964  st.SetX2NDC(startingX+0.3)
1965  st.SetY1NDC(startingY+dy)
1966  st.SetY2NDC(startingY+dy+0.15)
1967  st.SetTextColor(col)
1968 
1969  dy = 0.0
1970  for i, h in enumerate(histos):
1971  if self._statyadjust is not None and i < len(self._statyadjust):
1972  dy += self._statyadjust[i]
1973 
1974  _doStats(h, _plotStylesColor[i], dy)
1975  dy -= 0.19
1976 
def _setStats(self, histos, startingX, startingY)
Definition: plotting.py:1936
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 2219 of file plotting.py.

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

2219  def addToLegend(self, legend, legendLabels, denomUncertainty):
2220  """Add histograms to a legend.
2221 
2222  Arguments:
2223  legend -- TLegend
2224  legendLabels -- List of strings for the legend labels
2225  """
2226  first = denomUncertainty
2227  for h, label in zip(self._histograms, legendLabels):
2228  if h is None:
2229  first = False
2230  continue
2231  if first:
2232  self._forLegend = h.Clone()
2233  self._forLegend.SetFillStyle(1001)
2234  self._forLegend.SetFillColor(ROOT.kGray)
2235  entry = legend.AddEntry(self._forLegend, label, "lpf")
2236  first = False
2237  else:
2238  legend.AddEntry(h, label, "LP")
2239 
OutputIterator zip(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)
def addToLegend(self, legend, legendLabels, denomUncertainty)
Definition: plotting.py:2219
def plotting.Plot.clone (   self,
  kwargs 
)
def plotting.Plot.create (   self,
  tdirNEvents,
  requireAllHistograms = False 
)
Create histograms from list of TDirectories

Definition at line 1886 of file plotting.py.

References plotting.Plot._createOne(), RunHistogramManager._histograms, plotting.Plot._histograms, FP420HitsObject._name, TrackerHitsObject._name, PGeometricDet::Item._name, LikelihoodSpecies._name, TrackingRecHitAlgorithm._name, LikelihoodPdfProduct._name, LikelihoodPdf._name, citk::IsolationConeDefinitionBase._name, Logger._name, hcaldqm::DQModule._name, DrellYanValidation._name, WValidation._name, HistoParams< T >._name, hcaldqm::flag::Flag._name, hcaldqm::quantity::Quantity._name, GeometricTimingDetExtra._name, CutApplicatorBase._name, GeometricDetExtra._name, HistoParams< TH2F >._name, HistoParams< TProfile2D >._name, Vispa.Views.PropertyView.Property._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.TaskPlaceholder._name, plotting.Plot._name, Vispa.Gui.VispaWidget.VispaWidget._scale, plotting.AggregateBins._scale, HistoParams< TH1F >._title, HistoParams< TProfile >._title, HistoParams< T >._title, HistoParams< TH2F >._title, SiStripHitEffFromCalibTree._title, HistoParams< TProfile2D >._title, html.PageSet._title, html.HtmlReport._title, plotting.Subtract._title, plotting.Transform._title, plotting.FakeDuplicate._title, plotting.CutEfficiency._title, and genParticles_cff.map.

1886  def create(self, tdirNEvents, requireAllHistograms=False):
1887  """Create histograms from list of TDirectories"""
1888  self._histograms = [self._createOne(self._name, i, tdirNEvent[0], tdirNEvent[1]) for i, tdirNEvent in enumerate(tdirNEvents)]
1889 
1890  if self._fallback is not None:
1891  profileX = [self._profileX]*len(self._histograms)
1892  for i in xrange(0, len(self._histograms)):
1893  if self._histograms[i] is None:
1894  self._histograms[i] = self._createOne(self._fallback["name"], i, tdirNEvents[i][0], tdirNEvents[i][1])
1895  profileX[i] = self._fallback.get("profileX", self._profileX)
1896 
1897  if self._histogramModifier is not None:
1898  self._histograms = self._histogramModifier(self._histograms)
1899 
1900  if len(self._histograms) > len(_plotStylesColor):
1901  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)))
1902 
1903  # Modify histograms here in case self._name returns numbers
1904  # and self._histogramModifier creates the histograms from
1905  # these numbers
1906  def _modifyHisto(th1, profileX):
1907  if th1 is None:
1908  return None
1909 
1910  if profileX:
1911  th1 = th1.ProfileX()
1912 
1913  if self._fitSlicesY:
1914  ROOT.TH1.AddDirectory(True)
1915  th1.FitSlicesY()
1916  th1 = ROOT.gDirectory.Get(th1.GetName()+"_2")
1917  th1.SetDirectory(None)
1918  #th1.SetName(th1.GetName()+"_ref")
1919  ROOT.TH1.AddDirectory(False)
1920 
1921  if self._title is not None:
1922  th1.SetTitle(self._title)
1923 
1924  if self._scale is not None:
1925  th1.Scale(self._scale)
1926 
1927  return th1
1928 
1929  if self._fallback is not None:
1930  self._histograms = map(_modifyHisto, self._histograms, profileX)
1931  else:
1932  self._histograms = map(lambda h: _modifyHisto(h, self._profileX), self._histograms)
1933  if requireAllHistograms and None in self._histograms:
1934  self._histograms = [None]*len(self._histograms)
1935 
def create(self, tdirNEvents, requireAllHistograms=False)
Definition: plotting.py:1886
def _createOne(self, name, index, tdir, nevents)
Definition: plotting.py:1872
def plotting.Plot.draw (   self,
  pad,
  ratio,
  ratioFactor,
  nrows 
)
Draw the histograms using values for a given algorithm.

Definition at line 1990 of file plotting.py.

References RunHistogramManager._histograms, plotting.Plot._histograms, plotting._mergeBinLabelsX(), plotting._mergeBinLabelsY(), plotting.Plot._normalize(), plotting._th1IncludeOnlyBins(), HistoData.getName(), PhysicsTools::Source.getName(), emtf::Node.getName(), PassiveHit.getName(), ecaldqm::DBReaderWorker.getName(), CocoaMaterialElementary.getName(), LikelihoodSpecies.getName(), EcalLogicID.getName(), ParticleFlux.getName(), PCaloHit.getName(), pftools::SpaceManager.getName(), ecaldqm::DBWriterWorker.getName(), LikelihoodPdf.getName(), TkOfflineVariables.getName(), hcaldqm::mapper::Mapper.getName(), FieldHandlerBase< TOutput >.getName(), FittedEntry.getName(), TrackingRecHitAlgorithm.getName(), hcaldqm::mapper::HashMapper.getName(), jsoncollector::JsonMonitorable.getName(), CSGAction.getName(), AnyMVAEstimatorRun2Base.getName(), L1TUtmAlgorithm.getName(), L1TUtmScale.getName(), MVAVariableManager< ParticleType >.getName(), DTTPGLutFile.getName(), PhysicsTools::MVATrainer.getName(), L1TriggerLutFile.getName(), L1TUtmCondition.getName(), pos::PixelPortcardMap.getName(), QCriterion.getName(), fastsim::InteractionModel.getName(), L1MuGMTReg.getName(), GenericMVAComputer::TaggingVariableIterator< Iter_t >::Value.getName(), GEMStation.getName(), PhysicsTools::Variable::Value.getName(), pftools::SpaceVoxel.getName(), ecaldqm::DQWorker.getName(), RPCAMCLink.getName(), RPCDCCLink.getName(), L1TUtmTriggerMenu.getName(), L1TUtmObject.getName(), L1TUtmCut.getName(), edm::ELslProxy< ELgen >.getName(), L1MuGMTRegMMConfig.getName(), PhysicsTools::MVAModuleHelper< Record, Object, Filler >::Value.getName(), cscdqm::HistoDef.getName(), FourVectorHLT::PathInfo.getName(), RPCLBLink.getName(), MonitorElement.getName(), jsoncollector::DataPoint.getName(), edm::ELseverityLevel.getName(), PhysicsTools::Variable.getName(), PhysicsTools::TrainerMonitoring::Object.getName(), L1MuGMTRegSortRankOffset.getName(), L1MuGMTRegCDLConfig.getName(), cscdqm::CSCHistoDef.getName(), plotting.PlotEmpty.getName(), plotting.Plot.getName(), plotting.Plot.isTGraph2D(), and edm.print().

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

Definition at line 1868 of file plotting.py.

1869  """Return true if the ratio uncertainty should be drawn"""
1870  return self._ratioUncertainty
1871 
def drawRatioUncertainty(self)
Definition: plotting.py:1868
def plotting.Plot.getName (   self)
def plotting.Plot.getNumberOfHistograms (   self)
Return number of existing histograms.

Definition at line 1841 of file plotting.py.

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

Referenced by plotting.Plot.isEmpty().

1842  """Return number of existing histograms."""
1843  return len([h for h in self._histograms if h is not None])
1844 
def getNumberOfHistograms(self)
Definition: plotting.py:1841
def plotting.Plot.isEmpty (   self)
Return true if there are no histograms created for the plot

Definition at line 1845 of file plotting.py.

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

Referenced by plotting.Plot.clone().

1845  def isEmpty(self):
1846  """Return true if there are no histograms created for the plot"""
1847  return self.getNumberOfHistograms() == 0
1848 
def getNumberOfHistograms(self)
Definition: plotting.py:1841
def isEmpty(self)
Definition: plotting.py:1845
def plotting.Plot.isRatio (   self,
  ratio 
)

Definition at line 1855 of file plotting.py.

1855  def isRatio(self, ratio):
1856  if self._ratio is None:
1857  return ratio
1858  return ratio and self._ratio
1859 
def isRatio(self, ratio)
Definition: plotting.py:1855
def plotting.Plot.isTGraph2D (   self)

Definition at line 1849 of file plotting.py.

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

Referenced by plotting.Plot.draw().

1849  def isTGraph2D(self):
1850  for h in self._histograms:
1851  if isinstance(h, ROOT.TGraph2D):
1852  return True
1853  return False
1854 
def isTGraph2D(self)
Definition: plotting.py:1849
def plotting.Plot.setProperties (   self,
  kwargs 
)

Definition at line 1828 of file plotting.py.

1828  def setProperties(self, **kwargs):
1829  for name, value in six.iteritems(kwargs):
1830  if not hasattr(self, "_"+name):
1831  raise Exception("No attribute '%s'" % name)
1832  setattr(self, "_"+name, value)
1833 
def setProperties(self, kwargs)
Definition: plotting.py:1828

Member Data Documentation

plotting.Plot._forLegend
private

Definition at line 2232 of file plotting.py.

plotting.Plot._frame
private

Definition at line 2217 of file plotting.py.

plotting.Plot._histograms
private
plotting.Plot._mainAdditional
private

Definition at line 2091 of file plotting.py.

plotting.Plot._name
private
plotting.Plot._ratioAdditional
private

Definition at line 2092 of file plotting.py.

plotting.Plot._ratios
private

Definition at line 2095 of file plotting.py.

plotting.Plot._tmp_histos
private

Definition at line 2055 of file plotting.py.