Gaussian Kernel Density Estimation for 2D Data Visualization

  • Share this:

Code introduction


This function plots the 2D density estimate of a given dataset using Gaussian kernel density estimation.


Technology Stack : Matplotlib, NumPy, SciPy

Code Type : Function

Code Difficulty : Intermediate


                
                    
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

def plot_2d_density(data):
    """
    This function plots the 2D density estimate of a given dataset using a Gaussian kernel density estimation.
    """
    # Create a grid of points
    x = np.linspace(data[:, 0].min(), data[:, 0].max(), 100)
    y = np.linspace(data[:, 1].min(), data[:, 1].max(), 100)
    xx, yy = np.meshgrid(x, y)

    # Compute the density estimate
    positions = np.vstack([data[:, 0], data[:, 1]])
    kernel = gaussian_kde(positions)
    f = np.reshape(kernel(xx, yy), (100, 100))

    # Plot the density estimate
    plt.imshow(f, extent=(x.min(), x.max(), y.min(), y.max()), origin='lower')
    plt.colorbar()
    plt.show()

# Example usage
data = np.random.multivariate_normal([0, 0], [[1, 0.5], [0.5, 1]], 100)
plot_2d_density(data)