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

Skip to content

Commit 55728ad

Browse files
committed
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
1 parent 138239d commit 55728ad

File tree

3 files changed

+58
-114
lines changed

3 files changed

+58
-114
lines changed

lib/matplotlib/axes/_axes.py

Lines changed: 41 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -5878,65 +5878,60 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
58785878
arrays which are not required to be of the same length
58795879
58805880
bins : integer or array_like or 'auto', optional
5881-
If an integer is given, `bins + 1` bin edges are returned,
5881+
If an integer is given, ``bins + 1`` bin edges are returned,
58825882
consistently with :func:`numpy.histogram` for numpy version >=
58835883
1.3.
58845884
5885-
Unequally spaced bins are supported if `bins` is a sequence.
5885+
Unequally spaced bins are supported if *bins* is a sequence.
58865886
58875887
If Numpy 1.11 is installed, may also be ``'auto'``.
58885888
58895889
Default is taken from the rcParam ``hist.bins``.
58905890
58915891
range : tuple or None, optional
58925892
The lower and upper range of the bins. Lower and upper outliers
5893-
are ignored. If not provided, `range` is (x.min(), x.max()). Range
5894-
has no effect if `bins` is a sequence.
5893+
are ignored. If not provided, *range* is ``(x.min(), x.max())``.
5894+
Range has no effect if *bins* is a sequence.
58955895
5896-
If `bins` is a sequence or `range` is specified, autoscaling
5896+
If *bins* is a sequence or *range* is specified, autoscaling
58975897
is based on the specified bin range instead of the
58985898
range of x.
58995899
59005900
Default is ``None``
59015901
5902-
normed, density : boolean, optional
5903-
Either the 'normed' or the 'density' arg can be set to
5904-
accomplish this behavior:
5905-
5906-
If `True`, the first element of the return tuple will
5902+
density : boolean, optional
5903+
If ``True``, the first element of the return tuple will
59075904
be the counts normalized to form a probability density, i.e.,
59085905
the area (or integral) under the histogram will sum to 1.
59095906
This is achieved dividing the count by the number of observations
5910-
times the bin width and *not* dividing by the total number
5911-
of observations. If `stacked` is also `True`, the sum of the
5907+
times the bin width and not dividing by the total number
5908+
of observations. If *stacked* is also ``True``, the sum of the
59125909
histograms is normalized to 1.
59135910
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.'
5911+
Default is ``None`` for both *normed* and *density*. If either is
5912+
set, then that value will be used. If neither are set, then the
5913+
args will be treated as ``False``.
59175914
5918-
If both are set to different things, the hist function raises an
5919-
error.
5915+
If both *density* and *normed* are set an error is raised.
59205916
59215917
weights : (n, ) array_like or None, optional
5922-
An array of weights, of the same shape as `x`. Each value in `x`
5918+
An array of weights, of the same shape as *x*. Each value in *x*
59235919
only contributes its associated weight towards the bin count
5924-
(instead of 1). If `normed` or 'density' is True,
5920+
(instead of 1). If *normed* or *density* is ``True``,
59255921
the weights are normalized, so that the integral of the density
59265922
over the range remains 1.
59275923
59285924
Default is ``None``
59295925
59305926
cumulative : boolean, optional
5931-
If `True`, then a histogram is computed where each bin gives the
5927+
If ``True``, then a histogram is computed where each bin gives the
59325928
counts in that bin plus all bins for smaller values. The last 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
5939-
equals 1.
5929+
gives the total number of datapoints. If *normed* or *density*
5930+
is also ``True`` then the histogram is normalized such that the
5931+
last bin equals 1. If *cumulative* evaluates to less than 0
5932+
(e.g., -1), the direction of accumulation is reversed.
5933+
In this case, if *normed* and/or *density* is also ``True``, then
5934+
the histogram is normalized such that the first bin equals 1.
59405935
59415936
Default is ``False``
59425937
@@ -5982,22 +5977,23 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
59825977
59835978
rwidth : scalar or None, optional
59845979
The relative width of the bars as a fraction of the bin width. If
5985-
`None`, automatically compute the width.
5980+
``None``, automatically compute the width.
59865981
5987-
Ignored if `histtype` is 'step' or 'stepfilled'.
5982+
Ignored if *histtype* is 'step' or 'stepfilled'.
59885983
59895984
Default is ``None``
59905985
59915986
log : boolean, optional
5992-
If `True`, the histogram axis will be set to a log scale. If `log`
5993-
is `True` and `x` is a 1D array, empty bins will be filtered out
5994-
and only the non-empty (`n`, `bins`, `patches`) will be returned.
5987+
If ``True``, the histogram axis will be set to a log scale. If
5988+
*log* is ``True`` and *x* is a 1D array, empty bins will be
5989+
filtered out and only the non-empty ``(n, bins, patches)``
5990+
will be returned.
59955991
59965992
Default is ``False``
59975993
59985994
color : color or array_like of colors or None, optional
59995995
Color spec or sequence of color specs, one per dataset. Default
6000-
(`None`) uses the standard line color sequence.
5996+
(``None``) uses the standard line color sequence.
60015997
60025998
Default is ``None``
60035999
@@ -6009,19 +6005,19 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
60096005
default is ``None``
60106006
60116007
stacked : boolean, optional
6012-
If `True`, multiple data are stacked on top of each other If
6013-
`False` multiple data are aranged side by side if histtype is
6008+
If ``True``, multiple data are stacked on top of each other If
6009+
``False`` multiple data are aranged side by side if histtype is
60146010
'bar' or on top of each other if histtype is 'step'
60156011
60166012
Default is ``False``
60176013
60186014
Returns
60196015
-------
60206016
n : array or list of arrays
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
6017+
The values of the histogram bins. See *normed* or *density*
6018+
and *weights* for a description of the possible semantics.
6019+
If input *x* is an array, then this is an array of length
6020+
*nbins*. If input is a sequence arrays
60256021
``[data1, data2,..]``, then this is a list of arrays with
60266022
the values of the histograms for each of the arrays in the
60276023
same order.
@@ -6046,59 +6042,15 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
60466042
Notes
60476043
-----
60486044
Until numpy release 1.5, the underlying numpy histogram function was
6049-
incorrect with `normed`=`True` if bin sizes were unequal. MPL
6050-
inherited that error. It is now corrected within MPL when using
6045+
incorrect with ``normed=True`` if bin sizes were unequal. MPL
6046+
inherited that error. It is now corrected within MPL when using
60516047
earlier numpy versions.
60526048
60536049
"""
60546050
# Avoid shadowing the builtin.
60556051
bin_range = range
60566052
del range
60576053

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-
61026054
if not self._hold:
61036055
self.cla()
61046056

@@ -6124,9 +6076,10 @@ def _normalize_input(inp, ename='input'):
61246076
stacked = True
61256077

61266078
if density is not None and normed is not None:
6127-
raise ValueError("kwargs 'density' and 'normed' cannot be used"
6128-
"simultaneously. Please only use 'density', since "
6129-
"'normed' will be deprecated. ")
6079+
raise ValueError("kwargs 'density' and 'normed' cannot be used "
6080+
"simultaneously. "
6081+
"Please only use 'density', since 'normed'"
6082+
"will be deprecated.")
61306083

61316084
# process the unit information
61326085
self._process_unit_info(xdata=x, kwargs=kwargs)

lib/matplotlib/pyplot.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2992,10 +2992,10 @@ def hexbin(x, y, C=None, gridsize=100, bins=None, xscale='linear',
29922992
# This function was autogenerated by boilerplate.py. Do not edit as
29932993
# changes will be lost
29942994
@_autogen_docstring(Axes.hist)
2995-
def hist(x, bins=None, range=None, density=None, normed=None, weights=None,
2996-
cumulative=False, bottom=None, histtype='bar', align='mid',
2997-
orientation='vertical', rwidth=None, log=False, color=None, label=None,
2998-
stacked=False, hold=None, data=None, **kwargs):
2995+
def hist(x, bins=None, range=None, normed=False, weights=None, cumulative=False,
2996+
bottom=None, histtype='bar', align='mid', orientation='vertical',
2997+
rwidth=None, log=False, color=None, label=None, stacked=False,
2998+
hold=None, data=None, **kwargs):
29992999
ax = gca()
30003000
# Deprecated: allow callers to override the hold state
30013001
# by passing hold=True|False
@@ -3007,12 +3007,11 @@ def hist(x, bins=None, range=None, density=None, normed=None, weights=None,
30073007
warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
30083008
mplDeprecation)
30093009
try:
3010-
ret = ax.hist(x, bins=bins, range=range, density=density,
3011-
normed=normed, weights=weights, cumulative=cumulative,
3012-
bottom=bottom, histtype=histtype, align=align,
3013-
orientation=orientation, rwidth=rwidth, log=log,
3014-
color=color, label=label, stacked=stacked, data=data,
3015-
**kwargs)
3010+
ret = ax.hist(x, bins=bins, range=range, normed=normed,
3011+
weights=weights, cumulative=cumulative, bottom=bottom,
3012+
histtype=histtype, align=align, orientation=orientation,
3013+
rwidth=rwidth, log=log, color=color, label=label,
3014+
stacked=stacked, data=data, **kwargs)
30163015
finally:
30173016
ax._hold = washold
30183017

lib/matplotlib/tests/test_axes.py

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2776,6 +2776,7 @@ def test_hist_stacked_normed():
27762776
ax.hist((d1, d2), stacked=True, normed=True)
27772777

27782778

2779+
@image_comparison(baseline_images=['hist_stacked_normed'], extensions=['png'])
27792780
def test_hist_stacked_density():
27802781
# make some data
27812782
d1 = np.linspace(1, 3, 20)
@@ -2784,25 +2785,16 @@ def test_hist_stacked_density():
27842785
ax.hist((d1, d2), stacked=True, density=True)
27852786

27862787

2787-
def test_hist_normed_density():
2788-
#Normed and density should not be used simultaneously
2788+
@pytest.mark.parametrize('normed', [False, True])
2789+
@pytest.mark.parametrize('density', [False, True])
2790+
def test_hist_normed_density(normed, density):
2791+
# Normed and density should not be used simultaneously
27892792
d1 = np.linspace(1, 3, 20)
27902793
d2 = np.linspace(0, 10, 50)
2791-
fig = plt.figure()
2792-
ax = fig.add_subplot(111)
2793-
#test that kwargs normed and density cannot be set both.
2794-
with pytest.raises(Exception):
2795-
ax.hist((d1, d2), stacked=True, normed=True, density=True)
2796-
2797-
with pytest.raises(Exception):
2798-
ax.hist((d1, d2), stacked=True, normed=False, density=True)
2799-
2800-
with pytest.raises(Exception):
2801-
ax.hist((d1, d2), stacked=True, normed=False, density=False)
2802-
2794+
fig, ax = plt.subplots()
2795+
# test that kwargs normed and density cannot be set both.
28032796
with pytest.raises(Exception):
2804-
ax.hist((d1, d2), stacked=True, normed=True, density=False)
2805-
2797+
ax.hist((d1, d2), stacked=True, normed=normed, density=density)
28062798

28072799

28082800
@image_comparison(baseline_images=['hist_step_bottom'], extensions=['png'],

0 commit comments

Comments
 (0)