Weighted Histograms

I have a request that weighted histograms be added to the "hist"
function. Here's the code to do it (lightly modified from the version
in matplotlib.mlab, with changes commented:

    if not iterable(bins):
        ymin, ymax = min(y), max(y)
        if ymin==ymax:
            ymin -= 0.5
            ymax += 0.5
        bins = linspace(ymin, ymax, bins)

    if w is None: # unweighted if weights not
        w=ones(length(y)) # specified
        
    idx = argsort(y) # find indicies that will sort the data
    sy = take(y,idx) # sort the data
    sw = take(w,idx) # sort the weights
    n = searchsorted(sy, bins)
    n = concatenate([n,[len(y)]])
    hist = zeros(len(n)-1) # make the histogram
    
    for i in range(len(hist)): # sum up the weights that fall into
        l=n[i] # the range b/t each bin
        h=n[i+1] # ...
        hist[i] = sum(sw[l:h]) # ...

    if normed:
       db = bins[1]-bins[0]
       return 1/(len(y)*db)*n, bins
    else:
       return n, bins

Also, I'd be very happy if the (in my opinion totally rediculous)
default of 10 bins were changed to something more reasonable, such as
50 bins. However, that's easy enough for me to change myself.

Thank you,
Greg