Random Line Plot Generation with Matplotlib

  • Share this:

Code introduction


This function generates a random line plot using the matplotlib library. It allows for customizing the x-axis and y-axis labels, title, and legend labels.


Technology Stack : matplotlib library; line plot generation; customizing plot elements

Code Type : The type of code

Code Difficulty : Advanced


                
                    
import matplotlib.pyplot as plt
import numpy as np

def random_line_plot(x, y, title="Random Line Plot", xlabel="X Axis", ylabel="Y Axis", legend_labels=None):
    """
    Generate a random line plot using matplotlib.
    """
    plt.figure(figsize=(10, 5))
    plt.plot(x, y, label=legend_labels[0] if legend_labels else "Line 1")
    
    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    
    plt.grid(True)
    plt.show()

# Example usage:
# x = np.linspace(0, 10, 100)
# y = np.sin(x)
# random_line_plot(x, y, title="Sine Wave", xlabel="Angle (radians)", ylabel="Sine Value")