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

R语言如何提取密度(density)图最后一个峰值的关联数据

R实现密度曲线最后一个峰值对应数据提取

推荐工具包

使用pracma包的findpeaks函数即可实现非固定数量峰值的识别与最后一个峰值的提取,适配你的需求。

完整实现代码

1. 安装加载依赖包

# 首次使用需先安装
install.packages("pracma")
library(pracma)

2. 峰值识别与区间定位

# 提取待分析数值向量
val_vec <- data$V1
# 计算密度曲线,可根据业务需求调整带宽bw参数
dens_res <- density(val_vec)
# 识别所有峰值,可调整参数过滤噪声假峰
# 可选参数说明:minpeakheight 最小峰高阈值,minpeakdistance 峰之间最小间隔
peak_info <- findpeaks(dens_res$y, minpeakheight = 0.003)
# 所有峰值按x轴数值从小到大排序,取最后一个
sorted_peak_idx <- order(dens_res$x[peak_info[, 2]])
last_peak_pos <- peak_info[sorted_peak_idx, 2][length(sorted_peak_idx)]
# 定位最后一个峰的左右边界(谷值位置)
left_valley_pos <- which.min(dens_res$y[1:last_peak_pos])
right_valley_pos <- last_peak_pos + which.min(dens_res$y[last_peak_pos:length(dens_res$y)])
left_bound <- dens_res$x[left_valley_pos]
right_bound <- dens_res$x[right_valley_pos]

3. 提取对应原始数据

# 筛选落在最后一个峰区间内的所有原始观测值
last_peak_data <- data[data$V1 >= left_bound & data$V1 <= right_bound, ]

验证方法

你可以通过绘图验证区间准确性:

plot(dens_res, main = "密度曲线与最后一个峰区间")
abline(v = c(left_bound, right_bound), col = "red", lty = 2)
points(dens_res$x[last_peak_pos], dens_res$y[last_peak_pos], col = "blue", pch = 19)
  • 红色虚线为最后一个峰的左右边界
  • 蓝色点为最后一个峰值位置

内容的提问来源于stack exchange,提问作者Marine Bergot

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 08:36:04