CMS 3D CMS Logo

Functions | Variables
mpl_axes_hist_fix Namespace Reference

Functions

def hist (self, x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, kwargs)
 

Variables

 is_sequence_of_strings
 
 is_string_like
 
 iterable
 

Function Documentation

def mpl_axes_hist_fix.hist (   self,
  x,
  bins = 10,
  range = None,
  normed = False,
  weights = None,
  cumulative = False,
  bottom = None,
  histtype = 'bar',
  align = 'mid',
  orientation = 'vertical',
  rwidth = None,
  log = False,
  color = None,
  label = None,
  kwargs 
)
call signature::

  hist(x, bins=10, range=None, normed=False, cumulative=False,
       bottom=None, histtype='bar', align='mid',
       orientation='vertical', rwidth=None, log=False, **kwargs)

Compute and draw the histogram of *x*. The return value is a
tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,
[*patches0*, *patches1*,...]) if the input contains multiple
data.

Multiple data can be provided via *x* as a list of datasets
of potentially different length ([*x0*, *x1*, ...]), or as
a 2-D ndarray in which each column is a dataset.  Note that
the ndarray form is transposed relative to the list form.

Masked arrays are not supported at present.

Keyword arguments:

  *bins*:
    Either an integer number of bins or a sequence giving the
    bins.  If *bins* is an integer, *bins* + 1 bin edges
    will be returned, consistent with :func:`numpy.histogram`
    for numpy version >= 1.3, and with the *new* = True argument
    in earlier versions.
    Unequally spaced bins are supported if *bins* is a sequence.

  *range*:
    The lower and upper range of the bins. Lower and upper outliers
    are ignored. If not provided, *range* is (x.min(), x.max()).
    Range has no effect if *bins* is a sequence.

    If *bins* is a sequence or *range* is specified, autoscaling
    is based on the specified bin range instead of the
    range of x.

  *normed*:
    If *True*, the first element of the return tuple will
    be the counts normalized to form a probability density, i.e.,
    ``n/(len(x)*dbin)``.  In a probability density, the integral of
    the histogram should be 1; you can verify that with a
    trapezoidal integration of the probability density function::

      pdf, bins, patches = ax.hist(...)
      print np.sum(pdf * np.diff(bins))

    .. Note:: Until numpy release 1.5, the underlying numpy
              histogram function was incorrect with *normed*=*True*
              if bin sizes were unequal.  MPL inherited that
              error.  It is now corrected within MPL when using
              earlier numpy versions

  *weights*
    An array of weights, of the same shape as *x*.  Each value in
    *x* only contributes its associated weight towards the bin
    count (instead of 1).  If *normed* is True, the weights are
    normalized, so that the integral of the density over the range
    remains 1.

  *cumulative*:
    If *True*, then a histogram is computed where each bin
    gives the counts in that bin plus all bins for smaller values.
    The last bin gives the total number of datapoints.  If *normed*
    is also *True* then the histogram is normalized such that the
    last bin equals 1. If *cumulative* evaluates to less than 0
    (e.g. -1), the direction of accumulation is reversed.  In this
    case, if *normed* is also *True*, then the histogram is normalized
    such that the first bin equals 1.

  *histtype*: [ 'bar' | 'barstacked' | 'step' | 'stepfilled' ]
    The type of histogram to draw.

      - 'bar' is a traditional bar-type histogram.  If multiple data
        are given the bars are aranged side by side.

      - 'barstacked' is a bar-type histogram where multiple
        data are stacked on top of each other.

      - 'step' generates a lineplot that is by default
        unfilled.

      - 'stepfilled' generates a lineplot that is by default
        filled.

  *align*: ['left' | 'mid' | 'right' ]
    Controls how the histogram is plotted.

      - 'left': bars are centered on the left bin edges.

      - 'mid': bars are centered between the bin edges.

      - 'right': bars are centered on the right bin edges.

  *orientation*: [ 'horizontal' | 'vertical' ]
    If 'horizontal', :func:`~matplotlib.pyplot.barh` will be
    used for bar-type histograms and the *bottom* kwarg will be
    the left edges.

  *rwidth*:
    The relative width of the bars as a fraction of the bin
    width.  If *None*, automatically compute the width. Ignored
    if *histtype* = 'step' or 'stepfilled'.

  *log*:
    If *True*, the histogram axis will be set to a log scale.
    If *log* is *True* and *x* is a 1D array, empty bins will
    be filtered out and only the non-empty (*n*, *bins*,
    *patches*) will be returned.

  *color*:
    Color spec or sequence of color specs, one per
    dataset.  Default (*None*) uses the standard line
    color sequence.

  *label*:
    String, or sequence of strings to match multiple
    datasets.  Bar charts yield multiple patches per
    dataset, but only the first gets the label, so
    that the legend command will work as expected::

        ax.hist(10+2*np.random.randn(1000), label='men')
        ax.hist(12+3*np.random.randn(1000), label='women', alpha=0.5)
        ax.legend()

