Return the value of a 2D PDF given x and y in Python?
Question: I have some data that I plotted the PDF using matplotlib's hist2D function.
The result looks like this:

![enter image description here](http://i.stack.imgur.com/Yj83S.png)

The hist2d function returns a triple of arrays: H,xedges,yedges. H being the
2D histogram value. Now I'd like to turn this discrete H matrix and turn it
into a function, that returns the value of H for any given (x,y) input. In
other words I'd like to turn my 2D histogram into a 2D step function. Is there
a specific function that would be computationally cheap that I could use on
that purpose?

This looks like a pretty simple operation (usually done for image processing
but with pixel indices instead of real numbers) but I'm unable to find
anything about it, can you please help me?


Answer: You can construct an interpolator from the counts like this:

    
    
    from numpy import random, histogram2d, diff
    import matplotlib.pyplot as plt
    from scipy.interpolate import interp2d
    
    # Generate sample data
    n = 10000
    x = random.randn(n)
    y = -x + random.randn(n)
    
    # bin
    nbins = 100
    H, xedges, yedges = histogram2d(x, y, bins=nbins)
    
    # Figure out centers of bins
    def centers(edges):
        return edges[:-1] + diff(edges[:2])/2
    
    xcenters = centers(xedges)
    ycenters = centers(yedges)
    
    # Construct interpolator
    pdf = interp2d(xcenters, ycenters, H)
    
    # test
    plt.pcolor(xedges, yedges, pdf(xedges, yedges))
    

Result:

![result of interpolation](http://i.stack.imgur.com/fasvy.png)

Note that this will be linearly interpolated rather than step-wise. For a
quicker version which assumes a regular grid, this will also work:

    
    
    from numpy import meshgrid, vectorize
    
    def position(edges, value):
        return int((value - edges[0])/diff(edges[:2]))
    
    @vectorize
    def pdf2(x, y):
        return H[position(yedges, y), position(xedges, x)]
    
    # test - note we need the meshgrid here to get the right shapes
    xx, yy = meshgrid(xcenters, ycenters)
    plt.pcolor(xedges, yedges, pdf2(xx, yy))
    

