CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
List of all members | Public Member Functions | Private Member Functions | Private Attributes
plotting.Plot Class Reference

Public Member Functions

def __init__
 
def addToLegend
 
def create
 
def draw
 
def getName
 
def getNumberOfHistograms
 

Private Member Functions

def _createOne
 
def _normalize
 
def _setStats
 

Private Attributes

 _frame
 
 _histograms
 
 _name
 

Detailed Description

Represents one plot, comparing one or more histograms.

Definition at line 231 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:
title        -- String for a title of the plot (default None)
xtitle       -- String for x axis title (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)
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)
profileX     -- Take histograms via ProfileX()? (default False)
fitSlicesY   -- Take histograms via FitSlicesY() (default False)
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)
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)
histogramModifier -- Function to be called in create() to modify the histograms (default None)

Definition at line 233 of file plotting.py.

234  def __init__(self, name, **kwargs):
235  """ Constructor.
236 
237  Arguments:
238  name -- String for name of the plot, or Efficiency object
239 
240  Keyword arguments:
241  title -- String for a title of the plot (default None)
242  xtitle -- String for x axis title (default None)
243  ytitle -- String for y axis title (default None)
244  ytitlesize -- Float for y axis title size (default None)
245  ytitleoffset -- Float for y axis title offset (default None)
246  xmin -- Float for x axis minimum (default None, i.e. automatic)
247  xmax -- Float for x axis maximum (default None, i.e. automatic)
248  ymin -- Float for y axis minimum (default 0)
249  ymax -- Float for y axis maximum (default None, i.e. automatic)
250  xlog -- Bool for x axis log status (default False)
251  ylog -- Bool for y axis log status (default False)
252  xgrid -- Bool for x axis grid status (default True)
253  ygrid -- Bool for y axis grid status (default True)
254  stat -- Draw stat box? (default False)
255  fit -- Do gaussian fit? (default False)
256  statx -- Stat box x coordinate (default 0.65)
257  staty -- Stat box y coordinate (default 0.8)
258  statyadjust -- List of floats for stat box y coordinate adjustments (default None)
259  normalizeToUnitArea -- Normalize histograms to unit area? (default False)
260  profileX -- Take histograms via ProfileX()? (default False)
261  fitSlicesY -- Take histograms via FitSlicesY() (default False)
262  scale -- Scale histograms by a number (default None)
263  xbinlabels -- List of x axis bin labels (if given, default None)
264  xbinlabelsize -- Size of x axis bin labels (default None)
265  xbinlabeloption -- Option string for x axis bin labels (default None)
266  drawStyle -- If "hist", draw as line instead of points (default None)
267  drawCommand -- Deliver this to Draw() (default: None for same as drawStyle)
268  lineWidth -- If drawStyle=="hist", the width of line (default 2)
269  legendDx -- Float for moving TLegend in x direction for separate=True (default None)
270  legendDy -- Float for moving TLegend in y direction for separate=True (default None)
271  legendDw -- Float for changing TLegend width for separate=True (default None)
272  legendDh -- Float for changing TLegend height for separate=True (default None)
273  histogramModifier -- Function to be called in create() to modify the histograms (default None)
274  """
275  self._name = name
276 
277  def _set(attr, default):
278  setattr(self, "_"+attr, kwargs.get(attr, default))
279 
280  _set("title", None)
281  _set("xtitle", None)
282  _set("ytitle", None)
283  _set("ytitlesize", None)
284  _set("ytitleoffset", None)
285 
286  _set("xmin", None)
287  _set("xmax", None)
288  _set("ymin", 0.)
289  _set("ymax", None)
290 
291  _set("xlog", False)
292  _set("ylog", False)
293  _set("xgrid", True)
294  _set("ygrid", True)
295 
296  _set("stat", False)
297  _set("fit", False)
298 
299  _set("statx", 0.65)
300  _set("staty", 0.8)
301  _set("statyadjust", None)
302 
303  _set("normalizeToUnitArea", False)
304  _set("profileX", False)
305  _set("fitSlicesY", False)
306  _set("scale", None)
307  _set("xbinlabels", None)
308  _set("xbinlabelsize", None)
309  _set("xbinlabeloption", None)
310 
311  _set("drawStyle", None)
312  _set("drawCommand", None)
313  _set("lineWidth", 2)
314 
315  _set("legendDx", None)
316  _set("legendDy", None)
317  _set("legendDw", None)
318  _set("legendDh", None)
319 
320  _set("histogramModifier", None)
322  self._histograms = []

