Plotting Data Distribution with Histogram and KDE

  • Share this:

Code introduction


This function uses the histplot function from the seaborn library to plot the distribution of a dataset, and at the same time overlays a Kernel Density Estimate (KDE) by setting the kde parameter to True, thus more intuitively showing the probability density of the data.


Technology Stack : seaborn, numpy, matplotlib

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

def plot_dist_with_kde(data):
    """
    Plots a distribution of a dataset using a histogram and a Kernel Density Estimate (KDE).
    """
    sns.set(style="whitegrid")
    plt.figure(figsize=(10, 6))
    
    # Plotting the distribution with a histogram and a KDE overlay
    sns.histplot(data, kde=True)
    
    plt.title("Distribution with KDE")
    plt.xlabel("Value")
    plt.ylabel("Frequency")
    plt.show()

# Usage of the function with a random numpy array
data = np.random.randn(1000)
plot_dist_with_kde(data)