Python Matplotlib rectangular binning

I realize that there is a patch submitted to matplotlib, but I adopted the code from the other example to acommodate a few needs that I had.

now the histogram is plotted from the lower left corner, as in conventional math (not computing)

also, values outside the binning range are ignored and I use a 2d numpy array for the twodimensional array

I changed the data input from pairs to two 1D arrays since this is how data is supplied to scatter(x,y) and alike functions

def histBin(x,y,x_range=(0.0,1.0),y_range=(0.0,1.0),xbins=10,ybins=None):
    """ Helper function to do 2D histogram binning
        x, y are  lists / 2D arrays 
        x_range and yrange define the range of the plot similar to the hist(range=...) 
        xbins,ybins are the number of bins within this range.
    """

    pairsData = zip(x,y)

    if (ybins == None):
        ybins = xbins
    xdata, ydata = zip(*pairsData)
    xmin,xmax = x_range
    xmin = float(xmin)
    xmax = float(xmax)

    xwidth = xmax-xmin
    ymin,ymax = y_range    
    ymin = float(ymin)
    ymax = float(ymax)
    ywidth = ymax-ymin

    def xbin(xval):
        return floor(xbins*(xval-xmin)/xwidth) if xmin <= xval  < xmax else xbins-1 if xval ==xmax else None


    def ybin(yval):
        return floor(ybins*(yval-ymin)/ywidth) if ymin <= yval  < ymax else ybins-1 if yval ==ymax else None

    hist = numpy.zeros((xbins,ybins)) 
    for x,y in pairsData:
        i_x,i_y = xbin(x),ybin(ymax-y)
        if i_x is not None and i_y is not None:
            hist[i_y,i_x] += 1 

    extent = (xmin,xmax,ymin,ymax)

    return hist,extent

Numpy has a function called histogram2d, whose docstring also shows you how to visualize it using Matplotlib. Add interpolation=nearest to the imshow call to disable the interpolation.