Scatter Plot and Histogram Visualization

  • Share this:

Code introduction


This function uses the matplotlib library's pyplot module to plot a scatter plot and a histogram. It takes data, axis labels, and a title as parameters and displays both the scatter plot and histogram on the same graph.


Technology Stack : matplotlib, NumPy

Code Type : Function

Code Difficulty : Intermediate


                
                    
import numpy as np
import matplotlib.pyplot as plt

def plot_scatter_with_histogram(data, x_label, y_label, title):
    """
    This function plots a scatter plot and a histogram of the given data.
    """
    fig, ax1 = plt.subplots()

    # Scatter plot
    ax1.scatter(data[:, 0], data[:, 1], color='b')
    ax1.set_xlabel(x_label)
    ax1.set_ylabel(y_label, color='b')
    ax1.tick_params(axis='y', labelcolor='b')

    # Instantiate a second axes that shares the same x-axis
    ax2 = ax1.twinx()

    # Histogram
    ax2.hist(data[:, 0], bins=20, color='r', alpha=0.5)
    ax2.set_ylabel('Frequency', color='r')
    ax2.tick_params(axis='y', labelcolor='r')

    plt.title(title)
    plt.show()

# Example usage:
# Generate random data for demonstration
np.random.seed(0)
data = np.random.randn(100, 2)

plot_scatter_with_histogram(data, 'X-axis', 'Y-axis', 'Scatter Plot with Histogram')