ggplot中为阈值线上方点添加id标签运行报错求助
错误原因
- 语法缺失:
geom_label_repel()代码块末尾没有加+连接后续的labs()函数,导致图层链断裂,ggplot无法识别后续参数 - 全局映射不兼容子集数据:全局
aes()中直接指定x = as.numeric(row.names(df.sample)),当geom_text_repel、geom_label_repel调用只有1行的离群点子集时,继承的x映射长度和子集数据长度不匹配,触发长度校验错误 - 冗余图层:同时调用
geom_text_repel和geom_label_repel功能重叠,无需同时使用 - 阈值标注映射冲突:标注阈值线的
geom_text继承了全局映射,容易和固定位置的参数产生冲突
修复后可运行的完整代码
library(tidyverse) library(ggplot2) library(ggrepel) library(scales) library(ggthemes) df.sample %>% ggplot(aes(x = as.numeric(row.names(.)), # 用.指代管道传入的数据,避免全局变量引用问题 y = amount, label = as.character(id))) + geom_point(alpha = 0.6, position = position_jitter(w = 0.05, h = 0.0), aes(colour = (amount < 3)), size = 2) + geom_hline(aes(yintercept = 3, linetype = "Limit"), color = 'black', size = 1) + # 阈值标注关闭全局映射继承,避免长度不匹配 geom_text(inherit.aes = FALSE, aes(y = 3, x = 2, # 可根据实际数据量调整x位置 label = paste("Limit = ", round(3, 3))), hjust = 0, vjust = 1.5) + # 保留单个标签图层即可,带背景的label_repel可读性更强 geom_label_repel(data = subset(df.sample, outlier == 'TRUE'), nudge_y = 0.75, size = 4, box.padding = 0.5, point.padding = 0.5, force = 100, segment.size = 0.2, segment.color = "grey50", direction = "x") + # 补上缺失的图层连接符+ labs(title = "Outlier Detection", y = "amount", x = "") + theme_few() + theme(legend.position = "none", axis.text = element_text(size = 10, face = "bold"), axis.title = element_text(size = 10, face = "bold"), plot.title = element_text(colour = "blue", hjust = 0.5, size = 15, face = "bold"), strip.text = element_text(size = 10, face = "bold")) + scale_colour_manual(values = c("TRUE" = "green","FALSE" = "red"))
补充说明
如果不需要标签带白色背景,可直接把geom_label_repel替换为geom_text_repel。
内容的提问来源于stack exchange,提问作者Sharath
相关产品推荐
相关产品推荐

