Generating Histogram and KDE for Random Distributions

  • Share this:

Code introduction


This function generates a histogram and a kernel density estimate (KDE) for a random distribution. It uses numpy to generate random data and then uses the HoloViews library to create and display the graphics.


Technology Stack : numpy, holoviews

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
def plot_random_distribution(x, bins=10, kde=True):
    import numpy as np
    import holoviews as hv
    import holoviews.element.bars as bars
    import holoviews.element.kdplot as kdplot
    
    # Generate a random distribution using numpy
    np.random.seed(0)
    x = np.random.normal(0, 1, size=1000)
    
    # Create a histogram and a kernel density estimate (KDE)
    hist = bars.Histogram(x, bins=bins)
    kde_plot = kdplot.KDE(x, bins=bins) if kde else None
    
    # Combine the histogram and KDE into a layout
    plot = (hist + kde_plot).cols(1)
    
    # Display the plot
    plot.show()