39
39
try :
40
40
from numpy .lib .histograms import histogram_bin_edges
41
41
except ImportError :
42
+ # this function is new in np 1.15
42
43
def histogram_bin_edges (arr , bins , range = None , weights = None ):
44
+ # this in True for 1D arrays, and False for None and str
45
+ if np .ndim (bins ) == 1 :
46
+ return bins
47
+
43
48
if isinstance (bins , str ):
44
49
# rather than backporting the internals, just do the full
45
50
# computation. If this is too slow for users, they can
@@ -6630,9 +6635,6 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
6630
6635
if bin_range is not None :
6631
6636
bin_range = self .convert_xunits (bin_range )
6632
6637
6633
- # this in True for 1D arrays, and False for None and str
6634
- bins_array_given = np .ndim (bins ) == 1
6635
-
6636
6638
# We need to do to 'weights' what was done to 'x'
6637
6639
if weights is not None :
6638
6640
w = cbook ._reshape_2D (weights , 'weights' )
@@ -6659,14 +6661,32 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
6659
6661
6660
6662
hist_kwargs = dict ()
6661
6663
6664
+ # if the bin_range is not given, compute without nan numpy
6665
+ # does not do this for us when guessing the range (but will
6666
+ # happily ignore nans when computing the histogram).
6667
+ if bin_range is None :
6668
+ xmin = np .inf
6669
+ xmax = - np .inf
6670
+ for xi in x :
6671
+ if len (xi ):
6672
+ # python's min/max ignore nan,
6673
+ # np.minnan returns nan for all nan input
6674
+ xmin = min (xmin , np .nanmin (xi ))
6675
+ xmax = max (xmax , np .nanmax (xi ))
6676
+ # make sure we have seen at least one non-nan and finite
6677
+ # value before we reset the bin range
6678
+ if not np .isnan ([xmin , xmax ]).any () and not (xmin > xmax ):
6679
+ bin_range = (xmin , xmax )
6680
+
6662
6681
# If bins are not specified either explicitly or via range,
6663
6682
# we need to figure out the range required for all datasets,
6664
6683
# and supply that to np.histogram.
6665
- if not bins_array_given and not input_empty and len (x ) > 1 :
6684
+ if not input_empty and len (x ) > 1 :
6666
6685
if weights is not None :
6667
6686
_w = np .concatenate (w )
6668
6687
else :
6669
6688
_w = None
6689
+
6670
6690
bins = histogram_bin_edges (np .concatenate (x ),
6671
6691
bins , bin_range , _w )
6672
6692
else :
0 commit comments