ggplot2各分面按分组自动添加匹配配色geom_hline的方法
实现方法
无需手动逐分面指定参考线参数,核心逻辑是提前按分面维度、Method分组维度计算目标x值(true landmark=0.65)对应的y轴截距,生成独立的参考线数据集,传入geom_hline()即可自动匹配分面位置、继承颜色映射。
具体操作步骤
- 由于你的x轴取值序列
true_landmark本身包含0.65,直接按type、n(两个分面维度)、method(颜色分组维度)过滤出landmark=0.65的行,对应的value就是每条水平线需要的y截距。 - 如果后续目标x值不在现有离散x点序列中,用线性插值函数
approx()计算对应y值即可,代码里已经预留了插值逻辑的注释。 - 绘图时将参考线数据集传入
geom_hline(),映射yintercept到截距列、color到method列,参考线会自动匹配对应分面,颜色和图例保持完全一致。
完整可运行代码
library(ggplot2) # 固定随机种子保证结果可复现 set.seed(123) # 基础参数定义 true_landmark=seq(0.15,0.85,by=0.05) pt=6 theta=0.65 P_T=0.8 # 补全原代码缺失的参数定义 L=length(true_landmark) # 构造示例数据集 type <- rep(c(rep("Exponential",L*2),rep("Log-Normal",L*2),rep("Weibull",L*2)),3) method <- rep(c(rep("Landmark PFS",L),rep("RMST",L)),3*3) n <- c(rep(20,L*2*3),rep(30,L*2*3),rep(40,L*2*3)) value <- replicate(18,cumsum(runif(15))) landmark <- rep(true_landmark,2*3*3) df <- data.frame(type,method,n,value,landmark) df$n <- factor(df$n,labels=c(expression(n==20),expression(n==30),expression(n==40))) df$type <- factor(df$type, labels=c("Exponential", expression(paste("Log-Normal (",sigma==1,")")), expression(paste("Weibull (",k==0.5,")")))) # 生成水平参考线数据集:直接提取landmark=0.65对应的取值 hline_data <- df[df$landmark == theta, ] # 若目标x值不在现有x序列中,取消下面注释用插值法计算对应y值 # hline_data <- do.call(rbind, lapply(split(df, list(df$type, df$n, df$method)), function(subdf){ # data.frame( # type = unique(subdf$type), # n = unique(subdf$n), # method = unique(subdf$method), # value = approx(subdf$landmark, subdf$value, xout = theta)$y # ) # })) # 绘图 ggplot(df, aes(landmark,value,color=method)) + geom_line(alpha=0.5)+ geom_point(shape=19,alpha=0.5)+ # 添加匹配分面和配色的水平参考线 geom_hline(data = hline_data, aes(yintercept = value, color = method), linewidth=1)+ scale_x_continuous(name =paste("True Landmark PFS at", pt, "Months"), breaks=seq(true_landmark[1],true_landmark[length(true_landmark)], 0.1))+ ylab(label="Probability of Go")+ geom_vline(xintercept = theta, color="black", linetype="dashed")+ facet_grid(n~type,labeller=label_parsed)+ guides(color=guide_legend(title="Method"))+ theme(plot.caption=element_text(hjust=0))+ labs(caption=paste("Go: Posterior prob (True PFS/RMST at", pt, "month > target|data)", ">", P_T," Dashed line indicates target landmark PFS/RMST value"))
效果说明
- 无需手动指定18个(9分面*2方法)截距参数,代码自动按分组匹配位置
- 参考线颜色自动继承Method映射,和图例配色完全一致,无需手动指定色值
- 后续调整分面规则、增加方法分组时,只要参考线数据集的分组字段和主图保持一致,即可自动适配,无需修改参考线代码
内容的提问来源于stack exchange,提问作者Remy M
相关产品推荐
相关产品推荐

