Search code examples
pythonplotgraphfrequency

Generating sine wave signal with time-varying frequency


ı want to plot sine wave having different frequency and amplitude with different time in Python. For example, the sine wave having amplitude that is one in 0-100 samples (frequency must be 100) and two in 100-200 samples (freequncy must be 250). This is wave 1. And the other wave 2 similar to wave 1 must be created. Finally these must be sum up. Is it possible ? I tried different variant but. I did not get the result. In the code below, ı could not adjust frequency. How can o fix it ?

import matplotlib.pyplot as plt
import math

def y_func(x):
    return math.sin(x)

x_values = []
y_values = []

x = 0

amplitude = 1
while x < 5:
    x_values.append(x)
    y_values.append(amplitude * y_func(x))
    x += 0.1

amplitude = 2
while x < 10:
    x_values.append(x)
    y_values.append(amplitude * y_func(x))
    x += 0.1

plt.plot(x_values, y_values)

plt.title('test')
plt.show()

Solution

  • Please see the example below . It uses numpy which is often used for mathematical operations on time series or vectors.

    Result will look like this: result

    import matplotlib.pyplot as plt
    import numpy as np
    
    #Resolution of the x axis, for plotting
    #A resolution of 1e-4 seconds is equivalent to a frequency resolution of 10KHz,
    # which will give a smooth plot for our 250Hz wave
    t_resolution = 1e-4
    
    #Define the frequency 1 and frequency 2 waves
    freq1 = 100
    amplitude_1 = 1
    #To change the number of samples,
    # change the duration from 0.01s to something else
    n_samples_freq1 = int( 0.01 / t_resolution )
    
    freq2 = 250
    amplitude_2 = 2
    #To change the number of samples,
    # change the duration from 0.005s to something else
    n_samples_freq2 = int( 0.005 / t_resolution )
    
    #Now compute the waves
    total_samples = n_samples_freq1 + n_samples_freq2
    
    #Define a high-resolution time axis
    time_axis = np.arange(0, total_samples * t_resolution, t_resolution)
    
    #Create the freq1 and freq2 waves
    sin_freq1 = amplitude_1 * np.sin(2 * np.pi * freq1 * time_axis)
    sin_freq2 = amplitude_2 * np.sin(2 * np.pi * freq2 * time_axis)
    
    #Initially only freq1 is present (freq2 wave = 0)
    #Then freq1 wave is set to 0, and only freq2 is present.
    sin_freq1[n_samples_freq1:] = 0
    sin_freq2[:n_samples_freq1] = 0
    
    #Sum them together
    summed = sin_freq1 + sin_freq2
    
    #Plot the original waves, and the summed version
    plt.plot(time_axis, summed, 'grey', linewidth='12', label='freq1 + freq2')
    plt.plot(time_axis, sin_freq1, 'r--', linewidth=2, label='freq1')
    plt.plot(time_axis, sin_freq2, 'b', linewidth=2, label='freq2')
    plt.xlabel('time/s')
    plt.ylabel('amplitude')
    plt.legend()