Search code examples
pythonmatplotlibscipyhistogramspline

Spline Interpolation of a 2D Histogram - Python


i have a 2D Histogram (x,y coordinates and a “weight”) and i need to do a spline interpolation and extract data (so not only graphical), how can i do that with python? (i attach here the histo) Thanks! LightMap X_Z


Solution

  • You can use scipy, I took the following example from here and modified it slightly:

    from scipy import interpolate
    import matplotlib.pyplot as plt
    
    # define range of x values
    x = np.arange(-5.01, 5.01, 0.25)
    # define range of z values
    z = np.arange(-5.01, 5.01, 0.25)
    # create a meshgrid
    xx, zz = np.meshgrid(x, z)
    # these weights would be given to you in your histogram - here is an example function to generate weights
    weights = np.sin(xx**2+zz**2)
    # create interpolation object
    f = interpolate.interp2d(x, z, weights, kind='cubic')
    
    # generate new ranges of x and z values
    xnew = np.arange(-5.01, 5.01, 1e-2)
    znew = np.arange(-5.01, 5.01, 1e-2)
    # interpolate 
    weightsnew = f(xnew, znew)
    
    # plot
    plt.imshow(weightsnew)
    plt.show()