Generating and Saving Random Sine Wave Plot

  • Share this:

Code introduction


This function generates a random sine wave and plots it, then saves the plot to a file.


Technology Stack : matplotlib, numpy

Code Type : Function

Code Difficulty : Intermediate


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

def plot_random_data():
    # Generate random data
    x = np.linspace(0, 10, 100)
    y = np.sin(x) + random.uniform(-1, 1) * np.random.rand(100)
    
    # Plotting the data
    plt.figure(figsize=(10, 5))
    plt.plot(x, y, label='Random Sine Wave')
    plt.title('Random Sine Wave Plot')
    plt.xlabel('X-axis')
    plt.ylabel('Y-axis')
    plt.legend()
    plt.grid(True)
    
    # Save the plot to a file
    plt.savefig(f'plot_{datetime.now().strftime("%Y%m%d%H%M%S")}.png')
    plt.close()