ggplot2分组geom_vline均值线添加标签报Aesthetics长度错误
报错原因
报错核心是图层数据源不匹配:
- 你在最顶层
ggplot()里全局指定了数据源为原始数据df(共134行),后续未显式指定data参数的图层都会默认继承这个数据源 - 出问题的
geom_text层没有指定独立数据源,却直接传入了长度仅为4的llab$grp.mean、llab$ys向量,映射向量长度和当前图层数据源行数不一致,就会触发该报错 - 额外隐患:你使用了
s字段做分面,就算强行对齐长度,不绑定分面对应字段的话,所有分组标签会在两个班次分面中重复出现,不符合绘图逻辑
修复方案
- 给分组均值标签对应的
geom_text层显式指定数据源为存储分组统计结果的mu数据框,不要直接用$从全局环境提取向量传入映射 - 将x轴位置、标签文本都映射为
mu数据框内的对应列,mu中自带分面字段s,可以自动匹配分面规则,不会出现标签跨分面重复的问题 - 原有固定参考线的
geom_text逻辑无需修改,这类传入长度为1的常量映射不会和全局数据源产生长度冲突
修正后可运行代码
library(ggplot2) library(dplyr) df <- read.csv("f4_bna_no_cup.csv") # 按年-班次分组计算x均值,.groups = "drop" 取消分组残留避免后续警告 mu <- df %>% group_by(ys,s) %>% summarise(grp.mean = mean(x), .groups = "drop") ggplot(data=df, aes(x=x, group =ys, fill = yr, color = yr)) + geom_density(alpha = 0.4) + scale_x_continuous(limits=c(112,120))+ # 绘制分组均值竖线 geom_vline(aes(xintercept = grp.mean), data = mu, linetype = "dashed", size = 0.5) + # 修复后的分组均值标签:指定数据源、绑定字段映射,自动适配分面 geom_text(data = mu, aes(x=grp.mean, y=.6, label = ys), angle = 90, size = 3, vjust = -0.5, color = "black") + # 以下固定参考线及标签原有逻辑正常,无需修改 geom_vline(aes(xintercept=114.8), linetype="dashed", size=0.5, color = 'green3') + geom_text(aes(x=114.8, y=.6), label = "Target", angle = 90, color="black",size=3) + geom_vline(aes(xintercept=114.1), linetype="solid", size=0.5, color = 'limegreen') + geom_text(aes(x=114.1, y=.55), label = "Potential", angle = 90, color="black",size=3 ) + geom_vline(aes(xintercept=113.4), linetype="solid", size=0.5, color = 'firebrick3') + geom_text(aes(x=113.4, y=.62), label = "Label wt", angle = 90, color="black",size=3, family = "Times New Roman", vjust=0) + facet_grid( .~s, labeller = labeller( s = c(`1` = "Shift 1", `2` = "Shift 2") ))+ theme_light()+ theme(legend.position = "none")
注:代码中给分组均值标签统一设置了90度旋转、边距调整参数,和其余参考线标签风格保持一致,可根据实际显示效果微调y轴位置、对齐参数。
内容的提问来源于stack exchange,提问作者Jammer
相关产品推荐
相关产品推荐

