You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决ggplot中geom_text_repel线条注释不显示及重复问题

修复ggplot中geom_text_repel的两个问题:注释缺失与重复显示

问题原因分析

  • 重复注释:原数据中id有3个取值(1/2/3),经过pivot_longer转换后,每个class在time=4时会生成3条重复记录,导致geom_text_repel为同一类别绘制三次注释。
  • z类注释缺失:z列在time=3和time=4时均为NA,用subset(df.long, time == max(time))筛选后,z类没有有效数据,因此无法显示注释。

解决方案

  1. 消除重复注释:为每个class仅保留一条用于标注的记录,避免重复绘制。
  2. 修复z类注释缺失:不固定取最大time值,而是取每个class中最后一个非NA的score对应的行作为标注位置。

修改后的完整代码

library(ggplot2)
library(ggrepel)
library(dplyr)

df.1 <-
  data.frame(
    id = rep(c(1, 2, 3),each = 4),
    time = c(1, 2, 3, 4),
    x = c(1, 2, 3, 4),
    y = c(10, 23, 25, 28),
    z = c(2, 4, NA, NA)
  )

df.long <- df.1 %>% pivot_longer(cols = c(x, y, z), names_to = "class", values_to = "score")

# 生成注释用数据:每个class取最后一个非NA的score对应的行
label_data <- df.long %>%
  group_by(class) %>%
  filter(!is.na(score)) %>%
  slice_tail(n = 1) %>%
  ungroup()

ggplot(df.long, aes(x = time, y = score, col = class, group = class)) +
  geom_line() +
  geom_point() +
  geom_text_repel(
    data = label_data,
    aes(label = class),
    size = 2,
    point.padding = 0.2, 
    nudge_x = .3,
    segment.curvature = -1e-20,
    arrow = arrow(length = unit(0.015, "npc"))
  )

内容的提问来源于stack exchange,提问作者cliu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 19:11:07