Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 138239d

Browse files
chelseatroydstansby
authored andcommitted
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
1 parent bf2053f commit 138239d

File tree

2 files changed

+81
-28
lines changed

2 files changed

+81
-28
lines changed

lib/matplotlib/axes/_axes.py

Lines changed: 79 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5851,10 +5851,10 @@ def table(self, **kwargs):
58515851
#### Data analysis
58525852

58535853
@_preprocess_data(replace_names=["x", 'weights'], label_namer="x")
5854-
def hist(self, x, bins=None, range=None, density=None, normed=None,
5855-
weights=None, cumulative=False, bottom=None, histtype='bar',
5856-
align='mid', orientation='vertical', rwidth=None, log=False,
5857-
color=None, label=None, stacked=False,
5854+
def hist(self, x, bins=None, range=None, density=None, weights=None,
5855+
cumulative=False, bottom=None, histtype='bar', align='mid',
5856+
orientation='vertical', rwidth=None, log=False,
5857+
color=None, label=None, stacked=False, normed=None,
58585858
**kwargs):
58595859
"""
58605860
Plot a histogram.
@@ -5899,7 +5899,10 @@ def hist(self, x, bins=None, range=None, density=None, normed=None,
58995899
59005900
Default is ``None``
59015901
5902-
density : boolean, optional
5902+
normed, density : boolean, optional
5903+
Either the 'normed' or the 'density' arg can be set to
5904+
accomplish this behavior:
5905+
59035906
If `True`, the first element of the return tuple will
59045907
be the counts normalized to form a probability density, i.e.,
59055908
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,
59085911
of observations. If `stacked` is also `True`, the sum of the
59095912
histograms is normalized to 1.
59105913
5911-
Default is ``None``, behaves as ``False``.
5914+
Default is ``None`` for both 'normed' and 'density.' If either is
5915+
set, then that value will be used. If neither are set, then the args
5916+
will be treated as 'False.'
59125917
5913-
normed : boolean, optional
5914-
Will be deprecated, same role as density. For consistency
5915-
with NumPy 2.0.0 keyword density has been introduced.
5918+
If both are set to different things, the hist function raises an
5919+
error.
59165920
59175921
weights : (n, ) array_like or None, optional
59185922
An array of weights, of the same shape as `x`. Each value in `x`
59195923
only contributes its associated weight towards the bin count
5920-
(instead of 1). If `normed` is True, the weights are normalized,
5921-
so that the integral of the density over the range remains 1.
5924+
(instead of 1). If `normed` or 'density' is True,
5925+
the weights are normalized, so that the integral of the density
5926+
over the range remains 1.
59225927
59235928
Default is ``None``
59245929
59255930
cumulative : boolean, optional
59265931
If `True`, then a histogram is computed where each bin gives the
59275932
counts in that bin plus all bins for smaller values. The last bin
5928-
gives the total number of datapoints. If `normed` is also `True`
5929-
then the histogram is normalized such that the last bin equals 1.
5930-
If `cumulative` evaluates to less than 0 (e.g., -1), the direction
5931-
of accumulation is reversed. In this case, if `normed` is also
5932-
`True`, then the histogram is normalized such that the first bin
5933+
gives the total number of datapoints. If `normed` or 'density'
5934+
is also `True` then the histogram is normalized such that the last
5935+
bin equals 1. If `cumulative` evaluates to less than 0 (e.g., -1),
5936+
the direction of accumulation is reversed. In this case, if
5937+
`normed` and/or 'density' is also `True`, then the histogram is
5938+
normalized such that the first bin
59335939
equals 1.
59345940
59355941
Default is ``False``
@@ -6012,12 +6018,13 @@ def hist(self, x, bins=None, range=None, density=None, normed=None,
60126018
Returns
60136019
-------
60146020
n : array or list of arrays
6015-
The values of the histogram bins. See **normed** and **weights**
6016-
for a description of the possible semantics. If input **x** is an
6017-
array, then this is an array of length **nbins**. If input is a
6018-
sequence arrays ``[data1, data2,..]``, then this is a list of
6019-
arrays with the values of the histograms for each of the arrays
6020-
in the same order.
6021+
The values of the histogram bins. See **normed or density**
6022+
and **weights** for a description of the possible semantics.
6023+
If input **x** is an array, then this is an array of length
6024+
**nbins**. If input is a sequence arrays
6025+
``[data1, data2,..]``, then this is a list of arrays with
6026+
the values of the histograms for each of the arrays in the
6027+
same order.
60216028
60226029
bins : array
60236030
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,
60486055
bin_range = range
60496056
del range
60506057

6058+
# Sets the density variable, if necessary, to its predecessor, 'normed.'
6059+
if density is not None and normed is not None:
6060+
raise ValueError('The density and normed arguments represent the '
6061+
'same concept. Please set only one of them.')
6062+
elif normed is not None and density is None:
6063+
density = normed
6064+
elif normed is None and density is None:
6065+
density = False
6066+
6067+
def _normalize_input(inp, ename='input'):
6068+
"""Normalize 1 or 2d input into list of np.ndarray or
6069+
a single 2D np.ndarray.
6070+
6071+
Parameters
6072+
----------
6073+
inp : iterable
6074+
ename : str, optional
6075+
Name to use in ValueError if `inp` can not be normalized
6076+
6077+
"""
6078+
if (isinstance(x, np.ndarray) or
6079+
not iterable(cbook.safe_first_element(inp))):
6080+
# TODO: support masked arrays;
6081+
inp = np.asarray(inp)
6082+
if inp.ndim == 2:
6083+
# 2-D input with columns as datasets; switch to rows
6084+
inp = inp.T
6085+
elif inp.ndim == 1:
6086+
# new view, single row
6087+
inp = inp.reshape(1, inp.shape[0])
6088+
else:
6089+
raise ValueError(
6090+
"{ename} must be 1D or 2D".format(ename=ename))
6091+
if inp.shape[1] < inp.shape[0]:
6092+
warnings.warn(
6093+
'2D hist input should be nsamples x nvariables;\n '
6094+
'this looks transposed '
6095+
'(shape is %d x %d)' % inp.shape[::-1])
6096+
else:
6097+
# multiple hist with data of different length
6098+
inp = [np.asarray(xi) for xi in inp]
6099+
6100+
return inp
6101+
60516102
if not self._hold:
60526103
self.cla()
60536104

@@ -6143,7 +6194,9 @@ def hist(self, x, bins=None, range=None, density=None, normed=None,
61436194
m = m.astype(float) # causes problems later if it's an int
61446195
if mlast is None:
61456196
mlast = np.zeros(len(bins)-1, m.dtype)
6146-
6197+
if density and not stacked:
6198+
db = np.diff(bins)
6199+
m = (m.astype(float) / db) / m.sum()
61476200
if stacked:
61486201
if mlast is None:
61496202
mlast = np.zeros(len(bins)-1, m.dtype)
@@ -6248,8 +6301,9 @@ def hist(self, x, bins=None, range=None, density=None, normed=None,
62486301
if np.min(bottom) > 0:
62496302
minimum = np.min(bottom)
62506303
elif density or weights is not None:
6251-
# For normed (density = True) data full tick-label unit
6252-
# for the lowest filled bin)
6304+
# For data that is normed to form a probability density,
6305+
# set to minimum data value / logbase
6306+
# (gives 1 full tick-label unit for the lowest filled bin)
62536307
ndata = np.array(n)
62546308
minimum = (np.min(ndata[ndata > 0])) / logbase
62556309
else:

lib/matplotlib/tests/test_axes.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2775,13 +2775,12 @@ def test_hist_stacked_normed():
27752775
ax = fig.add_subplot(111)
27762776
ax.hist((d1, d2), stacked=True, normed=True)
27772777

2778-
@image_comparison(baseline_images=['hist_stacked_normed'])
2778+
27792779
def test_hist_stacked_density():
27802780
# make some data
27812781
d1 = np.linspace(1, 3, 20)
27822782
d2 = np.linspace(0, 10, 50)
2783-
fig = plt.figure()
2784-
ax = fig.add_subplot(111)
2783+
fig, ax = plt.subplots()
27852784
ax.hist((d1, d2), stacked=True, density=True)
27862785

27872786

0 commit comments

Comments
 (0)