You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pracma::findPeaks检测峰值并在ggplot中绘制竖线的问题

解决pracma::findPeaks峰值位置无法直接用于ggplot竖线绘制的问题

问题原因

pracma::findPeaks返回结果的第二列(即你代码中的peaks$V2)是y向量的索引位置,不是x轴的实际数值。你直接将这个索引值作为xintercept传入geom_vline,相当于把索引数当成了x轴坐标,这和你的信号x轴范围(如-505这类数值)完全不匹配,自然会出现位置逻辑不符的问题。

修正方案

从findPeaks的结果中提取峰值对应的索引,再从你的test数据框中取出对应索引的x轴实际数值,用这个数值来绘制竖线。同时避免用sapply批量添加图层,直接传入向量更简洁可靠。

修正后的代码

# 数据与初始绘图
x <- c(-505, -492.278481012658, ...)
y <- c(1.08962117485998, ...)
test <- as.data.frame(cbind(x, y))
ggplot(test, aes(x = x,y =  y)) + geom_line()+ theme_bw()

# 修正后的峰值检测与竖线绘制
library(pracma)
# findPeaks返回矩阵:V1=峰值y值,V2=y向量中的索引,V3=峰值左边界索引,V4=峰值右边界索引
peaks <- pracma::findpeaks(y, npeaks = 3)
# 通过索引提取对应x轴的实际数值
peak_x_values <- test$x[peaks[, 2]]

# 正确绘制峰值竖线
ggplot(test, aes(x = x, y = y)) + 
  geom_line() + 
  theme_bw() +
  geom_vline(xintercept = peak_x_values, color = "red", linetype = "dashed")

扩展:绘制峰值范围(左右边界)

如果需要标记峰值的左右边界范围,可以用findPeaks返回的V3、V4索引提取对应x值:

# 提取峰值左右边界的x值
peak_left_x <- test$x[peaks[, 3]]
peak_right_x <- test$x[peaks[, 4]]

# 绘制峰值及范围线
ggplot(test, aes(x = x, y = y)) + 
  geom_line() + 
  theme_bw() +
  geom_vline(xintercept = peak_x_values, color = "red", linetype = "dashed") +
  geom_vline(xintercept = c(peak_left_x, peak_right_x), color = "blue", linetype = "dotted")

内容的提问来源于stack exchange,提问作者Paul Endymion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 02:17:47