kwargs are used to update the properties of the
:class:`~matplotlib.patches.Patch` instances returned by *hist*:

%(Patch)s

**Example:**

.. plot:: mpl_examples/pylab_examples/histogram_demo.py

Definition at line 18 of file mpl_axes_hist_fix.py.

References python.LumiList.DeprecationWarning, cmsPerfStripChart.dict, objects.autophobj.float, is_sequence_of_strings, is_string_like, iterable, list(), hpstanc_transforms.max, min(), GetRecoTauVFromDQM_MC_cff.next, and ComparisonHelper.zip().

18  **kwargs):
19  """
20  call signature::
21 
22  hist(x, bins=10, range=None, normed=False, cumulative=False,
23  bottom=None, histtype='bar', align='mid',
24  orientation='vertical', rwidth=None, log=False, **kwargs)
25 
26  Compute and draw the histogram of *x*. The return value is a
27  tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,
28  [*patches0*, *patches1*,...]) if the input contains multiple
29  data.
30 
31  Multiple data can be provided via *x* as a list of datasets
32  of potentially different length ([*x0*, *x1*, ...]), or as
33  a 2-D ndarray in which each column is a dataset. Note that
34  the ndarray form is transposed relative to the list form.
35 
36  Masked arrays are not supported at present.
37 
38  Keyword arguments:
39 
40  *bins*:
41  Either an integer number of bins or a sequence giving the
42  bins. If *bins* is an integer, *bins* + 1 bin edges
43  will be returned, consistent with :func:`numpy.histogram`
44  for numpy version >= 1.3, and with the *new* = True argument
45  in earlier versions.
46  Unequally spaced bins are supported if *bins* is a sequence.
47 
48  *range*:
49  The lower and upper range of the bins. Lower and upper outliers
50  are ignored. If not provided, *range* is (x.min(), x.max()).
51  Range has no effect if *bins* is a sequence.
52 
53  If *bins* is a sequence or *range* is specified, autoscaling
54  is based on the specified bin range instead of the
55  range of x.
56 
57  *normed*:
58  If *True*, the first element of the return tuple will
59  be the counts normalized to form a probability density, i.e.,
60  ``n/(len(x)*dbin)``. In a probability density, the integral of
61  the histogram should be 1; you can verify that with a
62  trapezoidal integration of the probability density function::
63 
64  pdf, bins, patches = ax.hist(...)
65  print np.sum(pdf * np.diff(bins))
66 
67  .. Note:: Until numpy release 1.5, the underlying numpy
68  histogram function was incorrect with *normed*=*True*
69  if bin sizes were unequal. MPL inherited that
70  error. It is now corrected within MPL when using
71  earlier numpy versions
72 
73  *weights*
74  An array of weights, of the same shape as *x*. Each value in
75  *x* only contributes its associated weight towards the bin
76  count (instead of 1). If *normed* is True, the weights are
77  normalized, so that the integral of the density over the range
78  remains 1.
79 
80  *cumulative*:
81  If *True*, then a histogram is computed where each bin
82  gives the counts in that bin plus all bins for smaller values.
83  The last bin gives the total number of datapoints. If *normed*
84  is also *True* then the histogram is normalized such that the
85  last bin equals 1. If *cumulative* evaluates to less than 0
86  (e.g. -1), the direction of accumulation is reversed. In this
87  case, if *normed* is also *True*, then the histogram is normalized
88  such that the first bin equals 1.
89 
90  *histtype*: [ 'bar' | 'barstacked' | 'step' | 'stepfilled' ]
91  The type of histogram to draw.
92 
93  - 'bar' is a traditional bar-type histogram. If multiple data
94  are given the bars are aranged side by side.
95 
96  - 'barstacked' is a bar-type histogram where multiple
97  data are stacked on top of each other.
98 
99  - 'step' generates a lineplot that is by default
100  unfilled.
101 
102  - 'stepfilled' generates a lineplot that is by default
103  filled.
104 
105  *align*: ['left' | 'mid' | 'right' ]
106  Controls how the histogram is plotted.
107 
108  - 'left': bars are centered on the left bin edges.
109 
110  - 'mid': bars are centered between the bin edges.
111 
112  - 'right': bars are centered on the right bin edges.
113 
114  *orientation*: [ 'horizontal' | 'vertical' ]
115  If 'horizontal', :func:`~matplotlib.pyplot.barh` will be
116  used for bar-type histograms and the *bottom* kwarg will be
117  the left edges.
118 
119  *rwidth*:
120  The relative width of the bars as a fraction of the bin
121  width. If *None*, automatically compute the width. Ignored
122  if *histtype* = 'step' or 'stepfilled'.
123 
124  *log*:
125  If *True*, the histogram axis will be set to a log scale.
126  If *log* is *True* and *x* is a 1D array, empty bins will
127  be filtered out and only the non-empty (*n*, *bins*,
128  *patches*) will be returned.
129 
130  *color*:
131  Color spec or sequence of color specs, one per
132  dataset. Default (*None*) uses the standard line
133  color sequence.
134 
135  *label*:
136  String, or sequence of strings to match multiple
137  datasets. Bar charts yield multiple patches per
138  dataset, but only the first gets the label, so
139  that the legend command will work as expected::
140 
141  ax.hist(10+2*np.random.randn(1000), label='men')
142  ax.hist(12+3*np.random.randn(1000), label='women', alpha=0.5)
143  ax.legend()
144 
145  kwargs are used to update the properties of the
146  :class:`~matplotlib.patches.Patch` instances returned by *hist*:
147 
148  %(Patch)s
149 
150  **Example:**
151 
152  .. plot:: mpl_examples/pylab_examples/histogram_demo.py
153  """
154  if not self._hold: self.cla()
155 
156  # NOTE: the range keyword overwrites the built-in func range !!!
157  # needs to be fixed in numpy !!!
158 
159  # Validate string inputs here so we don't have to clutter
160  # subsequent code.
161  if histtype not in ['bar', 'barstacked', 'step', 'stepfilled']:
162  raise ValueError("histtype %s is not recognized" % histtype)
163 
164  if align not in ['left', 'mid', 'right']:
165  raise ValueError("align kwarg %s is not recognized" % align)
166 
167  if orientation not in [ 'horizontal', 'vertical']:
168  raise ValueError(
169  "orientation kwarg %s is not recognized" % orientation)
170 
171 
172  if kwargs.get('width') is not None:
173  raise DeprecationWarning(
174  'hist now uses the rwidth to give relative width '
175  'and not absolute width')
176 
177  # Massage 'x' for processing.
178  # NOTE: Be sure any changes here is also done below to 'weights'
179  if isinstance(x, np.ndarray) or not iterable(x[0]):
180  # TODO: support masked arrays;
181  x = np.asarray(x)
182  if x.ndim == 2:
183  x = x.T # 2-D input with columns as datasets; switch to rows
184  elif x.ndim == 1:
185  x = x.reshape(1, x.shape[0]) # new view, single row
186  else:
187  raise ValueError("x must be 1D or 2D")
188  if x.shape[1] < x.shape[0]:
189  warnings.warn('2D hist input should be nsamples x nvariables;\n '
190  'this looks transposed (shape is %d x %d)' % x.shape[::-1])
191  else:
192  # multiple hist with data of different length
193  x = [np.array(xi) for xi in x]
194 
195  nx = len(x) # number of datasets
196 
197  if color is None:
198  color = [next(self._get_lines.color_cycle)
199  for i in xrange(nx)]
200  else:
201  color = mcolors.colorConverter.to_rgba_array(color)
202  if len(color) != nx:
203  raise ValueError("color kwarg must have one color per dataset")
204 
205  # We need to do to 'weights' what was done to 'x'
206  if weights is not None:
207  if isinstance(weights, np.ndarray) or not iterable(weights[0]) :
208  w = np.array(weights)
209  if w.ndim == 2:
210  w = w.T
211  elif w.ndim == 1:
212  w.shape = (1, w.shape[0])
213  else:
214  raise ValueError("weights must be 1D or 2D")
215  else:
216  w = [np.array(wi) for wi in weights]
217 
218  if len(w) != nx:
219  raise ValueError('weights should have the same shape as x')
220  for i in xrange(nx):
221  if len(w[i]) != len(x[i]):
222  raise ValueError(
223  'weights should have the same shape as x')
224  else:
225  w = [None]*nx
226 
227 
228  # Save autoscale state for later restoration; turn autoscaling
229  # off so we can do it all a single time at the end, instead
230  # of having it done by bar or fill and then having to be redone.
231  _saved_autoscalex = self.get_autoscalex_on()
232  _saved_autoscaley = self.get_autoscaley_on()
233  self.set_autoscalex_on(False)
234  self.set_autoscaley_on(False)
235 
236  # Save the datalimits for the same reason:
237  _saved_bounds = self.dataLim.bounds
238 
239  # Check whether bins or range are given explicitly. In that
240  # case use those values for autoscaling.
241  binsgiven = (cbook.iterable(bins) or range != None)
242 
243  # If bins are not specified either explicitly or via range,
244  # we need to figure out the range required for all datasets,
245  # and supply that to np.histogram.
246  if not binsgiven:
247  xmin = np.inf
248  xmax = -np.inf
249  for xi in x:
250  xmin = min(xmin, xi.min())
251  xmax = max(xmax, xi.max())
252  range = (xmin, xmax)
253 
254  #hist_kwargs = dict(range=range, normed=bool(normed))
255  # We will handle the normed kwarg within mpl until we
256  # get to the point of requiring numpy >= 1.5.
257  hist_kwargs = dict(range=range)
258  if np.__version__ < "1.3": # version 1.1 and 1.2
259  hist_kwargs['new'] = True
260 
261  n = []
262  for i in xrange(nx):
263  # this will automatically overwrite bins,
264  # so that each histogram uses the same bins
265  m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
266  if normed:
267  db = np.diff(bins)
268  m = (m.astype(float) / db) / m.sum()
269  n.append(m)
270  if normed and db.std() > 0.01 * db.mean():
271  warnings.warn("""
272  This release fixes a normalization bug in the NumPy histogram
273  function prior to version 1.5, occuring with non-uniform
274  bin widths. The returned and plotted value is now a density:
275  n / (N * bin width),
276  where n is the bin count and N the total number of points.
277  """)
278 
279 
280 
281  if cumulative:
282  slc = slice(None)
283  if cbook.is_numlike(cumulative) and cumulative < 0:
284  slc = slice(None,None,-1)
285 
286  if normed:
287  n = [(m * np.diff(bins))[slc].cumsum()[slc] for m in n]
288  else:
289  n = [m[slc].cumsum()[slc] for m in n]
290 
291  patches = []
292 
293  if histtype.startswith('bar'):
294  totwidth = np.diff(bins)
295 
296  if rwidth is not None:
297  dr = min(1.0, max(0.0, rwidth))
298  elif len(n)>1:
299  dr = 0.8
300  else:
301  dr = 1.0
302 
303  if histtype=='bar':
304  width = dr*totwidth/nx
305  dw = width
306 
307  if nx > 1:
308  boffset = -0.5*dr*totwidth*(1.0-1.0/nx)
309  else:
310  boffset = 0.0
311  stacked = False
312  elif histtype=='barstacked':
313  width = dr*totwidth
314  boffset, dw = 0.0, 0.0
315  stacked = True
316 
317  if align == 'mid' or align == 'edge':
318  boffset += 0.5*totwidth
319  elif align == 'right':
320  boffset += totwidth
321 
322  if orientation == 'horizontal':
323  _barfunc = self.barh
324  else: # orientation == 'vertical'
325  _barfunc = self.bar
326 
327  for m, c in zip(n, color):
328  patch = _barfunc(bins[:-1]+boffset, m, width, bottom,
329  align='center', log=log,
330  color=c)
331  patches.append(patch)
332  if stacked:
333  if bottom is None:
334  bottom = 0.0
335  bottom += m
336  boffset += dw
337 
338  elif histtype.startswith('step'):
339  x = np.zeros( 2*len(bins), np.float )
340  y = np.zeros( 2*len(bins), np.float )
341 
342  x[0::2], x[1::2] = bins, bins
343 
344  # FIX FIX FIX
345  # This is the only real change.
346  # minimum = min(bins)
347  if log is True:
348  minimum = 1.0
349  elif log:
350  minimum = float(log)
351  else:
352  minimum = 0.0
353  # FIX FIX FIX end
354 
355  if align == 'left' or align == 'center':
356  x -= 0.5*(bins[1]-bins[0])
357  elif align == 'right':
358  x += 0.5*(bins[1]-bins[0])
359 
360  if log:
361  y[0],y[-1] = minimum, minimum
362  if orientation == 'horizontal':
363  self.set_xscale('log')
364  else: # orientation == 'vertical'
365  self.set_yscale('log')
366 
367  fill = (histtype == 'stepfilled')
368 
369  for m, c in zip(n, color):
370  y[1:-1:2], y[2::2] = m, m
371  if log:
372  y[y<minimum]=minimum
373  if orientation == 'horizontal':
374  x,y = y,x
375 
376  if fill:
377  patches.append( self.fill(x, y,
378  closed=False, facecolor=c) )
379  else:
380  patches.append( self.fill(x, y,
381  closed=False, edgecolor=c, fill=False) )
382 
383  # adopted from adjust_x/ylim part of the bar method
384  if orientation == 'horizontal':
385  xmin0 = max(_saved_bounds[0]*0.9, minimum)
386  xmax = self.dataLim.intervalx[1]
387  for m in n:
388  xmin = np.amin(m[m!=0]) # filter out the 0 height bins
389  xmin = max(xmin*0.9, minimum)
390  xmin = min(xmin0, xmin)
391  self.dataLim.intervalx = (xmin, xmax)
392  elif orientation == 'vertical':
393  ymin0 = max(_saved_bounds[1]*0.9, minimum)
394  ymax = self.dataLim.intervaly[1]
395  for m in n:
396  ymin = np.amin(m[m!=0]) # filter out the 0 height bins
397  ymin = max(ymin*0.9, minimum)
398  ymin = min(ymin0, ymin)
399  self.dataLim.intervaly = (ymin, ymax)
400 
401  if label is None:
402  labels = ['_nolegend_']
403  elif is_string_like(label):
404  labels = [label]
405  elif is_sequence_of_strings(label):
406  labels = list(label)
407  else:
408  raise ValueError(
409  'invalid label: must be string or sequence of strings')
410  if len(labels) < nx:
411  labels += ['_nolegend_'] * (nx - len(labels))
412 
413  for (patch, lbl) in zip(patches, labels):
414  for p in patch:
415  p.update(kwargs)
416  p.set_label(lbl)
417  lbl = '_nolegend_'
418 
419  if binsgiven:
420  if orientation == 'vertical':
421  self.update_datalim([(bins[0],0), (bins[-1],0)], updatey=False)
422  else:
423  self.update_datalim([(0,bins[0]), (0,bins[-1])], updatex=False)
424 
425  self.set_autoscalex_on(_saved_autoscalex)
426  self.set_autoscaley_on(_saved_autoscaley)
427  self.autoscale_view()
428 
429  if nx == 1:
430  return n[0], bins, cbook.silent_list('Patch', patches[0])
431  else:
432  return n, bins, cbook.silent_list('Lists of Patches', patches)
433 
OutputIterator zip(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)
T min(T a, T b)
Definition: MathUtil.h:58
How EventSelector::AcceptEvent() decides whether to accept an event for output otherwise it is excluding the probing of A single or multiple positive and the trigger will pass if any such matching triggers are PASS or EXCEPTION[A criterion thatmatches no triggers at all is detected and causes a throw.] A single negative with an expectation of appropriate bit checking in the decision and the trigger will pass if any such matching triggers are FAIL or EXCEPTION A wildcarded negative criterion that matches more than one trigger in the trigger list("!*","!HLTx*"if it matches 2 triggers or more) will accept the event if all the matching triggers are FAIL.It will reject the event if any of the triggers are PASS or EXCEPTION(this matches the behavior of"!*"before the partial wildcard feature was incorporated).Triggers which are in the READY state are completely ignored.(READY should never be returned since the trigger paths have been run

Variable Documentation

mpl_axes_hist_fix.is_sequence_of_strings

Definition at line 12 of file mpl_axes_hist_fix.py.

Referenced by hist().

mpl_axes_hist_fix.is_string_like

Definition at line 11 of file mpl_axes_hist_fix.py.

Referenced by hist().

mpl_axes_hist_fix.iterable

Definition at line 10 of file mpl_axes_hist_fix.py.

Referenced by hist().