如何在R的ggplot中绘制波数不匹配的两个FTIR光谱到同一图
解决FTIR光谱波数不一致时的同图绘制问题
方法一:直接叠加线条(最简单快捷)
不需要合并数据集,直接在同一个ggplot对象中依次添加两个geom_line,分别指定各自的数据集,并通过颜色区分两组数据:
library(readxl) library(ggplot2) # 读取两个数据集 sacola57 <- read_excel("57.xlsx", sheet = 1) PADRAO <- read_excel("padrao.xlsx", sheet = 1) # 绘制对比图 ggplot() + # 添加第一个光谱线条 geom_line(data = sacola57, aes(x = Wavenumber, y = Absorbance, color = "sacola57")) + # 添加第二个光谱线条 geom_line(data = PADRAO, aes(x = Wavenumber, y = Absorbance, color = "PADRAO")) + # 设置主题,移除网格线 theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + # 自定义图例标题和颜色 labs(color = "样本类型") + scale_color_manual(values = c("sacola57" = "#1f77b4", "PADRAO" = "#ff7f0e"))
方法二:插值对齐波数后用长格式绘图
如果希望用tidy数据格式绘图,可以先通过插值将两个数据集的波数对齐,再合并成统一数据集:
library(readxl) library(ggplot2) library(dplyr) library(tidyr) # 读取数据 sacola57 <- read_excel("57.xlsx", sheet = 1) PADRAO <- read_excel("padrao.xlsx", sheet = 1) # 生成统一的波数序列:覆盖两个数据集的全部波数范围,步长设为1 min_wavenum <- min(sacola57$Wavenumber, PADRAO$Wavenumber) max_wavenum <- max(sacola57$Wavenumber, PADRAO$Wavenumber) common_wavenum <- seq(from = min_wavenum, to = max_wavenum, by = 1) # 对两个数据集分别进行线性插值,匹配统一波数 sacola_interp <- tibble( Wavenumber = common_wavenum, Absorbance = approx(sacola57$Wavenumber, sacola57$Absorbance, xout = common_wavenum)$y, Sample = "sacola57" ) padrao_interp <- tibble( Wavenumber = common_wavenum, Absorbance = approx(PADRAO$Wavenumber, PADRAO$Absorbance, xout = common_wavenum)$y, Sample = "PADRAO" ) # 合并成长格式数据集 combined_data <- bind_rows(sacola_interp, padrao_interp) # 绘制对比图 ggplot(combined_data, aes(x = Wavenumber, y = Absorbance, color = Sample)) + geom_line() + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + labs(color = "样本类型") + scale_color_manual(values = c("sacola57" = "#1f77b4", "PADRAO" = "#ff7f0e"))
说明
- 方法一适合快速出图,不需要修改原始数据;
- 方法二通过插值对齐波数,适合后续需要对数据进行统一分析的场景,
approx函数默认使用线性插值,能较好保留FTIR光谱的趋势。
内容的提问来源于stack exchange,提问作者oceanpath
相关产品推荐
相关产品推荐

