Combining Boxplot, Violin, and Density Plots with Seaborn

  • Share this:

Code introduction


This function creates a combination plot of boxplot, violin plot, and density plot using the Seaborn library to visualize data distribution. It first generates a random color palette, then fits a normal distribution to the data, and then draws a boxplot, violin plot, and density plot. Finally, it displays the graph.


Technology Stack : Seaborn, NumPy, Pandas, Matplotlib, SciPy

Code Type : The type of code

Code Difficulty : Advanced


                
                    
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm

def random_seaborn_plot(dataframe, x, y):
    # Generate a random color palette
    palette = sns.color_palette("hsv", len(dataframe))

    # Fit a normal distribution to the data
    z = np.random.normal(size=len(dataframe))

    # Create a boxplot with the specified color palette
    sns.boxplot(x=x, y=y, data=dataframe, palette=palette)

    # Overlay a violin plot on the same data
    sns.violinplot(x=x, y=y, data=dataframe, palette=palette)

    # Overlay a density plot on the violin plot
    sns.kdeplot(x=x, y=y, data=dataframe, palette=palette)

    plt.show()

# Example usage:
# dataframe = pd.DataFrame({
#     'x': np.random.rand(100),
#     'y': np.random.rand(100)
# })
# random_seaborn_plot(dataframe, 'x', 'y')