Member Function Documentation

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

Definition at line 330 of file plotting.py.

References FP420HitsObject._name, TrackerHitsObject._name, PGeometricDet::Item._name, LikelihoodSpecies._name, LikelihoodPdfProduct._name, LikelihoodPdf._name, citk::IsolationConeDefinitionBase._name, DrellYanValidation._name, WValidation._name, HistoParams< T >._name, CutApplicatorBase._name, ElectronMVAEstimatorRun2Phys14NonTrig._name, PhotonMVAEstimatorRun2Spring15NonTrig._name, PhotonMVAEstimatorRun2Phys14NonTrig._name, plotting.FakeDuplicate._name, GeometricDetExtra._name, ElectronMVAEstimatorRun2Spring15NonTrig._name, HistoParams< TH2F >._name, plotting.AggregateBins._name, plotting.AggregateHistos._name, HistoParams< TProfile2D >._name, plotting.Plot._name, Vispa.Views.PropertyView.Property._name, and SequenceTypes.SequencePlaceholder._name.

Referenced by plotting.Plot.create().

331  def _createOne(self, tdir):
332  """Create one histogram from a TDirectory."""
333  if tdir == None:
334  return None
335 
336  # If name is Efficiency instead of string, call its create()
337  if hasattr(self._name, "create"):
338  th1 = self._name.create(tdir)
339  else:
340  th1 = tdir.Get(self._name)
341 
342  # Check the histogram exists
343  if th1 == None:
344  print "Did not find {histo} from {dir}".format(histo=self._name, dir=tdir.GetPath())
345  if missingOk:
346  return None
347  else:
348  sys.exit(1)
349 
350  return th1
def _createOne
Definition: plotting.py:330
def plotting.Plot._normalize (   self)
private
Normalise histograms to unit area

Definition at line 431 of file plotting.py.

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

Referenced by plotting.Plot.draw().

432  def _normalize(self):
433  """Normalise histograms to unit area"""
434 
435  for h in self._histograms:
436  if h is None:
437  continue
438  i = h.Integral()
439  if i == 0:
440  continue
441  h.Scale(1.0/i)
def _normalize
Definition: plotting.py:431
def plotting.Plot._setStats (   self,
  startingX,
  startingY 
)
private
Set stats box.

Definition at line 390 of file plotting.py.

References RunHistogramManager._histograms, plotting.Plot._histograms, DTSC._stat, and DTTrigGeom._stat.

Referenced by plotting.Plot.draw().

391  def _setStats(self, startingX, startingY):
392  """Set stats box."""
393  if not self._stat:
394  for h in self._histograms:
395  if h is not None and hasattr(h, "SetStats"):
396  h.SetStats(0)
397  return
398 
399  def _doStats(h, col, dy):
400  if h is None:
401  return
402  h.SetStats(1)
403 
404  if self._fit:
405  h.Fit("gaus", "Q")
406  f = h.GetListOfFunctions().FindObject("gaus")
407  if f == None:
408  h.SetStats(0)
409  return
410  f.SetLineColor(col)
411  f.SetLineWidth(1)
412  h.Draw()
413  ROOT.gPad.Update()
414  st = h.GetListOfFunctions().FindObject("stats")
415  if self._fit:
416  st.SetOptFit(0010)
417  st.SetOptStat(1001)
418  st.SetX1NDC(startingX)
419  st.SetX2NDC(startingX+0.3)
420  st.SetY1NDC(startingY+dy)
421  st.SetY2NDC(startingY+dy+0.15)
422  st.SetTextColor(col)
423 
424  dy = 0.0
425  for i, h in enumerate(self._histograms):
426  if self._statyadjust is not None and i < len(self._statyadjust):
427  dy += self._statyadjust[i]
428 
429  _doStats(h, _plotStylesColor[i], dy)
430  dy -= 0.19
def plotting.Plot.addToLegend (   self,
  legend,
  legendLabels 
)
Add histograms to a legend.

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

