Python绘图:如何在指定x轴范围内标注峰值数据?
解决峰值标注的索引错误与范围筛选问题
错误原因解析
- 你最初的循环用
x里的浮点数值当索引调用y[i],但numpy数组/列表的索引必须是整数、切片这类合法类型,浮点数直接当索引肯定报错。 - 把
x转成int后,比如11.944会被转成11,但你的y数组只有7个元素(索引范围是0到6),11远超出了数组的有效索引范围,所以触发越界错误。
实现代码(带范围筛选)
先把数据转成numpy数组(处理起来更便捷),然后筛选出x值在xlim区间内的峰值,再进行标注:
import matplotlib.pyplot as plt import numpy as np # 原始数据 x = np.array([1.5293, 2.9786, 8.6734, 11.944, 13.309, 13.337, 14.591]) y = np.array([3978.072, 1391.799, 1739.091, 218146.734, 29643.477, 29680.311, 965.577]) xlim = [11.5, 12.5] # 筛选x在指定范围内的索引 mask = (x >= xlim[0]) & (x <= xlim[1]) filtered_x = x[mask] filtered_y = y[mask] # 绘制全量数据图 plt.figure(figsize=(10, 5)) plt.subplot(121) plt.plot(x, y, 'b-', marker='o') # 标注符合条件的峰值 for px, py in zip(filtered_x, filtered_y): plt.annotate(f'{int(py)}', (px, py), textcoords="offset points", xytext=(0,10), ha='center') plt.xlabel('X轴') plt.ylabel('Y轴') plt.title('全量数据图') # 绘制峰值放大图 plt.subplot(122) plt.plot(x, y, 'b-', marker='o') plt.xlim(xlim) # 标注符合条件的峰值 for px, py in zip(filtered_x, filtered_y): plt.annotate(f'{int(py)}', (px, py), textcoords="offset points", xytext=(0,10), ha='center') plt.xlabel('X轴') plt.ylabel('Y轴') plt.title('峰值放大图') plt.tight_layout() plt.show()
代码说明
mask = (x >= xlim[0]) & (x <= xlim[1]):生成布尔数组,标记哪些x值在指定范围内。filtered_x和filtered_y:只保留符合范围的峰值数据。plt.annotate里的textcoords="offset points", xytext=(0,10)是让标注文本在峰值点上方10像素处,避免和点重叠,ha='center'让文本居中对齐。
内容的提问来源于stack exchange,提问作者werghuiop
相关产品推荐
相关产品推荐

