8000 FIX: restore (and test) handling of nan in hist data · matplotlib/matplotlib@388a209 · GitHub
[go: up one dir, main page]

Skip to content

Commit 388a209

Browse files
committed
FIX: restore (and test) handling of nan in hist data
1 parent 3b47bc1 commit 388a209

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

lib/matplotlib/axes/_axes.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6659,6 +6659,19 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
66596659

66606660
hist_kwargs = dict()
66616661

6662+
# if the bin_range is not given, compute without nan numpy
6663+
# does not do this for us when guessing the range (but will
6664+
# happily ignore nans when computing the histogram).
6665+
if bin_range is None:
6666+
xmin = np.inf
6667+
xmax = -np.inf
6668+
for xi in x:
6669+
if len(xi):
6670+
xmin = min(xmin, np.nanmin(xi))
6671+
xmax = max(xmax, np.nanmax(xi))
6672+
if xmax > xmin:
6673+
bin_range = (xmin, xmax)
6674+
66626675
# If bins are not specified either explicitly or via range,
66636676
# we need to figure out the range required for all datasets,
66646677
# and supply that to np.histogram.
@@ -6667,6 +6680,7 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
66676680
_w = np.concatenate(w)
66686681
else:
66696682
_w = None
6683+
66706684
bins = histogram_bin_edges(np.concatenate(x),
66716685
bins, bin_range, _w)
66726686
else:

lib/matplotlib/tests/test_axes.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6352,3 +6352,17 @@ def test_hist_auto_bins():
63526352
_, bins, _ = plt.hist([[1, 2, 3], [3, 4, 5, 6]], bins='auto')
63536353
assert bins[0] <= 1
63546354
assert bins[-1] >= 6
6355+
6356+
6357+
def test_hist_nan_data():
6358+
fig, (ax1, ax2) = plt.subplots(2)
6359+
6360+
data = [1, 2, 3]
6361+
nan_data = data + [np.nan]
6362+
6363+
bins, edges, _ = ax1.hist(data)
6364+
with np.errstate(invalid='ignore'):
6365+
nanbins, nanedges, _ = ax2.hist(nan_data)
6366+
6367+
assert np.allclose(bins, nanbins)
6368+
assert np.allclose(edges, nanedges)

0 commit comments

Comments
 (0)
0