Random Chart Generator with Seaborn

  • Share this:

Code introduction


This function uses the seaborn library to randomly generate different types of charts, including bar plots, box plots, line plots, and scatter plots. It first generates a random dataset and then draws a chart based on the randomly selected chart type.


Technology Stack : The packages and technologies used in this code include seaborn, numpy, matplotlib, and pandas.

Code Type : The type of code

Code Difficulty : Intermediate


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

def generate_random_plot():
    # Generate a random dataset
    np.random.seed(10)
    data = pd.DataFrame({
        'Category': pd.Categorical([np.random.choice(['A', 'B', 'C']) for _ in range(100)]),
        'Value': np.random.rand(100) * 100
    })

    # Randomly select a seaborn plot type
    plot_type = np.random.choice(['barplot', 'stripplot', 'lineplot', 'scatterplot'])

    # Set the figure and axis
    plt.figure(figsize=(10, 6))
    ax = plt.gca()

    # Generate the plot based on the random selection
    if plot_type == 'barplot':
        sns.barplot(x='Category', y='Value', data=data, ax=ax)
    elif plot_type == 'stripplot':
        sns.stripplot(x='Category', y='Value', data=data, ax=ax)
    elif plot_type == 'lineplot':
        sns.lineplot(x='Category', y='Value', data=data, ax=ax)
    elif plot_type == 'scatterplot':
        sns.scatterplot(x='Category', y='Value', data=data, ax=ax)

    plt.title(f'Random {plot_type}')
    plt.show()