如何在R语言中计算光谱峰的FWHM(半高全宽)
用R语言计算光谱峰的半高全宽(FWHM)
示例数据与基础绘图
首先修正你代码中的变量名问题(原始数据集是theta和intensity,但创建数据框时误用了thetaOne/intensityOne),正确的绘图代码如下:
# 加载所需包 pacman::p_load(ggplot2, dplyr) # 示例数据集 theta <- c(32.1, 32.2, 32.3,32.4,32.5, 32.6, 32.7, 32.8, 32.9, 33.0, 33.1) intensity <- c(0, 0, 18, 138, 405, 449, 187, 29, 2, 0, 0) # 创建数据框 DataOne <- data.frame(theta = theta, intensity = intensity) # 绘制光谱图 PlotOne <- ggplot(data = DataOne) + geom_line(aes(x = theta, y = intensity), linewidth = 1) + labs(x = "Theta", y = "Intensity") + theme_minimal() PlotOne
自定义FWHM计算函数
下面是一个支持指定x轴区域的FWHM计算函数,针对离散的光谱数据,通过线性插值找到半高处的x值:
calculate_fwhm <- function(df, x_col, y_col, x_start, x_end) { # 筛选指定x区域内的数据 peak_data <- df %>% filter({{x_col}} >= x_start & {{x_col}} <= x_end) # 找到峰值强度和对应的x值 peak_intensity <- max(peak_data[[y_col]]) peak_x <- peak_data[[x_col]][which.max(peak_data[[y_col]])] # 计算半高值 half_height <- peak_intensity / 2 # 拆分峰值左侧和右侧数据,用于插值 left_side <- peak_data %>% filter({{x_col}} <= peak_x) right_side <- peak_data %>% filter({{x_col}} >= peak_x) # 线性插值找到左侧半高处的x值 left_x <- approx(x = left_side[[y_col]], y = left_side[[x_col]], xout = half_height)$y # 线性插值找到右侧半高处的x值 right_x <- approx(x = right_side[[y_col]], y = right_side[[x_col]], xout = half_height)$y # 计算FWHM fwhm_value <- right_x - left_x # 返回结果列表,包含峰值信息和FWHM return(list( peak_x = peak_x, peak_intensity = peak_intensity, half_height = half_height, left_half_x = left_x, right_half_x = right_x, fwhm = fwhm_value )) }
函数使用示例
针对你的示例数据,指定x轴范围32.2到33.0来计算FWHM:
# 计算FWHM fwhm_result <- calculate_fwhm(DataOne, theta, intensity, x_start = 32.2, x_end = 33.0) # 查看结果 print(fwhm_result) # 输出示例: # $peak_x # [1] 32.6 # # $peak_intensity # [1] 449 # # $half_height # [1] 224.5 # # $left_half_x # [1] 32.43659 # # $right_half_x # [1] 32.72059 # # $fwhm # [1] 0.284
可视化FWHM结果
可以把FWHM的标注添加到光谱图上,更直观:
PlotOne + # 标记峰值 geom_point(aes(x = fwhm_result$peak_x, y = fwhm_result$peak_intensity), color = "red", size = 3) + # 绘制半高水平线 geom_hline(yintercept = fwhm_result$half_height, linetype = "dashed", color = "blue") + # 标记半高处的两个点 geom_point(aes(x = fwhm_result$left_half_x, y = fwhm_result$half_height), color = "blue", size = 2) + geom_point(aes(x = fwhm_result$right_half_x, y = fwhm_result$half_height), color = "blue", size = 2) + # 添加FWHM文本标注 annotate("text", x = (fwhm_result$left_half_x + fwhm_result$right_half_x)/2, y = fwhm_result$half_height + 50, label = paste0("FWHM = ", round(fwhm_result$fwhm, 3)), color = "blue")
这个函数可以直接应用到你的大型数据集,只需要指定每个峰对应的x轴起始和结束范围即可。
内容的提问来源于stack exchange,提问作者Giovanni Saboia
相关产品推荐
相关产品推荐

