如何在ggplot2混合效应模型中仅显示最差回归线的95%下界及优化图例
解决方案代码与说明
1. 加载依赖包并模拟数据集
library(tidyverse) # 固定随机种子确保结果可复现 set.seed(123) n_lots <- 5 # 批次数量 n_per_lot <- 10 # 每个批次的观测数 # 生成各批次的斜率(越负下降越快)和截距 slopes <- runif(n_lots, -2, -0.5) intercepts <- runif(n_lots, 90, 100) # 构造数据集 df <- expand_grid(Lot = paste0("Lot_", 1:n_lots), Time = seq(1, 10, length.out = n_per_lot)) %>% left_join(tibble(Lot = paste0("Lot_", 1:n_lots), slope = slopes, intercept = intercepts), by = "Lot") %>% mutate(Purity = intercept + slope * Time + rnorm(n(), 0, 1)) %>% select(-slope, -intercept)
2. 识别「最差回归线」批次
# 对每个批次拟合线性模型,计算与y=80的交点时间 lot_models <- df %>% group_by(Lot) %>% nest() %>% mutate(model = map(data, ~lm(Purity ~ Time, data = .x)), intercept = map_dbl(model, ~coef(.x)[[1]]), slope = map_dbl(model, ~coef(.x)[[2]]), # 计算回归线与y=80的交点时间 cross_time = (80 - intercept)/slope) %>% ungroup() # 筛选出最早与y=80相交的批次 worst_lot <- lot_models %>% filter(cross_time == min(cross_time)) %>% pull(Lot)
3. 生成最差批次的95%下界置信限数据
# 为最差批次生成预测数据,仅保留下界置信限 worst_pred <- lot_models %>% filter(Lot == worst_lot) %>% pull(model) %>% first() %>% predict(newdata = tibble(Time = seq(min(df$Time), max(df$Time), length.out = 100)), interval = "confidence", level = 0.95) %>% as_tibble() %>% mutate(Time = seq(min(df$Time), max(df$Time), length.out = 100)) %>% select(Time, lwr)
4. 绘制符合需求的图形
ggplot(df, aes(x = Time, y = Purity, color = Lot)) + # 绘制所有批次的散点 geom_point(size = 2) + # 绘制所有批次的回归线(无置信区间,不显示图例线条) geom_smooth(method = "lm", se = FALSE, show.legend = FALSE) + # 绘制最差批次的95%下界置信限(虚线) geom_line(data = worst_pred, aes(y = lwr, color = worst_lot), linetype = "dashed") + # 添加y=80的参考水平线 geom_hline(yintercept = 80, color = "red", linetype = "solid") + # 优化图例:仅显示点符号,隐藏线条 guides(color = guide_legend(override.aes = list(linetype = "blank"))) + # 图形标签设置 labs(title = "Purity vs Time by Lot", x = "Time", y = "Purity", color = "Lot") + theme_minimal()
关键说明
- 识别最差批次:通过计算每条回归线与y=80的交点时间,取时间最小的批次即为「最早相交」的最差批次。
- 下界置信限绘制:单独提取最差批次的模型预测结果,仅保留95%置信区间的下界,用虚线绘制。
- 图例优化:通过
show.legend = FALSE隐藏回归线的图例项,再用guide_legend(override.aes = list(linetype = "blank"))确保图例仅显示散点符号。
内容的提问来源于stack exchange,提问作者Joe the Second
相关产品推荐
相关产品推荐

