R-找数据的波谷:找出位置和数值并画在图上
2024-08-19 本文已影响0人
MYS_bio_man
R-找数据的波谷:找出位置和数值并画在图上
1. 普通函数
Assuming your data is stored in a variable called data
data <- c(1,0,9,8,77,5,3,0,0,8,9,55,4,33,22,11,2) # Replace with your actual data
Calculate density
dens <- density(data)
Find indices of local minima
find_minima <- function(dens_y) {
local_minima <- c(FALSE, diff(sign(diff(dens_y))) > 0, FALSE)
return(local_minima)
}
Apply the function to density values
minima_indices <- find_minima(dens$y)
Get the x value corresponding to the valley
valley_x <- dens$x[minima_indices]
Plot the density and highlight the valley
plot(dens, main = "Density Distribution with Valley")
polygon(dens, col="lightcoral", border="black")
points(valley_x, dens$y[minima_indices], col="blue", pch=19)
image.png
2. ggplot2的实现
加载必要的包
library(ggplot2)
假设数据存储在变量 data 中,这里顺便换组数据试试看
data <- c(1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3)
计算密度
dens <- density(data)
找到局部极小值的索引
find_minima <- function(dens_y) {
local_minima <- c(FALSE, diff(sign(diff(dens_y))) > 0, FALSE)
return(local_minima)
}
应用函数找出密度中的极小值
minima_indices <- find_minima(dens$y)
获取波谷对应的x值和y值
valley_x <- dens$x[minima_indices]
valley_y <- dens$y[minima_indices]
将密度估计结果转化为数据框,以便使用ggplot2
df <- data.frame(x = dens$x, y = dens$y)
使用ggplot2绘制密度图,并标注波谷
ggplot(df, aes(x = x, y = y)) +
geom_line(size = 1) +
geom_area(fill = "lightcoral", alpha = 0.5) +
geom_point(aes(x = valley_x, y = valley_y), color = "blue", size = 3) +
ggtitle("let us see 1 see") +
labs(x = "Value", y = "Density") +
theme_minimal(base_size = 15) +
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_rect(color = "black", fill = NA, size = 1)
)
image.png