Definition at line 554 of file plotting.py.

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

555  def addToLegend(self, legend, legendLabels):
556  """Add histograms to a legend.
557 
558  Arguments:
559  legend -- TLegend
560  legendLabels -- List of strings for the legend labels
561  """
562  for h, label in zip(self._histograms, legendLabels):
563  if h is None:
564  continue
565  legend.AddEntry(h, label, "LP")
def addToLegend
Definition: plotting.py:554
def plotting.Plot.create (   self,
  tdirs 
)
Create histograms from list of TDirectories

Definition at line 351 of file plotting.py.

References plotting.Plot._createOne(), RunHistogramManager._histograms, plotting.Plot._histograms, plotting.AggregateBins._scale, Vispa.Gui.VispaWidget.VispaWidget._scale, HistoParams< TH1F >._title, HistoParams< TProfile >._title, HistoParams< T >._title, plotting.FakeDuplicate._title, HistoParams< TH2F >._title, HistoParams< TProfile2D >._title, and python.multivaluedict.map().

352  def create(self, tdirs):
353  """Create histograms from list of TDirectories"""
354  self._histograms = [self._createOne(tdir) for tdir in tdirs]
355 
356  if self._histogramModifier is not None:
357  self._histograms = self._histogramModifier(self._histograms)
358 
359  if len(self._histograms) > len(_plotStylesColor):
360  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)))
361 
362  # Modify histograms here in case self._name returns numbers
363  # and self._histogramModifier creates the histograms from
364  # these numbers
365  def _modifyHisto(th1):
366  if th1 is None:
367  return None
368 
369  if self._profileX:
370  th1 = th1.ProfileX()
371 
372  if self._fitSlicesY:
373  ROOT.TH1.AddDirectory(True)
374  th1.FitSlicesY()
375  th1 = ROOT.gDirectory.Get(th1.GetName()+"_2")
376  th1.SetDirectory(None)
377  #th1.SetName(th1.GetName()+"_ref")
378  ROOT.TH1.AddDirectory(False)
379 
380  if self._title is not None:
381  th1.SetTitle(self._title)
382 
383  if self._scale is not None:
384  th1.Scale(self._scale)
385 
386  return th1
387 
388  self._histograms = map(_modifyHisto, self._histograms)
389 
def _createOne
Definition: plotting.py:330
def plotting.Plot.draw (   self,
  algo 
)
Draw the histograms using values for a given algorithm.

Definition at line 442 of file plotting.py.

