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

ggplot中线末端图例标签重叠原因及正确放置方法问询

ggplot折线图末端标签优化方案

针对你遇到的两个问题,给出如下解决方法:

问题1:将图例标签放置在每条折线末端

核心思路是按分组提取每组最后一个数据点,仅在该位置绘制标签,而非在全量数据上重复绘制。

问题2:解决标签重叠问题

原代码的问题在于:geom_text未按分组筛选数据,导致每个分组的所有行都绘制了一次标签,且last(moyenn_gliss)取的是全数据集的最后一个值,而非每组的末端值,最终造成标签重叠。

修正后的完整代码

df <- structure(list(Epreuve = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), levels = "CE", class = "factor"),     Country = structure(c(1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L,     1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L), levels = c("Country1",     "Country2"), class = "factor"), Month = structure(c(18779,     18779, 18809, 18809, 18840, 18871, 18871, 18901, 18901, 18932,     18962, 18962, 18993, 19024, 19024, 19052, 19083, 19113, 19144,     19144), class = "Date"), moyenn_gliss = c(55, 62, 47.5, 68.5,     44.6666666666667, 36, 45.6666666666667, 38, 25, 41.6666666666667,     48.6666666666667, 16.6666666666667, 52, 45.6666666666667,     25, 34, 23.3333333333333, 17.6666666666667, 25.3333333333333,     51.6666666666667), nb_total = c(250L, 38L, 250L, 38L, 250L,     250L, 38L, 250L, 38L, 250L, 250L, 38L, 250L, 250L, 38L, 250L,     250L, 250L, 250L, 38L), grp = c(4L, 3L, 4L, 3L, 4L, 4L, 3L,     4L, 3L, 4L, 4L, 3L, 4L, 4L, 3L, 4L, 4L, 4L, 4L, 3L)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"))

library(tidyverse); library(plotly)

# 预处理:提取每组最后一个数据点,用于绘制末端标签
df_labels <- df %>%
  group_by(Country, Epreuve) %>%
  slice_tail(n = 1) %>%
  ungroup() %>%
  mutate(label = paste(Country, Epreuve))

p <- df %>% 
  ggplot(aes(Month, moyenn_gliss, color = interaction(Country, Epreuve, drop = T, sep = " "))) + 
  geom_point(aes(size = grp)) + 
  geom_line(aes(size = grp * 0.7)) + 
  # 使用预处理后的标签数据,仅在每组末端绘制一次标签
  geom_text(data = df_labels, aes(x = Month, y = moyenn_gliss, label = label), 
            hjust = -0.1, # 标签稍微向右偏移,避免和点重叠
            show.legend = FALSE) + 
  scale_x_date(breaks = unique(df$Month), date_labels="%b %y") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) # 可选:旋转x轴标签避免重叠

ggplotly(p)

关键改动说明

  • 新增df_labels:按Country和Epreuve分组,提取每组最后一个数据点,确保每个分组仅生成一个标签位置。
  • geom_text指定data = df_labels:仅使用筛选后的标签数据绘制标签,避免重复绘制。
  • 添加hjust = -0.1:让标签稍微向右偏移,避免和折线末端的点重叠,优化视觉效果。
  • 移除原代码中在aes内赋值size_pt的写法,直接使用grp更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 22:36:20