Creating Pairplots with Distinct Hue Categories

  • Share this:

Code introduction


This function creates a pairplot with distinct colors for each category in the hue variable based on the given DataFrame and column names.


Technology Stack : Seaborn, Pandas, NumPy, Matplotlib

Code Type : The type of code

Code Difficulty : Intermediate


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

def plot_distinct_categories(data, x, y, hue):
    """
    This function creates a pairplot with distinct categories for the given hue variable.
    """
    # Create a DataFrame with the specified columns
    df = data[[x, y, hue]]
    
    # Group the data by the hue variable
    grouped = df.groupby(hue)
    
    # Create a pairplot for each category in the hue variable
    sns.pairplot(grouped, hue=hue)
    
    # Show the plot
    plt.show()

# Example DataFrame
data = pd.DataFrame({
    'x': np.random.randn(100),
    'y': np.random.randn(100),
    'hue': np.random.choice(['A', 'B', 'C'], 100)
})

# Call the function
plot_distinct_categories(data, 'x', 'y', 'hue')