References plotting._findBounds(), RunHistogramManager._histograms, plotting.Plot._histograms, FP420HitsObject._name, TrackerHitsObject._name, PGeometricDet::Item._name, LikelihoodSpecies._name, LikelihoodPdfProduct._name, LikelihoodPdf._name, citk::IsolationConeDefinitionBase._name, DrellYanValidation._name, WValidation._name, HistoParams< T >._name, CutApplicatorBase._name, ElectronMVAEstimatorRun2Phys14NonTrig._name, PhotonMVAEstimatorRun2Spring15NonTrig._name, PhotonMVAEstimatorRun2Phys14NonTrig._name, plotting.FakeDuplicate._name, GeometricDetExtra._name, ElectronMVAEstimatorRun2Spring15NonTrig._name, HistoParams< TH2F >._name, plotting.AggregateBins._name, plotting.AggregateHistos._name, HistoParams< TProfile2D >._name, plotting.Plot._name, Vispa.Views.PropertyView.Property._name, SequenceTypes.SequencePlaceholder._name, plotting.Plot._normalize(), plotting.Plot._setStats(), MEGeom._xmax, HistoParams< T >._xmax, HistoParams< TH1F >._xmax, HistoParams< TProfile >._xmax, HistoParams< TH2F >._xmax, HistoParams< TProfile2D >._xmax, MEGeom._xmin, HistoParams< TH1F >._xmin, HistoParams< TProfile >._xmin, HistoParams< T >._xmin, HistoParams< TH2F >._xmin, HistoParams< TProfile2D >._xmin, MEGeom._ymax, HistoParams< TProfile >._ymax, HistoParams< T >._ymax, HistoParams< TH1F >._ymax, HistoParams< TH2F >._ymax, HistoParams< TProfile2D >._ymax, MEGeom._ymin, HistoParams< TProfile >._ymin, HistoParams< TH1F >._ymin, HistoParams< T >._ymin, HistoParams< TH2F >._ymin, and HistoParams< TProfile2D >._ymin.

443  def draw(self, algo):
444  """Draw the histograms using values for a given algorithm."""
445  if self._normalizeToUnitArea:
446  self._normalize()
447 
448  def _styleMarker(h, msty, col):
449  h.SetMarkerStyle(msty)
450  h.SetMarkerColor(col)
451  h.SetMarkerSize(0.7)
452  h.SetLineColor(1)
453  h.SetLineWidth(1)
454 
455  def _styleHist(h, msty, col):
456  _styleMarker(h, msty, col)
457  h.SetLineColor(col)
458  h.SetLineWidth(self._lineWidth)
459 
460  # Use marker or hist style
461  style = _styleMarker
462  if self._drawStyle is not None:
463  if "hist" in self._drawStyle.lower():
464  style = _styleHist
465  if isinstance(self._histograms[0], ROOT.TGraph):
466  if "l" in self._drawStyle.lower():
467  style = _styleHist
468 
469  # Apply style to histograms, filter out Nones
470  histos = []
471  for i, h in enumerate(self._histograms):
472  if h is None:
473  continue
474  style(h, _plotStylesMarker[i], _plotStylesColor[i])
475  histos.append(h)
476  if len(histos) == 0:
477  print "No histograms for plot {name}".format(name=self._name)
478  return
479 
480  # Set log and grid
481  ROOT.gPad.SetLogx(self._xlog)
482  ROOT.gPad.SetLogy(self._ylog)
483  ROOT.gPad.SetGridx(self._xgrid)
484  ROOT.gPad.SetGridy(self._ygrid)
485 
486  # Return value if number, or algo-specific value if AlgoOpt
487  def _getVal(val):
488  if hasattr(val, "value"):
489  return val.value(algo)
490  return val
491 
492  bounds = _findBounds(histos,
493  xmin=_getVal(self._xmin), xmax=_getVal(self._xmax),
494  ymin=_getVal(self._ymin), ymax=_getVal(self._ymax))
495 
496  # Create bounds before stats in order to have the
497  # SetRangeUser() calls made before the fit
498  self._setStats(self._statx, self._staty)
499 
500  xbinlabels = self._xbinlabels
501  if xbinlabels is None:
502  if len(histos[0].GetXaxis().GetBinLabel(1)) > 0:
503  xbinlabels = []
504  for i in xrange(1, histos[0].GetNbinsX()+1):
505  xbinlabels.append(histos[0].GetXaxis().GetBinLabel(i))
506 
507  # Create frame
508  if xbinlabels is None:
509  frame = ROOT.gPad.DrawFrame(*bounds)
510  else:
511  # Special form needed if want to set x axis bin labels
512  nbins = len(xbinlabels)
513  frame = ROOT.TH1F("hframe", "hframe", nbins, bounds[0], bounds[2])
514  frame.SetBit(ROOT.TH1.kNoStats)
515  frame.SetBit(ROOT.kCanDelete)
516  frame.SetMinimum(bounds[1])
517  frame.SetMaximum(bounds[3])
518  frame.GetYaxis().SetLimits(bounds[1], bounds[3])
519  frame.Draw("")
520 
521  xaxis = frame.GetXaxis()
522  for i in xrange(nbins):
523  xaxis.SetBinLabel(i+1, xbinlabels[i])
524  if self._xbinlabelsize is not None:
525  xaxis.SetLabelSize(self._xbinlabelsize)
526  if self._xbinlabeloption is not None:
527  frame.LabelsOption(self._xbinlabeloption)
528 
529  # Set properties of frame
530  frame.SetTitle(histos[0].GetTitle())
531  if self._xtitle is not None:
532  frame.GetXaxis().SetTitle(self._xtitle)
533  if self._ytitle is not None:
534  frame.GetYaxis().SetTitle(self._ytitle)
535  if self._ytitlesize is not None:
536  frame.GetYaxis().SetTitleSize(self._ytitlesize)
537  if self._ytitleoffset is not None:
538  frame.GetYaxis().SetTitleOffset(self._ytitleoffset)
539 
540  # Draw histograms
541  opt = "sames" # s for statbox or something?
542  ds = ""
543  if self._drawStyle is not None:
544  ds = self._drawStyle
545  if self._drawCommand is not None:
546  ds = self._drawCommand
547  if len(ds) > 0:
548  opt += " "+ds
549  for h in histos:
550  h.Draw(opt)
551 
552  ROOT.gPad.RedrawAxis()
553  self._frame = frame # keep the frame in memory for sure
def _normalize
Definition: plotting.py:431
def _findBounds
Definition: plotting.py:46
def plotting.Plot.getName (   self)

