Random Plot Generator with Matplotlib

  • Share this:

Code introduction


This function generates a random plot using the matplotlib library. It draws data based on a randomly selected type, such as line, bar, scatter, histogram, or pie chart.


Technology Stack : matplotlib, numpy, random, plt.subplots(), ax.plot(), ax.bar(), ax.scatter(), ax.hist(), ax.pie(), plt.show()

Code Type : The type of code

Code Difficulty : Intermediate


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

def random_plot(x, y):
    """
    Generate a random plot with a selected type from matplotlib.
    """
    # Select a random plot type
    plot_types = ['line', 'bar', 'scatter', 'hist', 'pie']
    plot_type = random.choice(plot_types)
    
    # Generate a random figure and axis
    fig, ax = plt.subplots()
    
    # Plot the data based on the selected type
    if plot_type == 'line':
        ax.plot(x, y)
    elif plot_type == 'bar':
        ax.bar(x, y)
    elif plot_type == 'scatter':
        ax.scatter(x, y)
    elif plot_type == 'hist':
        ax.hist(y, bins=10)
    elif plot_type == 'pie':
        ax.pie(y)
    
    # Show the plot
    plt.show()

# Example usage:
# random_plot(np.random.rand(10), np.random.rand(10))