Histogram Plotting with NumPy and Matplotlib

  • Share this:

Code introduction


This function uses numpy's histogram function to calculate the histogram of the given data and then visualizes it using matplotlib.


Technology Stack : numpy, matplotlib

Code Type : Function

Code Difficulty : Intermediate


                
                    
import numpy as np
import matplotlib.pyplot as plt

def plot_histogram(data, bins=10):
    """
    Plots a histogram of the given data using numpy's histogram function and matplotlib for visualization.
    """
    # Generate histogram data
    counts, bin_edges = np.histogram(data, bins=bins)
    
    # Create the plot
    plt.figure(figsize=(8, 4))
    plt.bar(bin_edges[:-1], counts, width=np.diff(bin_edges), align='edge')
    plt.xlabel('Value')
    plt.ylabel('Frequency')
    plt.title('Histogram of Data')
    plt.show()

# Example usage
data = np.random.randn(1000)
plot_histogram(data)