CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
Functions | Variables
mpl_axes_hist_fix Namespace Reference

Functions

def hist
 

Variables

 is_sequence_of_strings = cbook.is_sequence_of_strings
 
 is_string_like = cbook.is_string_like
 
 iterable = cbook.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 cmsPerfStripChart.dict, is_sequence_of_strings, is_string_like, iterable, list(), bookConverter.max, min(), GetRecoTauVFromDQM_MC_cff.next, and ComparisonHelper.zip().

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

Definition at line 11 of file mpl_axes_hist_fix.py.

Referenced by hist().

mpl_axes_hist_fix.iterable = cbook.iterable

Definition at line 10 of file mpl_axes_hist_fix.py.

Referenced by hist().