Using scipy.stats.gaussian_kde with 2 dimensional data

后端 未结 4 1943
独厮守ぢ
独厮守ぢ 2020-12-31 20:13

I\'m trying to use the scipy.stats.gaussian_kde class to smooth out some discrete data collected with latitude and longitude information, so it shows up as somewhat similar

4条回答
  •  一整个雨季
    2020-12-31 20:46

    This example seems to be what you're looking for:

    import numpy as np
    import scipy.stats as stats
    from matplotlib.pyplot import imshow
    
    # Create some dummy data
    rvs = np.append(stats.norm.rvs(loc=2,scale=1,size=(2000,1)),
                    stats.norm.rvs(loc=0,scale=3,size=(2000,1)),
                    axis=1)
    
    kde = stats.kde.gaussian_kde(rvs.T)
    
    # Regular grid to evaluate kde upon
    x_flat = np.r_[rvs[:,0].min():rvs[:,0].max():128j]
    y_flat = np.r_[rvs[:,1].min():rvs[:,1].max():128j]
    x,y = np.meshgrid(x_flat,y_flat)
    grid_coords = np.append(x.reshape(-1,1),y.reshape(-1,1),axis=1)
    
    z = kde(grid_coords.T)
    z = z.reshape(128,128)
    
    imshow(z,aspect=x_flat.ptp()/y_flat.ptp())
    

    enter image description here

    Axes need fixing, obviously.

    You can also do a scatter plot of the data with

    scatter(rvs[:,0],rvs[:,1])
    

    enter image description here

提交回复
热议问题