如何在ggplot折线图末尾添加列名标签?geom_text/geom_label失效
ggplot折线图末尾添加列名的解决方案
我尝试用ggplot绘制折线图时,想在每条折线的末尾添加对应列的名称,但使用geom_text和geom_label都无法实现预期效果。我的代码如下:
df %>% filter(played < 39) %>% #筛选出赛季场次为38场的数据 filter(place==1) %>% #只分析冠军队伍 #绘制冠军数据折线图 ggplot()+ aes(x=season) + geom_line(aes(y=points), color = "blue") + geom_line(aes(y=goals), color="red") + geom_line(aes(y=won), color = "purple") + geom_line(aes(y=loss), color = "orange") + geom_line(aes(y=draw)) + geom_label() + labs( title = "巴西甲级联赛", subtitle = "2006 - 2024" ) + theme( )
当前图表效果:
你的代码存在两个核心问题:
- 采用宽格式数据单独绘制每条折线,导致标签无法批量对应到每条线
geom_label()没有指定任何映射参数(x、y坐标和标签内容),自然不会显示预期的文本
正确的做法是先把数据转换为长格式,再统一处理折线和标签,具体步骤如下:
1. 数据转长格式
使用tidyr::pivot_longer将多个数值列(points、goals、won、loss、draw)转换为两列:metric(存储原列名)和value(存储对应数值),这样可以用一条geom_line绘制所有折线。
2. 绘制折线并添加末尾标签
- 折线部分:通过
aes(group = metric, color = metric)让ggplot自动区分不同指标的折线 - 标签部分:过滤出每个指标的最后一个赛季数据,用
geom_label将标签定位在折线末尾
完整代码:
library(tidyverse) df %>% filter(played < 39, place == 1) %>% # 转换为长格式 pivot_longer(cols = c(points, goals, won, loss, draw), names_to = "metric", values_to = "value") %>% ggplot(aes(x = season, y = value)) + # 绘制所有折线,自动按metric区分颜色和分组 geom_line(aes(color = metric, group = metric), linewidth = 1) + # 添加折线末尾标签:筛选每个metric的最后一个season数据 geom_label(data = . %>% group_by(metric) %>% filter(season == max(season)), aes(label = metric), hjust = 0, # 标签向左对齐(避免超出图表) nudge_x = 0.2, # 标签向右偏移一点,避免和折线重叠 show.legend = FALSE) + labs(title = "巴西甲级联赛", subtitle = "2006 - 2024", y = "数值") + theme_minimal()
代码说明
pivot_longer:将宽格式转长格式,是处理多系列折线图的标准操作,大幅简化代码geom_label的data参数:通过分组筛选每个指标的最后一个赛季数据,确保标签只出现在折线末尾hjust = 0和nudge_x:调整标签位置,避免和折线或图表边缘重叠show.legend = FALSE:避免标签在图例中重复显示
内容的提问来源于stack exchange,提问作者Lucas Batista
相关产品推荐
相关产品推荐