Definition at line 327 of file plotting.py.

References FP420HitsObject._name, TrackerHitsObject._name, PGeometricDet::Item._name, LikelihoodSpecies._name, LikelihoodPdfProduct._name, LikelihoodPdf._name, citk::IsolationConeDefinitionBase._name, DrellYanValidation._name, WValidation._name, HistoParams< T >._name, CutApplicatorBase._name, ElectronMVAEstimatorRun2Phys14NonTrig._name, PhotonMVAEstimatorRun2Spring15NonTrig._name, PhotonMVAEstimatorRun2Phys14NonTrig._name, plotting.FakeDuplicate._name, GeometricDetExtra._name, ElectronMVAEstimatorRun2Spring15NonTrig._name, HistoParams< TH2F >._name, plotting.AggregateBins._name, plotting.AggregateHistos._name, HistoParams< TProfile2D >._name, plotting.Plot._name, Vispa.Views.PropertyView.Property._name, and SequenceTypes.SequencePlaceholder._name.

328  def getName(self):
329  return str(self._name)
def plotting.Plot.getNumberOfHistograms (   self)
Return number of existing histograms.

Definition at line 323 of file plotting.py.

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

324  def getNumberOfHistograms(self):
325  """Return number of existing histograms."""
326  return len(self._histograms)
def getNumberOfHistograms
Definition: plotting.py:323

Member Data Documentation

plotting.Plot._frame
private

Definition at line 552 of file plotting.py.

plotting.Plot._histograms
private

Definition at line 321 of file plotting.py.

Referenced by plotting.Plot._normalize(), plotting.Plot._setStats(), plotting.Plot.addToLegend(), plotting.Plot.create(), plotting.Plot.draw(), and plotting.Plot.getNumberOfHistograms().

plotting.Plot._name
private

Definition at line 274 of file plotting.py.

Referenced by plotting.Plot._createOne(), plotting.PlotGroup._save(), plotting.Plot.draw(), and plotting.Plot.getName().