Issue
Below is a code in which it plots a sine wave and adds a step wave on top of it:
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()
And this results in the following plot:
Is there a way to label this point, where the arrow is located?
Solution
IIUC, one of the options would be to add shifted samples to the 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')
Answered By - Timeless
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.