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
相关产品推荐
相关产品推荐

