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

在R中绘制同时间序列两组的scatter plot并执行cross-correlation分析

解决方案

完全可行,核心是先把你的宽格式数据转成适合分组处理的长格式,再一步步完成绘图和分析。下面是具体代码和步骤:

1. 数据格式转换(关键步骤)

你的数据是宽格式(每列对应一个重复),先用tidyr把它转成长格式,方便后续分组处理:

# 加载必要包
library(tidyverse)
library(ggplot2)

# 模拟你的数据(替换成真实数据即可)
set.seed(123)
df <- tibble(
  Time = 1:10,
  Vitamin_rep1 = rnorm(10, 5, 1),
  Vitamin_rep2 = rnorm(10, 5, 1.2),
  Diffusion_rep1 = rnorm(10, 10, 2) + 0.8*Vitamin_rep1,
  Diffusion_rep2 = rnorm(10, 10, 2) + 0.7*Vitamin_rep2
)

# 转长格式:将Vitamin和Diffusion的重复列拆分,按Time和重复编号配对
df_long <- df %>%
  pivot_longer(cols = starts_with("Vitamin"), names_to = "Vitamin_Rep", values_to = "Vitamin") %>%
  pivot_longer(cols = starts_with("Diffusion"), names_to = "Diffusion_Rep", values_to = "Diffusion") %>%
  # 提取重复编号(比如从Vitamin_rep1中提取1)
  mutate(
    Rep = str_extract(Vitamin_Rep, "\\d+"),
    Rep = as.factor(Rep)
  ) %>%
  # 只保留同编号的重复配对(比如Vitamin_rep1对应Diffusion_rep1)
  filter(str_extract(Vitamin_Rep, "\\d+") == str_extract(Diffusion_Rep, "\\d+")) %>%
  select(Time, Rep, Vitamin, Diffusion)

2. 绘制带线性回归的散点图

用ggplot2绘制,支持按重复组添加回归线,或者添加整体回归线:

# 散点图+分组回归线
ggplot(df_long, aes(x = Vitamin, y = Diffusion, color = Rep)) +
  geom_point(size = 2, alpha = 0.7) +
  geom_smooth(method = "lm", se = FALSE, linewidth = 1) +
  labs(x = "Vitamin Intake", y = "Diffusion", title = "Vitamin vs Diffusion with Replicates") +
  theme_bw()

# 散点图+整体回归线(不分组)
ggplot(df_long, aes(x = Vitamin, y = Diffusion)) +
  geom_point(aes(color = Rep), size = 2, alpha = 0.7) +
  geom_smooth(method = "lm", se = TRUE, linewidth = 1, color = "black") +
  labs(x = "Vitamin Intake", y = "Diffusion", title = "Vitamin vs Diffusion with Global Regression") +
  theme_bw()

3. 时间序列互相关分析

互相关用来分析两组时间序列在不同滞后下的相关性,可针对每个重复组单独计算,也可合并所有重复计算:

# 针对每个重复组做互相关分析
df_long %>%
  group_by(Rep) %>%
  group_walk(function(data, key) {
    cat("=== 重复组", key$Rep, "互相关分析 ===\n")
    ccf_result <- ccf(data$Vitamin, data$Diffusion, plot = TRUE, main = paste("Cross-Correlation for Rep", key$Rep))
    # 打印显著的滞后值(95%置信水平)
    sig_lags <- which(abs(ccf_result$acf) > qnorm((1 + 0.95)/2)/sqrt(length(data$Time)))
    cat("显著滞后值:", ccf_result$lag[sig_lags], "\n\n")
  })

# 合并所有重复做整体互相关(需保证时间顺序一致)
all_vitamin <- c(df_long$Vitamin[df_long$Rep == "1"], df_long$Vitamin[df_long$Rep == "2"])
all_diffusion <- c(df_long$Diffusion[df_long$Rep == "1"], df_long$Diffusion[df_long$Rep == "2"])
ccf(all_vitamin, all_diffusion, plot = TRUE, main = "Cross-Correlation (All Replicates)")

关键说明

  • 转长格式是解决分组问题的核心,转成后可轻松按重复组(Rep)执行任何分析或绘图操作。
  • 互相关结果中,正滞后表示Diffusion滞后于Vitamin,负滞后表示Vitamin滞后于Diffusion。
  • 如果你的重复不需要严格配对(比如允许Vitamin_rep1和Diffusion_rep2组合),去掉代码里的filter步骤即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 13:01:07