From bf2053f57fd3f76a0c686b3f3ec844bfe048ea4f Mon Sep 17 00:00:00 2001 From: Moritz Boehle Date: Thu, 30 Mar 2017 16:05:03 +0200 Subject: [PATCH 1/4] FIX: Introduced new keyword 'density' in the hist function to be consistent with numpy Reformatted according to pep8 Added tests for density. Style fixes in hist function. Density and normed cannot be set to not None at the same time anymore. Density and normed cannot be set to not None at the same time anymore. --- lib/matplotlib/axes/_axes.py | 47 ++++++++++++++++++------------- lib/matplotlib/pyplot.py | 19 +++++++------ lib/matplotlib/tests/test_axes.py | 30 ++++++++++++++++++++ 3 files changed, 67 insertions(+), 29 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 30712f937875..aaab75d37175 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -91,7 +91,6 @@ def _plot_args_replacer(args, data): # The axes module contains all the wrappers to plotting functions. # All the other methods should go in the _AxesBase class. - class Axes(_AxesBase): """ The :class:`Axes` contains most of the figure elements: @@ -5852,9 +5851,9 @@ def table(self, **kwargs): #### Data analysis @_preprocess_data(replace_names=["x", 'weights'], label_namer="x") - def hist(self, x, bins=None, range=None, normed=False, weights=None, - cumulative=False, bottom=None, histtype='bar', align='mid', - orientation='vertical', rwidth=None, log=False, + def hist(self, x, bins=None, range=None, density=None, normed=None, + weights=None, cumulative=False, bottom=None, histtype='bar', + align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, **kwargs): """ @@ -5900,7 +5899,7 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None, Default is ``None`` - normed : boolean, optional + density : boolean, optional If `True`, the first element of the return tuple will be the counts normalized to form a probability density, i.e., the area (or integral) under the histogram will sum to 1. @@ -5909,7 +5908,11 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None, of observations. If `stacked` is also `True`, the sum of the histograms is normalized to 1. - Default is ``False`` + Default is ``None``, behaves as ``False``. + + normed : boolean, optional + Will be deprecated, same role as density. For consistency + with NumPy 2.0.0 keyword density has been introduced. weights : (n, ) array_like or None, optional An array of weights, of the same shape as `x`. Each value in `x` @@ -6069,6 +6072,11 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None, if histtype == 'barstacked' and not stacked: stacked = True + if density is not None and normed is not None: + raise ValueError("kwargs 'density' and 'normed' cannot be used" + "simultaneously. Please only use 'density', since " + "'normed' will be deprecated. ") + # process the unit information self._process_unit_info(xdata=x, kwargs=kwargs) x = self.convert_xunits(x) @@ -6120,11 +6128,11 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None, xmin = min(xmin, xi.min()) xmax = max(xmax, xi.max()) bin_range = (xmin, xmax) - - # hist_kwargs = dict(range=range, normed=bool(normed)) - # We will handle the normed kwarg within mpl until we - # get to the point of requiring numpy >= 1.5. - hist_kwargs = dict(range=bin_range) + density = bool(density) or bool(normed) + if density and not stacked: + hist_kwargs = dict(range=bin_range, density=density) + else: + hist_kwargs = dict(range=bin_range) n = [] mlast = None @@ -6135,9 +6143,7 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None, m = m.astype(float) # causes problems later if it's an int if mlast is None: mlast = np.zeros(len(bins)-1, m.dtype) - if normed and not stacked: - db = np.diff(bins) - m = (m.astype(float) / db) / m.sum() + if stacked: if mlast is None: mlast = np.zeros(len(bins)-1, m.dtype) @@ -6145,7 +6151,7 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None, mlast[:] = m n.append(m) - if stacked and normed: + if stacked and density: db = np.diff(bins) for m in n: m[:] = (m.astype(float) / db) / n[-1].sum() @@ -6154,7 +6160,7 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None, if cbook.is_numlike(cumulative) and cumulative < 0: slc = slice(None, None, -1) - if normed: + if density: n = [(m * np.diff(bins))[slc].cumsum()[slc] for m in n] else: n = [m[slc].cumsum()[slc] for m in n] @@ -6241,13 +6247,14 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None, # Setting a minimum of 0 results in problems for log plots if np.min(bottom) > 0: minimum = np.min(bottom) - elif normed or weights is not None: - # For normed data, set to minimum data value / logbase - # (gives 1 full tick-label unit for the lowest filled bin) + elif density or weights is not None: + # For normed (density = True) data full tick-label unit + # for the lowest filled bin) ndata = np.array(n) minimum = (np.min(ndata[ndata > 0])) / logbase else: - # For non-normed data, set the min to 1 / log base, + # For non-normed (density = False) data, + # set the min to 1 / log base, # again so that there is 1 full tick-label unit # for the lowest bin minimum = 1.0 / logbase diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index 1b694498e62d..97424a7b1a22 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -2992,10 +2992,10 @@ def hexbin(x, y, C=None, gridsize=100, bins=None, xscale='linear', # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.hist) -def hist(x, bins=None, range=None, normed=False, weights=None, cumulative=False, - bottom=None, histtype='bar', align='mid', orientation='vertical', - rwidth=None, log=False, color=None, label=None, stacked=False, - hold=None, data=None, **kwargs): +def hist(x, bins=None, range=None, density=None, normed=None, weights=None, + cumulative=False, bottom=None, histtype='bar', align='mid', + orientation='vertical', rwidth=None, log=False, color=None, label=None, + stacked=False, hold=None, data=None, **kwargs): ax = gca() # Deprecated: allow callers to override the hold state # by passing hold=True|False @@ -3007,11 +3007,12 @@ def hist(x, bins=None, range=None, normed=False, weights=None, cumulative=False, warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", mplDeprecation) try: - ret = ax.hist(x, bins=bins, range=range, normed=normed, - weights=weights, cumulative=cumulative, bottom=bottom, - histtype=histtype, align=align, orientation=orientation, - rwidth=rwidth, log=log, color=color, label=label, - stacked=stacked, data=data, **kwargs) + ret = ax.hist(x, bins=bins, range=range, density=density, + normed=normed, weights=weights, cumulative=cumulative, + bottom=bottom, histtype=histtype, align=align, + orientation=orientation, rwidth=rwidth, log=log, + color=color, label=label, stacked=stacked, data=data, + **kwargs) finally: ax._hold = washold diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 09a75616db69..481072ac5c2b 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -2775,6 +2775,36 @@ def test_hist_stacked_normed(): ax = fig.add_subplot(111) ax.hist((d1, d2), stacked=True, normed=True) +@image_comparison(baseline_images=['hist_stacked_normed']) +def test_hist_stacked_density(): + # make some data + d1 = np.linspace(1, 3, 20) + d2 = np.linspace(0, 10, 50) + fig = plt.figure() + ax = fig.add_subplot(111) + ax.hist((d1, d2), stacked=True, density=True) + + +def test_hist_normed_density(): + #Normed and density should not be used simultaneously + d1 = np.linspace(1, 3, 20) + d2 = np.linspace(0, 10, 50) + fig = plt.figure() + ax = fig.add_subplot(111) + #test that kwargs normed and density cannot be set both. + with pytest.raises(Exception): + ax.hist((d1, d2), stacked=True, normed=True, density=True) + + with pytest.raises(Exception): + ax.hist((d1, d2), stacked=True, normed=False, density=True) + + with pytest.raises(Exception): + ax.hist((d1, d2), stacked=True, normed=False, density=False) + + with pytest.raises(Exception): + ax.hist((d1, d2), stacked=True, normed=True, density=False) + + @image_comparison(baseline_images=['hist_step_bottom'], extensions=['png'], remove_text=True) From 138239de88287281c0f05a47ec9a49544867a3f4 Mon Sep 17 00:00:00 2001 From: chelseatroy Date: Mon, 16 Jan 2017 22:00:21 -0600 Subject: [PATCH 2/4] Replace hist normed arg with density arg in a backward-compatible way. Update documentation to reflect addition of density arg to hist Adjust documentation and test formatting Raise if density and normed are both set in hist Update documentation to match pep8 guidelines --- lib/matplotlib/axes/_axes.py | 104 +++++++++++++++++++++++------- lib/matplotlib/tests/test_axes.py | 5 +- 2 files changed, 81 insertions(+), 28 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index aaab75d37175..fc8117fd5a9a 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -5851,10 +5851,10 @@ def table(self, **kwargs): #### Data analysis @_preprocess_data(replace_names=["x", 'weights'], label_namer="x") - def hist(self, x, bins=None, range=None, density=None, normed=None, - weights=None, cumulative=False, bottom=None, histtype='bar', - align='mid', orientation='vertical', rwidth=None, log=False, - color=None, label=None, stacked=False, + def hist(self, x, bins=None, range=None, density=None, weights=None, + cumulative=False, bottom=None, histtype='bar', align='mid', + orientation='vertical', rwidth=None, log=False, + color=None, label=None, stacked=False, normed=None, **kwargs): """ Plot a histogram. @@ -5899,7 +5899,10 @@ def hist(self, x, bins=None, range=None, density=None, normed=None, Default is ``None`` - density : boolean, optional + normed, density : boolean, optional + Either the 'normed' or the 'density' arg can be set to + accomplish this behavior: + If `True`, the first element of the return tuple will be the counts normalized to form a probability density, i.e., the area (or integral) under the histogram will sum to 1. @@ -5908,28 +5911,31 @@ def hist(self, x, bins=None, range=None, density=None, normed=None, of observations. If `stacked` is also `True`, the sum of the histograms is normalized to 1. - Default is ``None``, behaves as ``False``. + Default is ``None`` for both 'normed' and 'density.' If either is + set, then that value will be used. If neither are set, then the args + will be treated as 'False.' - normed : boolean, optional - Will be deprecated, same role as density. For consistency - with NumPy 2.0.0 keyword density has been introduced. + If both are set to different things, the hist function raises an + error. weights : (n, ) array_like or None, optional 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. + (instead of 1). If `normed` or 'density' is True, + the weights are normalized, so that the integral of the density + over the range remains 1. Default is ``None`` cumulative : boolean, optional 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 + gives the total number of datapoints. If `normed` or 'density' + 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` and/or 'density' is also `True`, then the histogram is + normalized such that the first bin equals 1. Default is ``False`` @@ -6012,12 +6018,13 @@ def hist(self, x, bins=None, range=None, density=None, normed=None, Returns ------- n : array or list of arrays - The values of the histogram bins. See **normed** and **weights** - for a description of the possible semantics. If input **x** is an - array, then this is an array of length **nbins**. If input is a - sequence arrays ``[data1, data2,..]``, then this is a list of - arrays with the values of the histograms for each of the arrays - in the same order. + The values of the histogram bins. See **normed or density** + and **weights** for a description of the possible semantics. + If input **x** is an array, then this is an array of length + **nbins**. If input is a sequence arrays + ``[data1, data2,..]``, then this is a list of arrays with + the values of the histograms for each of the arrays in the + same order. bins : array The edges of the bins. Length nbins + 1 (nbins left edges and right @@ -6048,6 +6055,50 @@ def hist(self, x, bins=None, range=None, density=None, normed=None, bin_range = range del range + # Sets the density variable, if necessary, to its predecessor, 'normed.' + if density is not None and normed is not None: + raise ValueError('The density and normed arguments represent the ' + 'same concept. Please set only one of them.') + elif normed is not None and density is None: + density = normed + elif normed is None and density is None: + density = False + + def _normalize_input(inp, ename='input'): + """Normalize 1 or 2d input into list of np.ndarray or + a single 2D np.ndarray. + + Parameters + ---------- + inp : iterable + ename : str, optional + Name to use in ValueError if `inp` can not be normalized + + """ + if (isinstance(x, np.ndarray) or + not iterable(cbook.safe_first_element(inp))): + # TODO: support masked arrays; + inp = np.asarray(inp) + if inp.ndim == 2: + # 2-D input with columns as datasets; switch to rows + inp = inp.T + elif inp.ndim == 1: + # new view, single row + inp = inp.reshape(1, inp.shape[0]) + else: + raise ValueError( + "{ename} must be 1D or 2D".format(ename=ename)) + if inp.shape[1] < inp.shape[0]: + warnings.warn( + '2D hist input should be nsamples x nvariables;\n ' + 'this looks transposed ' + '(shape is %d x %d)' % inp.shape[::-1]) + else: + # multiple hist with data of different length + inp = [np.asarray(xi) for xi in inp] + + return inp + if not self._hold: self.cla() @@ -6143,7 +6194,9 @@ def hist(self, x, bins=None, range=None, density=None, normed=None, m = m.astype(float) # causes problems later if it's an int if mlast is None: mlast = np.zeros(len(bins)-1, m.dtype) - + if density and not stacked: + db = np.diff(bins) + m = (m.astype(float) / db) / m.sum() if stacked: if mlast is None: mlast = np.zeros(len(bins)-1, m.dtype) @@ -6248,8 +6301,9 @@ def hist(self, x, bins=None, range=None, density=None, normed=None, if np.min(bottom) > 0: minimum = np.min(bottom) elif density or weights is not None: - # For normed (density = True) data full tick-label unit - # for the lowest filled bin) + # For data that is normed to form a probability density, + # set to minimum data value / logbase + # (gives 1 full tick-label unit for the lowest filled bin) ndata = np.array(n) minimum = (np.min(ndata[ndata > 0])) / logbase else: diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 481072ac5c2b..97a7c6f6c6be 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -2775,13 +2775,12 @@ def test_hist_stacked_normed(): ax = fig.add_subplot(111) ax.hist((d1, d2), stacked=True, normed=True) -@image_comparison(baseline_images=['hist_stacked_normed']) + def test_hist_stacked_density(): # make some data d1 = np.linspace(1, 3, 20) d2 = np.linspace(0, 10, 50) - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.hist((d1, d2), stacked=True, density=True) From 55728ad04b30ae613ab6ccc554a96b3c5b6f8034 Mon Sep 17 00:00:00 2001 From: David Stansby Date: Sat, 5 Aug 2017 12:31:00 +0100 Subject: [PATCH 3/4] Clean hist docstring Remove changes to pyplot.py Remove accidental normalize imput method PEP8 new tests Only check for double kwargs once Remove duplicate test and parametrize test Small docstring fix --- lib/matplotlib/axes/_axes.py | 129 ++++++++++-------------------- lib/matplotlib/pyplot.py | 19 +++-- lib/matplotlib/tests/test_axes.py | 24 ++---- 3 files changed, 58 insertions(+), 114 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index fc8117fd5a9a..c2213a56ef9d 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -5878,11 +5878,11 @@ def hist(self, x, bins=None, range=None, density=None, weights=None, arrays which are not required to be of the same length bins : integer or array_like or 'auto', optional - If an integer is given, `bins + 1` bin edges are returned, + If an integer is given, ``bins + 1`` bin edges are returned, consistently with :func:`numpy.histogram` for numpy version >= 1.3. - Unequally spaced bins are supported if `bins` is a sequence. + Unequally spaced bins are supported if *bins* is a sequence. If Numpy 1.11 is installed, may also be ``'auto'``. @@ -5890,53 +5890,48 @@ def hist(self, x, bins=None, range=None, density=None, weights=None, range : tuple or None, optional 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. + 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 + If *bins* is a sequence or *range* is specified, autoscaling is based on the specified bin range instead of the range of x. Default is ``None`` - normed, density : boolean, optional - Either the 'normed' or the 'density' arg can be set to - accomplish this behavior: - - If `True`, the first element of the return tuple will + density : boolean, optional + If ``True``, the first element of the return tuple will be the counts normalized to form a probability density, i.e., the area (or integral) under the histogram will sum to 1. This is achieved dividing the count by the number of observations - times the bin width and *not* dividing by the total number - of observations. If `stacked` is also `True`, the sum of the + times the bin width and not dividing by the total number + of observations. If *stacked* is also ``True``, the sum of the histograms is normalized to 1. - Default is ``None`` for both 'normed' and 'density.' If either is - set, then that value will be used. If neither are set, then the args - will be treated as 'False.' + Default is ``None`` for both *normed* and *density*. If either is + set, then that value will be used. If neither are set, then the + args will be treated as ``False``. - If both are set to different things, the hist function raises an - error. + If both *density* and *normed* are set an error is raised. weights : (n, ) array_like or None, optional - An array of weights, of the same shape as `x`. Each value in `x` + 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` or 'density' is True, + (instead of 1). If *normed* or *density* is ``True``, the weights are normalized, so that the integral of the density over the range remains 1. Default is ``None`` cumulative : boolean, optional - If `True`, then a histogram is computed where each bin gives the + 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` or 'density' - 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` and/or 'density' is also `True`, then the histogram is - normalized such that the first bin - equals 1. + gives the total number of datapoints. If *normed* or *density* + 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* and/or *density* is also ``True``, then + the histogram is normalized such that the first bin equals 1. Default is ``False`` @@ -5982,22 +5977,23 @@ def hist(self, x, bins=None, range=None, density=None, weights=None, rwidth : scalar or None, optional The relative width of the bars as a fraction of the bin width. If - `None`, automatically compute the width. + ``None``, automatically compute the width. - Ignored if `histtype` is 'step' or 'stepfilled'. + Ignored if *histtype* is 'step' or 'stepfilled'. Default is ``None`` log : boolean, optional - 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. + 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. Default is ``False`` color : color or array_like of colors or None, optional Color spec or sequence of color specs, one per dataset. Default - (`None`) uses the standard line color sequence. + (``None``) uses the standard line color sequence. Default is ``None`` @@ -6009,8 +6005,8 @@ def hist(self, x, bins=None, range=None, density=None, weights=None, default is ``None`` stacked : boolean, optional - If `True`, multiple data are stacked on top of each other If - `False` multiple data are aranged side by side if histtype is + If ``True``, multiple data are stacked on top of each other If + ``False`` multiple data are aranged side by side if histtype is 'bar' or on top of each other if histtype is 'step' Default is ``False`` @@ -6018,10 +6014,10 @@ def hist(self, x, bins=None, range=None, density=None, weights=None, Returns ------- n : array or list of arrays - The values of the histogram bins. See **normed or density** - and **weights** for a description of the possible semantics. - If input **x** is an array, then this is an array of length - **nbins**. If input is a sequence arrays + The values of the histogram bins. See *normed* or *density* + and *weights* for a description of the possible semantics. + If input *x* is an array, then this is an array of length + *nbins*. If input is a sequence arrays ``[data1, data2,..]``, then this is a list of arrays with the values of the histograms for each of the arrays in the same order. @@ -6046,8 +6042,8 @@ def hist(self, x, bins=None, range=None, density=None, weights=None, Notes ----- 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 + incorrect with ``normed=True`` if bin sizes were unequal. MPL + inherited that error. It is now corrected within MPL when using earlier numpy versions. """ @@ -6055,50 +6051,6 @@ def hist(self, x, bins=None, range=None, density=None, weights=None, bin_range = range del range - # Sets the density variable, if necessary, to its predecessor, 'normed.' - if density is not None and normed is not None: - raise ValueError('The density and normed arguments represent the ' - 'same concept. Please set only one of them.') - elif normed is not None and density is None: - density = normed - elif normed is None and density is None: - density = False - - def _normalize_input(inp, ename='input'): - """Normalize 1 or 2d input into list of np.ndarray or - a single 2D np.ndarray. - - Parameters - ---------- - inp : iterable - ename : str, optional - Name to use in ValueError if `inp` can not be normalized - - """ - if (isinstance(x, np.ndarray) or - not iterable(cbook.safe_first_element(inp))): - # TODO: support masked arrays; - inp = np.asarray(inp) - if inp.ndim == 2: - # 2-D input with columns as datasets; switch to rows - inp = inp.T - elif inp.ndim == 1: - # new view, single row - inp = inp.reshape(1, inp.shape[0]) - else: - raise ValueError( - "{ename} must be 1D or 2D".format(ename=ename)) - if inp.shape[1] < inp.shape[0]: - warnings.warn( - '2D hist input should be nsamples x nvariables;\n ' - 'this looks transposed ' - '(shape is %d x %d)' % inp.shape[::-1]) - else: - # multiple hist with data of different length - inp = [np.asarray(xi) for xi in inp] - - return inp - if not self._hold: self.cla() @@ -6124,9 +6076,10 @@ def _normalize_input(inp, ename='input'): stacked = True if density is not None and normed is not None: - raise ValueError("kwargs 'density' and 'normed' cannot be used" - "simultaneously. Please only use 'density', since " - "'normed' will be deprecated. ") + raise ValueError("kwargs 'density' and 'normed' cannot be used " + "simultaneously. " + "Please only use 'density', since 'normed'" + "will be deprecated.") # process the unit information self._process_unit_info(xdata=x, kwargs=kwargs) diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index 97424a7b1a22..1b694498e62d 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -2992,10 +2992,10 @@ def hexbin(x, y, C=None, gridsize=100, bins=None, xscale='linear', # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost @_autogen_docstring(Axes.hist) -def hist(x, bins=None, range=None, density=None, normed=None, weights=None, - cumulative=False, bottom=None, histtype='bar', align='mid', - orientation='vertical', rwidth=None, log=False, color=None, label=None, - stacked=False, hold=None, data=None, **kwargs): +def hist(x, bins=None, range=None, normed=False, weights=None, cumulative=False, + bottom=None, histtype='bar', align='mid', orientation='vertical', + rwidth=None, log=False, color=None, label=None, stacked=False, + hold=None, data=None, **kwargs): ax = gca() # Deprecated: allow callers to override the hold state # by passing hold=True|False @@ -3007,12 +3007,11 @@ def hist(x, bins=None, range=None, density=None, normed=None, weights=None, warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", mplDeprecation) try: - ret = ax.hist(x, bins=bins, range=range, density=density, - normed=normed, weights=weights, cumulative=cumulative, - bottom=bottom, histtype=histtype, align=align, - orientation=orientation, rwidth=rwidth, log=log, - color=color, label=label, stacked=stacked, data=data, - **kwargs) + ret = ax.hist(x, bins=bins, range=range, normed=normed, + weights=weights, cumulative=cumulative, bottom=bottom, + histtype=histtype, align=align, orientation=orientation, + rwidth=rwidth, log=log, color=color, label=label, + stacked=stacked, data=data, **kwargs) finally: ax._hold = washold diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 97a7c6f6c6be..55dd74a0d924 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -2776,6 +2776,7 @@ def test_hist_stacked_normed(): ax.hist((d1, d2), stacked=True, normed=True) +@image_comparison(baseline_images=['hist_stacked_normed'], extensions=['png']) def test_hist_stacked_density(): # make some data d1 = np.linspace(1, 3, 20) @@ -2784,25 +2785,16 @@ def test_hist_stacked_density(): ax.hist((d1, d2), stacked=True, density=True) -def test_hist_normed_density(): - #Normed and density should not be used simultaneously +@pytest.mark.parametrize('normed', [False, True]) +@pytest.mark.parametrize('density', [False, True]) +def test_hist_normed_density(normed, density): + # Normed and density should not be used simultaneously d1 = np.linspace(1, 3, 20) d2 = np.linspace(0, 10, 50) - fig = plt.figure() - ax = fig.add_subplot(111) - #test that kwargs normed and density cannot be set both. - with pytest.raises(Exception): - ax.hist((d1, d2), stacked=True, normed=True, density=True) - - with pytest.raises(Exception): - ax.hist((d1, d2), stacked=True, normed=False, density=True) - - with pytest.raises(Exception): - ax.hist((d1, d2), stacked=True, normed=False, density=False) - + fig, ax = plt.subplots() + # test that kwargs normed and density cannot be set both. with pytest.raises(Exception): - ax.hist((d1, d2), stacked=True, normed=True, density=False) - + ax.hist((d1, d2), stacked=True, normed=normed, density=density) @image_comparison(baseline_images=['hist_step_bottom'], extensions=['png'], From 9535c3b506899857f3651d944fb03cf6d48b357a Mon Sep 17 00:00:00 2001 From: David Stansby Date: Sun, 6 Aug 2017 11:04:42 +0100 Subject: [PATCH 4/4] Small docstring fix --- lib/matplotlib/axes/_axes.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index c2213a56ef9d..912cc5e2b84f 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -5903,10 +5903,10 @@ def hist(self, x, bins=None, range=None, density=None, weights=None, If ``True``, the first element of the return tuple will be the counts normalized to form a probability density, i.e., the area (or integral) under the histogram will sum to 1. - This is achieved dividing the count by the number of observations - times the bin width and not dividing by the total number - of observations. If *stacked* is also ``True``, the sum of the - histograms is normalized to 1. + This is achieved by dividing the count by the number of + observations times the bin width and not dividing by the total + number of observations. If *stacked* is also ``True``, the sum of + the histograms is normalized to 1. Default is ``None`` for both *normed* and *density*. If either is set, then that value will be used. If neither are set, then the