36
36
from matplotlib .axes ._base import _AxesBase , _process_plot_format
37
37
from matplotlib .axes ._secondary_axes import SecondaryAxis
38
38
39
+ try :
40
+ from numpy .lib .histograms import histogram_bin_edges
41
+ except ImportError :
42
+ def histogram_bin_edges (arr , bins , range = None , weights = None ):
43
+ if isinstance (bins , str ):
44
+ # rather than backporting the internals, just do the full
45
+ # computation. If this is too slow for users, they can
46
+ # update numpy, or pick a manual number of bins
47
+ return np .histogram (arr , bins , range , weights )[1 ]
48
+ else :
49
+ if bins is None :
50
+ # hard-code numpy's default
51
+ bins = 10
52
+ if range is None :
53
+ range = np .min (arr ), np .max (arr )
54
+
55
+ return np .linspace (* range , bins + 1 )
56
+
57
+
39
58
_log = logging .getLogger (__name__ )
40
59
41
60
@@ -6611,10 +6630,8 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
6611
6630
if bin_range is not None :
6612
6631
bin_range = self .convert_xunits (bin_range )
6613
6632
6614
- # Check whether bins or range are given explicitly.
6615
- binsgiven = ((np .iterable (bins ) and
6616
- not isinstance (bins , str )) or
6617
- bin_range is not None )
6633
+ # this in True for 1D arrays, and False for None and str
6634
+ bins_array_given = np .ndim (bins ) == 1
6618
6635
6619
6636
# We need to do to 'weights' what was done to 'x'
6620
6637
if weights is not None :
@@ -6640,22 +6657,24 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
6640
6657
"sets and %d colors were provided" % (nx , len (color )))
6641
6658
raise ValueError (error_message )
6642
6659
6660
+ hist_kwargs = dict ()
6661
+
6643
6662
# If bins are not specified either explicitly or via range,
6644
6663
# we need to figure out the range required for all datasets,
6645
6664
# and supply that to np.histogram.
6646
- if not binsgiven and not input_empty :
6647
- xmin = np .inf
6648
- xmax = - np .inf
6649
- for xi in x :
6650
- if len (xi ) > 0 :
6651
- xmin = min (xmin , np .nanmin (xi ))
6652
- xmax = max (xmax , np .nanmax (xi ))
6653
- bin_range = (xmin , xmax )
6665
+ if not bins_array_given and not input_empty and len (x ) > 1 :
6666
+ if weights is not None :
6667
+ _w = np .concatenate (w )
6668
+ else :
6669
+ _w = None
6670
+ bins = histogram_bin_edges (np .concatenate (x ),
6671
+ bins , bin_range , _w )
6672
+ else :
6673
+ hist_kwargs ['range' ] = bin_range
6674
+
6654
6675
density = bool (density ) or bool (normed )
6655
6676
if density and not stacked :
6656
- hist_kwargs = dict (range = bin_range , density = density )
6657
- else :
6658
- hist_kwargs = dict (range = bin_range )
6677
+ hist_kwargs = dict (density = density )
6659
6678
6660
6679
# List to store all the top coordinates of the histograms
6661
6680
tops = []
0 commit comments