Random Bar Plot Generation with Seaborn

  • Share this:

Code introduction


This function generates a random bar plot using the seaborn library. It accepts a DataFrame and two string arguments representing the data columns for the x and y axes. If the hue argument is specified, it can also group by this argument. The function also allows for custom color palettes.


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_bar_plot(data, x, y, hue=None, palette='viridis'):
    """
    Generates a random bar plot using seaborn.
    """
    # Create a DataFrame from the data
    df = pd.DataFrame(data)
    
    # Set the style of the visualization
    sns.set(style="whitegrid")
    
    # Create the bar plot
    plt.figure(figsize=(10, 6))
    ax = sns.barplot(x=x, y=y, hue=hue, data=df, palette=palette)
    
    # Set the title and labels
    ax.set_title('Random Bar Plot')
    ax.set_xlabel(x)
    ax.set_ylabel(y)
    
    # Display the plot
    plt.show()

# Example usage:
data = {
    'Category': np.random.choice(['A', 'B', 'C'], size=30),
    'Values': np.random.rand(30) * 100
}
df = pd.DataFrame(data)
generate_random_bar_plot(df, 'Category', 'Values')