geom_label_repel未关联sec.axis求助:双轴ggplot标签无法自动定位
解决ggplot双轴图表中geom_label_repel定位错误的问题
问题核心是标签的Y轴映射未和折线保持一致:你的折线通过prop*15将次轴数值缩放到主轴范围,但标签用的是prop*1,导致位置完全偏离折线。
修正步骤
- 将
geom_label_repel中的y = prop*1改为y = prop*15,和折线的Y轴缩放系数统一 - 修正
arrange的错误写法(原代码arrange(df, by = day)简化为arrange(day)) - 调整次轴
breaks参数(原范围0-10超出次轴实际值,改为0-1匹配prop的取值范围)
完整修正代码
library(ggplot2) library(dplyr) library(scales) df <- data.frame(day = as.character(seq(from = 1, to = 100, by = 1)), total = rbinom(n=100,30,0.5), prop = runif(100)) df <- df %>% arrange(day) df$`percentage` <- label_percent(accuracy = 0.01)(df$prop) ggplot(data = df, aes(x = day, y = total)) + geom_bar(stat = "identity", fill = "lightgreen", width = 0.35) + geom_line(aes(x = day, y = prop*15, group = 1), color = "red", size = 1) + scale_y_continuous( labels = function(x) format(x, scientific = FALSE), sec.axis = sec_axis(trans = ~./15, name = "Secondary axis", breaks = seq(from = 0, to = 1, by = 0.1), labels = scales::percent))+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5))+ geom_label_repel(data=df[nrow(df),], aes(x = day, y = prop*15, label = paste0(round(prop*100,2), "%")), color = 'red', segment.alpha = 0.5) + scale_x_discrete(expand = expansion(add = c(0, 7)))
关键说明
- 双轴图表本质是将次轴数据缩放后映射到主轴,所有关联次轴的图层(折线、标签)必须使用相同的缩放比例
sec_axis的breaks要匹配转换后的数据范围,避免出现无效刻度- 标签文本追加
%符号,和次轴的百分比格式保持一致,提升可读性
内容的提问来源于stack exchange,提问作者Bileobio
相关产品推荐
相关产品推荐

