Random Boxplot Generation with Seaborn

  • Share this:

Code introduction


This function generates a random boxplot using the seaborn library, with options to display the median line and rotate the x-axis labels.


Technology Stack : seaborn, numpy, pandas, 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 generate_random_boxplot(dataframe, x, y, hue=None):
    """
    Generate a random boxplot using seaborn.
    """
    # Set up random seed for reproducibility
    np.random.seed(0)
    
    # Randomly select the palette
    palette = sns.color_palette(np.random.choice(['husl', 'coolwarm', 'viridis', 'muted'], 1)[0])
    
    # Generate the boxplot
    sns.boxplot(data=dataframe, x=x, y=y, hue=hue, palette=palette)
    
    # Randomly choose if we want to show the median line
    if np.random.choice([True, False]):
        plt.axhline(y=dataframe[y].median(), color='black', linewidth=0.5)
    
    # Randomly choose if we want to rotate the x-axis labels
    if np.random.choice([True, False]):
        plt.xticks(rotation=45)
    
    plt.show()

# Example usage:
# Create a random DataFrame
np.random.seed(0)
data = pd.DataFrame({
    'Category': np.random.choice(['A', 'B', 'C'], 100),
    'Value': np.random.rand(100) * 100
})
data['Category'] = data['Category'].astype('category')

# Call the function
generate_random_boxplot(data, 'Category', 'Value')