如何在Python中从重复周期的曲线图提取指定数据点?
提取曲线图中手动标记的蓝色数据点(Python实现)
我有一个包含6个重复周期的曲线图,单个周期的效率数据如下,后续周期重复该数据。图中星号为实际数据点,需要提取手动标记的蓝色数据点,请问如何在Python中实现?
我的数据
Efficiency 0 0 59.02 60 56.54 56.54 62.63 61.94 61.94 62.9 59.02 0
绘图代码
x = df["Efficiency"] import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=(25,6)) axes = fig.add_axes([0.1,0.1,0.8,0.8]) axes.plot(x, color='green', lw=3, marker="*", ms=15, mec='r') plt.xlim(0,72) plt.ylim(0,65) plt.show()
对应的曲线图:
解决方案
方法1:手动指定单周期内的蓝色点位置
先观察单个周期里哪些索引对应蓝色标记点(比如从图中可看到单个周期内的第3、4、7、10、11个数据点,对应索引2、3、6、9、10),然后按周期批量提取:
import pandas as pd # 单个周期内蓝色点的索引(对应单周期数据的位置) single_cycle_blue_indices = [2, 3, 6, 9, 10] total_cycles = 6 # 生成所有周期的蓝色点全局索引 global_blue_indices = [idx + cycle*12 for cycle in range(total_cycles) for idx in single_cycle_blue_indices] # 提取数据 blue_points = df.iloc[global_blue_indices]["Efficiency"] # 输出结果 print("提取的蓝色点数据:") print(blue_points)
方法2:自动识别特征点(若蓝色点为峰值/关键转折点)
如果蓝色点是每个周期的峰值、上升沿起点或下降沿终点,可以用代码自动识别:
import pandas as pd import numpy as np eff_data = df["Efficiency"].values cycle_length = 12 blue_points = [] global_blue_indices = [] for cycle_num in range(6): # 截取当前周期的数据 cycle_data = eff_data[cycle_num*cycle_length : (cycle_num+1)*cycle_length] # 1. 找上升沿第一个非0点 first_non_zero = np.where(cycle_data > 0)[0][0] # 2. 找下降沿最后一个非0点 last_non_zero = np.where(cycle_data > 0)[0][-1] # 3. 找局部峰值(排除首尾0) peak_mask = (cycle_data[1:-1] > cycle_data[:-2]) & (cycle_data[1:-1] > cycle_data[2:]) & (cycle_data[1:-1] > 0) peak_indices = np.where(peak_mask)[0] + 1 # 转换为原周期索引 # 合并所有蓝色点索引并去重 cycle_blue_indices = np.unique([first_non_zero, last_non_zero] + list(peak_indices)) # 转换为全局索引 global_indices = [cycle_num*cycle_length + idx for idx in cycle_blue_indices] # 收集数据和索引 blue_points.extend(eff_data[global_indices]) global_blue_indices.extend(global_indices) # 转换为Series方便查看 blue_points_series = pd.Series(blue_points, index=global_blue_indices, name="Blue_Point_Efficiency") print("自动提取的蓝色点数据:") print(blue_points_series)
验证提取结果
可以把提取的蓝色点叠加到原图上,确认是否正确:
import matplotlib.pyplot as plt fig = plt.figure(figsize=(25,6)) axes = fig.add_axes([0.1,0.1,0.8,0.8]) # 绘制原图 axes.plot(df["Efficiency"], color='green', lw=3, marker="*", ms=15, mec='r') # 绘制提取的蓝色点 axes.scatter(global_blue_indices, blue_points, color='blue', s=200, zorder=5) plt.xlim(0,72) plt.ylim(0,65) plt.show()
内容的提问来源于stack exchange,提问作者aparna podili
相关产品推荐
相关产品推荐

