Matplotlib阶梯图特定点位标注方法咨询
如何给阶梯图上的特定点添加箭头标注
完全可以实现,你只需要在原有代码基础上,针对想要标注的特定点单独设置带箭头的注释即可。下面是修改后的示例代码,关键改动已标注:
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)') # 标注所有点(保留原有逻辑) 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') # --- 新增:给特定点添加箭头标注 --- # 示例1:标注第3个采样点(索引从0开始) target_idx = 2 x_target, y_target = sample_times[target_idx], sampled_sine_wave[target_idx] plt.annotate( f"关键点\n{y_target:.2f}", (x_target, y_target), textcoords="offset points", xytext=(30, 20), # 注释文本偏移量 ha='center', fontsize=10, color='red', arrowprops=dict(arrowstyle="->", color='red', lw=1.5) # 设置箭头样式 ) # 示例2:标注振幅最大的点 max_y_idx = np.argmax(sampled_sine_wave) x_max, y_max = sample_times[max_y_idx], sampled_sine_wave[max_y_idx] plt.annotate( f"峰值\n{y_max:.2f}", (x_max, y_max), textcoords="offset points", xytext=(-30, 30), ha='center', fontsize=10, color='green', arrowprops=dict(arrowstyle="->", color='green', lw=1.5) ) plt.title('Analog Sine Wave and Digital Step Signal with Target Point Annotations') plt.xlabel('Time') plt.ylabel('Amplitude') plt.legend() plt.grid(True) plt.show()
关键说明
- 你可以通过索引直接指定要标注的点,比如示例里的
target_idx = 2对应第3个采样点; - 也可以通过条件筛选特定点,比如用
np.argmax()找到振幅最大的点; arrowprops参数可以自定义箭头样式,包括箭头类型、颜色、线宽等;xytext用来调整注释文本相对于目标点的偏移位置,避免遮挡图像。
内容的提问来源于stack exchange,提问作者Akshay
相关产品推荐
相关产品推荐

