Random Visualization Function

  • Share this:

Code introduction


This function accepts a DataFrame and the names of x and y columns, randomly selects a chart type (scatter plot, line plot, bar plot, histogram), and draws it with random colors.


Technology Stack : Pandas, NumPy, Seaborn, Matplotlib

Code Type : Python Function

Code Difficulty : Intermediate


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

def random_viz_function(data, x, y):
    """
    This function creates a random visualization based on the input data and specified columns.
    """
    # Create a DataFrame from the input data
    df = pd.DataFrame(data)
    
    # Generate a random plot type
    plot_type = random.choice(['scatter', 'line', 'bar', 'histogram'])
    
    # Choose random color palette
    palette = sns.color_palette(random.choice(['husl', 'hsv', 'coolwarm', 'viridis', 'plasma', 'magma']))
    
    # Create the plot based on the random plot type
    if plot_type == 'scatter':
        plt.scatter(df[x], df[y], color=random.choice(palette))
    elif plot_type == 'line':
        plt.plot(df[x], df[y], color=random.choice(palette))
    elif plot_type == 'bar':
        plt.bar(df[x], df[y], color=random.choice(palette))
    elif plot_type == 'histogram':
        plt.hist(df[y], bins=random.randint(5, 10), color=random.choice(palette))
    
    plt.xlabel(x)
    plt.ylabel(y)
    plt.title(f'Random {plot_type.capitalize()} Plot')
    plt.show()

# Example usage:
# data = {'x': [1, 2, 3, 4, 5], 'y': [2, 3, 5, 7, 11]}
# random_viz_function(data, 'x', 'y')