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

Skip to content

Commit 728cca3

Browse files
committed
Refactor hist for less numerical errors
1 parent 8b1881f commit 728cca3

File tree

1 file changed

+15
-9
lines changed

1 file changed

+15
-9
lines changed

lib/matplotlib/axes/_axes.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6633,7 +6633,11 @@ def hist(self, x, bins=None, range=None, density=False, weights=None,
66336633

66346634
if histtype.startswith('bar'):
66356635

6636-
totwidth = np.diff(bins)
6636+
def _get_boffset(boffset):
6637+
if np.any(boffset):
6638+
return np.diff(boffset)
6639+
else:
6640+
return 0.0
66376641

66386642
if rwidth is not None:
66396643
dr = np.clip(rwidth, 0, 1)
@@ -6644,17 +6648,17 @@ def hist(self, x, bins=None, range=None, density=False, weights=None,
66446648
dr = 1.0
66456649

66466650
if histtype == 'bar' and not stacked:
6647-
width = dr * totwidth / nx
6648-
dw = width
6649-
boffset = -0.5 * dr * totwidth * (1 - 1 / nx)
6651+
starts = dr * bins / nx
6652+
dw = starts
6653+
boffset = -0.5 * dr * bins * (1 - 1 / nx)
66506654
elif histtype == 'barstacked' or stacked:
6651-
width = dr * totwidth
6655+
starts = dr * bins
66526656
boffset, dw = 0.0, 0.0
66536657

66546658
if align == 'mid':
6655-
boffset += 0.5 * totwidth
6659+
boffset += 0.5 * bins
66566660
elif align == 'right':
6657-
boffset += totwidth
6661+
boffset += bins
66586662

66596663
if orientation == 'horizontal':
66606664
_barfunc = self.barh
@@ -6663,15 +6667,17 @@ def hist(self, x, bins=None, range=None, density=False, weights=None,
66636667
_barfunc = self.bar
66646668
bottom_kwarg = 'bottom'
66656669

6670+
width = np.diff(starts)
6671+
66666672
for m, c in zip(tops, color):
66676673
if bottom is None:
66686674
bottom = np.zeros(len(m))
66696675
if stacked:
66706676
height = m - bottom
66716677
else:
66726678
height = m
6673-
bars = _barfunc(bins[:-1]+boffset, height, width,
6674-
align='center', log=log,
6679+
bars = _barfunc(bins[:-1] + _get_boffset(boffset), height,
6680+
width, align='center', log=log,
66756681
color=c, **{bottom_kwarg: bottom})
66766682
patches.append(bars)
66776683
if stacked:

0 commit comments

Comments
 (0)