Random Plot Generation with Seaborn

  • Share this:

Code introduction


This function generates a random plot using Seaborn based on the provided dataframe and parameters. The function first checks if the hue parameter is provided; if not, it randomly selects a column as the hue. Then, the function randomly chooses a plot type and creates the corresponding plot.


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_plot(dataframe, x, y, hue=None):
    """
    This function generates a random plot using Seaborn based on the provided dataframe and parameters.
    """
    # Generate a random categorical hue if hue is not provided
    if hue is None:
        hue = dataframe.columns[np.random.randint(dataframe.shape[1])]

    # Randomly choose a type of plot
    plot_type = np.random.choice(['bar', 'line', 'point', 'scatter', 'hist', 'kde'])

    # Randomly choose whether to use hue
    use_hue = np.random.choice([True, False])

    # Create the plot
    if plot_type == 'bar':
        sns.barplot(x=x, y=y, hue=hue, data=dataframe)
    elif plot_type == 'line':
        sns.lineplot(x=x, y=y, hue=hue, data=dataframe)
    elif plot_type == 'point':
        sns.pointplot(x=x, y=y, hue=hue, data=dataframe)
    elif plot_type == 'scatter':
        sns.scatterplot(x=x, y=y, hue=hue, data=dataframe)
    elif plot_type == 'hist':
        sns.histplot(y=y, hue=hue, data=dataframe)
    elif plot_type == 'kde':
        sns.kdeplot(x=x, hue=hue, data=dataframe)

    plt.show()

# Example usage:
# dataframe = pd.DataFrame({'x': np.random.rand(10), 'y': np.random.rand(10), 'group': np.random.choice(['A', 'B'], 10)})
# generate_random_plot(dataframe, 'x', 'y', 'group')