我想在Python中绘制不同时间、不同频率和幅度的正弦波。 例如,正弦波的振幅为 0-100 个样本中的 1 个(频率必须为 100)和 100-200 个样本中的 2 个(freequncy 必须为 250)。这是第 1 波。必须创建与第 1 波类似的另一个第 2 波波。最后必须总结一下这些。是否可以 ?我尝试了不同的变体但是。我没有得到结果。在下面的代码中,我无法调整频率。如何修复它?
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()
请参阅下面的示例。它使用
numpy
,通常用于时间序列或向量的数学运算。
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()