下面是一个代码,它绘制了一个正弦波并在其顶部添加了一个阶跃波:
import numpy as np
import matplotlib.pyplot as plt
# sine wave parameters
A = 5 # Increased Amplitude
f = 1 # Frequency in Hz
T = 1/f # Period
t = np.linspace(0, 2*T, 1000) # Time from 0 to 2 periods
# Create a sine wave
sine_wave = A * np.sin(2 * np.pi * f * t)
# Digital signal (sampled)
sampling_rate = 10
sampling_interval = 1 / sampling_rate
sample_times = np.arange(0, 2*T, sampling_interval)
sampled_sine_wave = A * np.sin(2 * np.pi * f * sample_times)
# Plot the results with a step function representing the digital signal and label the points
plt.figure(figsize=(12, 8))
plt.plot(t, sine_wave, label='Continuous Sine Wave')
plt.step(sample_times, sampled_sine_wave, 'r-', where='post', linewidth=2, label='Digital Signal (Step Wave)')
# Label each point on the step function
for x, y in zip(sample_times, sampled_sine_wave):
label = f"{y:.2f}"
plt.annotate(label, (x, y), textcoords="offset points", xytext=(0,10), ha='center', fontsize=8, color='blue')
plt.title('Analog Sine Wave and Digital Step Signal with Labels')
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.legend()
plt.grid(True)
plt.show()
这会导致以下情节:
有没有办法绘制箭头所在的点?
如有任何帮助,我们将不胜感激。
zip
:
for xl, xr, y in zip(sample_times, sample_times[1:], sampled_sine_wave):
label = f"{y:.2f}"
plt.annotate(label, (xl, y), textcoords="offset points",
xytext=(0,10), ha='center', fontsize=8, color='blue')
plt.annotate(label, (xr, y), textcoords="offset points",
xytext=(0,10), ha='center', fontsize=8, color='green')
输出: