Random Catplot Generation with Seaborn

  • Share this:

Code introduction


This function uses the Seaborn library's catplot function to draw a boxplot of a randomly selected categorical variable against a numerical variable. If there is a categorical variable in the data, a grouping variable for color can also be selected.


Technology Stack : Seaborn, Pandas, Matplotlib

Code Type : The type of code

Code Difficulty :


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

def generate_random_catplot(data):
    """
    Generates a random catplot using Seaborn.

    Parameters:
    - data (DataFrame): A pandas DataFrame containing the data to plot.

    Returns:
    - None
    """
    # Randomly select a categorical variable for the x-axis
    x_var = data.select_dtypes(include=['category']).sample(1).columns[0]
    
    # Randomly select a numerical variable for the y-axis
    y_var = data.select_dtypes(include=['number']).sample(1).columns[0]
    
    # Randomly select a hue variable for the color
    hue_var = data.select_dtypes(include=['category']).sample(1).columns[0] if data.select_dtypes(include=['category']).shape[1] > 0 else None
    
    # Generate a figure and axis
    fig, ax = plt.subplots()
    
    # Plot the catplot
    sns.catplot(x=x_var, y=y_var, hue=hue_var, data=data, ax=ax)
    
    # Set title and labels
    ax.set_title(f"Catplot of {y_var} by {x_var}")
    ax.set_xlabel(x_var)
    ax.set_ylabel(y_var)
    if hue_var:
        ax.legend(title=hue_var)
    
    # Show the plot
    plt.show()

# Example usage
data = pd.DataFrame({
    'Category': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'],
    'Value': [1, 2, 3, 4, 5, 6, 7, 8, 9],
    'Group': ['X', 'X', 'X', 'Y', 'Y', 'Y', 'X', 'X', 'X']
})

generate_random_catplot(data)