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

R语言ggplot绘制分组折线图时如何为各折线末端点添加数值标注

你可以通过添加geom_text图层,仅映射每个分组的末端点数据实现标注需求,具体实现步骤如下:

步骤1:提取各分组折线的末端点数据

先筛选出每个Foundation Type对应最大年份的观测值,作为标注的数据源:

library(tidyverse)
end_points <- USbyFoundType %>%
  group_by(`Foundation Type`) %>%
  filter(Year == max(Year)) %>%
  ungroup()

步骤2:修改绘图代码添加标注层

在原有折线图代码基础上增加geom_text层即可:

ggplot(USbyFoundType, aes(x=Year, y=`Percent Shares`, 
            group=`Foundation Type`, color=`Foundation Type`)) +
  geom_line() +
  geom_text(data = end_points,
            # 标注保留2位小数,可根据需求调整精度或直接使用原始值
            aes(label = round(`Percent Shares`, 2)),
            hjust = -0.2, # 控制文字位于点的右侧,避免遮挡折线
            show.legend = FALSE) # 关闭标注的图例,避免和折线图例重复

标注重叠优化方案

如果分组较多导致末端标签重叠,可以使用ggrepel包的geom_text_repel自动调整标签位置:

# 未安装先执行:install.packages("ggrepel")
library(ggrepel)

ggplot(USbyFoundType, aes(x=Year, y=`Percent Shares`, 
            group=`Foundation Type`, color=`Foundation Type`)) +
  geom_line() +
  geom_text_repel(data = end_points,
            aes(label = round(`Percent Shares`, 2)),
            nudge_x = 0.3,
            direction = "y",
            show.legend = FALSE)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 01:51:04