Random Plot Generator

  • Share this:

Code introduction


This function generates a random plot based on the input data, including line plots, scatter plots, bar plots, and histograms.


Technology Stack : matplotlib, pandas, numpy

Code Type : The type of code

Code Difficulty : Intermediate


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

def generate_random_plot(data):
    """
    Generates a random plot based on the input data.
    """
    # Generate a random plot type
    plot_type = random.choice(['line', 'scatter', 'bar', 'histogram'])
    
    # Create a DataFrame from the input data
    df = pd.DataFrame(data)
    
    # Generate a figure and axis
    fig, ax = plt.subplots()
    
    # Plot the data based on the random plot type
    if plot_type == 'line':
        ax.plot(df['x'], df['y'], label='Line Plot')
    elif plot_type == 'scatter':
        ax.scatter(df['x'], df['y'], label='Scatter Plot')
    elif plot_type == 'bar':
        ax.bar(df['x'], df['y'], label='Bar Plot')
    elif plot_type == 'histogram':
        ax.hist(df['y'], bins=5, label='Histogram')
    
    # Add labels and title
    ax.set_xlabel('X-axis Label')
    ax.set_ylabel('Y-axis Label')
    ax.set_title('Random Plot')
    ax.legend()
    
    # Show the plot
    plt.show()

# Sample data
data = {
    'x': np.random.rand(10),
    'y': np.random.rand(10)
}

# Generate and display the plot
generate_random_plot(data)