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

Skip to content

Commit bf2053f

Browse files
moboehledstansby
authored andcommitted
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.
1 parent 66270ba commit bf2053f

File tree

3 files changed

+67
-29
lines changed

3 files changed

+67
-29
lines changed

lib/matplotlib/axes/_axes.py

Lines changed: 27 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,6 @@ def _plot_args_replacer(args, data):
9191
# The axes module contains all the wrappers to plotting functions.
9292
# All the other methods should go in the _AxesBase class.
9393

94-
9594
class Axes(_AxesBase):
9695
"""
9796
The :class:`Axes` contains most of the figure elements:
@@ -5852,9 +5851,9 @@ def table(self, **kwargs):
58525851
#### Data analysis
58535852

58545853
@_preprocess_data(replace_names=["x", 'weights'], label_namer="x")
5855-
def hist(self, x, bins=None, range=None, normed=False, weights=None,
5856-
cumulative=False, bottom=None, histtype='bar', align='mid',
5857-
orientation='vertical', rwidth=None, log=False,
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,
58585857
color=None, label=None, stacked=False,
58595858
**kwargs):
58605859
"""
@@ -5900,7 +5899,7 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None,
59005899
59015900
Default is ``None``
59025901
5903-
normed : boolean, optional
5902+
density : boolean, optional
59045903
If `True`, the first element of the return tuple will
59055904
be the counts normalized to form a probability density, i.e.,
59065905
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,
59095908
of observations. If `stacked` is also `True`, the sum of the
59105909
histograms is normalized to 1.
59115910
5912-
Default is ``False``
5911+
Default is ``None``, behaves as ``False``.
5912+
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.
59135916
59145917
weights : (n, ) array_like or None, optional
59155918
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,
60696072
if histtype == 'barstacked' and not stacked:
60706073
stacked = True
60716074

6075+
if density is not None and normed is not None:
6076+
raise ValueError("kwargs 'density' and 'normed' cannot be used"
6077+
"simultaneously. Please only use 'density', since "
6078+
"'normed' will be deprecated. ")
6079+
60726080
# process the unit information
60736081
self._process_unit_info(xdata=x, kwargs=kwargs)
60746082
x = self.convert_xunits(x)
@@ -6120,11 +6128,11 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None,
61206128
xmin = min(xmin, xi.min())
61216129
xmax = max(xmax, xi.max())
61226130
bin_range = (xmin, xmax)
6123-
6124-
# hist_kwargs = dict(range=range, normed=bool(normed))
6125-
# We will handle the normed kwarg within mpl until we
6126-
# get to the point of requiring numpy >= 1.5.
6127-
hist_kwargs = dict(range=bin_range)
6131+
density = bool(density) or bool(normed)
6132+
if density and not stacked:
6133+
hist_kwargs = dict(range=bin_range, density=density)
6134+
else:
6135+
hist_kwargs = dict(range=bin_range)
61286136

61296137
n = []
61306138
mlast = None
@@ -6135,17 +6143,15 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None,
61356143
m = m.astype(float) # causes problems later if it's an int
61366144
if mlast is None:
61376145
mlast = np.zeros(len(bins)-1, m.dtype)
6138-
if normed and not stacked:
6139-
db = np.diff(bins)
6140-
m = (m.astype(float) / db) / m.sum()
6146+
61416147
if stacked:
61426148
if mlast is None:
61436149
mlast = np.zeros(len(bins)-1, m.dtype)
61446150
m += mlast
61456151
mlast[:] = m
61466152
n.append(m)
61476153

6148-
if stacked and normed:
6154+
if stacked and density:
61496155
db = np.diff(bins)
61506156
for m in n:
61516157
m[:] = (m.astype(float) / db) / n[-1].sum()
@@ -6154,7 +6160,7 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None,
61546160
if cbook.is_numlike(cumulative) and cumulative < 0:
61556161
slc = slice(None, None, -1)
61566162

6157-
if normed:
6163+
if density:
61586164
n = [(m * np.diff(bins))[slc].cumsum()[slc] for m in n]
61596165
else:
61606166
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,
62416247
# Setting a minimum of 0 results in problems for log plots
62426248
if np.min(bottom) > 0:
62436249
minimum = np.min(bottom)
6244-
elif normed or weights is not None:
6245-
# For normed data, set to minimum data value / logbase
6246-
# (gives 1 full tick-label unit for the lowest filled bin)
6250+
elif density or weights is not None:
6251+
# For normed (density = True) data full tick-label unit
6252+
# for the lowest filled bin)
62476253
ndata = np.array(n)
62486254
minimum = (np.min(ndata[ndata > 0])) / logbase
62496255
else:
6250-
# For non-normed data, set the min to 1 / log base,
6256+
# For non-normed (density = False) data,
6257+
# set the min to 1 / log base,
62516258
# again so that there is 1 full tick-label unit
62526259
# for the lowest bin
62536260
minimum = 1.0 / logbase

lib/matplotlib/pyplot.py

Lines changed: 10 additions & 9 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, 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):
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):
29992999
ax = gca()
30003000
# Deprecated: allow callers to override the hold state
30013001
# by passing hold=True|False
@@ -3007,11 +3007,12 @@ def hist(x, bins=None, range=None, normed=False, weights=None, cumulative=False,
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, 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)
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)
30153016
finally:
30163017
ax._hold = washold
30173018

lib/matplotlib/tests/test_axes.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2775,6 +2775,36 @@ 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'])
2779+
def test_hist_stacked_density():
2780+
# make some data
2781+
d1 = np.linspace(1, 3, 20)
2782+
d2 = np.linspace(0, 10, 50)
2783+
fig = plt.figure()
2784+
ax = fig.add_subplot(111)
2785+
ax.hist((d1, d2), stacked=True, density=True)
2786+
2787+
2788+
def test_hist_normed_density():
2789+
#Normed and density should not be used simultaneously
2790+
d1 = np.linspace(1, 3, 20)
2791+
d2 = np.linspace(0, 10, 50)
2792+
fig = plt.figure()
2793+
ax = fig.add_subplot(111)
2794+
#test that kwargs normed and density cannot be set both.
2795+
with pytest.raises(Exception):
2796+
ax.hist((d1, d2), stacked=True, normed=True, density=True)
2797+
2798+
with pytest.raises(Exception):
2799+
ax.hist((d1, d2), stacked=True, normed=False, density=True)
2800+
2801+
with pytest.raises(Exception):
2802+
ax.hist((d1, d2), stacked=True, normed=False, density=False)
2803+
2804+
with pytest.raises(Exception):
2805+
ax.hist((d1, d2), stacked=True, normed=True, density=False)
2806+
2807+
27782808

27792809
@image_comparison(baseline_images=['hist_step_bottom'], extensions=['png'],
27802810
remove_text=True)

0 commit comments

Comments
 (0)