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

如何在ggplot2的geom_line折线图末尾添加Unicode拉丁十字符号

在ggplot2折线图的每条折线末尾添加拉丁十字符号"✝"

问题说明

你目前使用geom_point时会给所有数据点都添加符号,需要实现仅在每条折线的末尾位置添加拉丁十字"✝"。

解决方案

核心是先筛选出每个id对应的最后一个时间点的数据,再用这个子集绘制末尾符号,而非使用全部数据集。

步骤1:提取每条折线的末尾数据点

利用dplyr的分组和切片功能,获取每个id的最后一行数据:

end_points <- longer_t1 %>%
  group_by(id) %>%
  slice_tail(n = 1) %>%
  ungroup()

步骤2:修改ggplot代码绘制符号

将geom_point的数据源替换为筛选后的end_points,并设置对应的符号:

library(tidyverse)
library(scales)

# 加载你的数据集
longer_t1 <- structure(list(id = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 
5L, 5L, 5L, 5L, 6L, 6L, 7L, 7L, 7L, 7L, 8L, 9L, 9L, 9L, 10L, 
10L, 10L, 11L, 11L, 11L, 11L, 12L, 12L, 13L, 13L, 14L, 14L, 15L, 
16L, 17L, 17L, 18L, 18L, 19L, 19L, 20L, 20L, 20L, 21L, 21L, 21L, 
22L, 23L, 23L, 24L, 24L, 25L, 25L, 26L, 26L, 27L, 27L, 28L, 28L, 
29L, 29L, 29L, 30L), levels = c("1", "2", "3", "4", "5", "6", 
"7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", 
"18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", 
"29", "30"), class = "factor"), time_point = structure(c(1L, 
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 3L, 4L, 1L, 2L, 1L, 2L, 3L, 
4L, 1L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 4L, 1L, 2L, 1L, 2L, 
1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 3L, 1L, 2L, 3L, 
1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 3L, 
1L), levels = c("0", "24", "48", "72"), class = "factor"), avg_rag = c(257600, 
11653000, 161100, 295303000, 151300, 6288000, 319800, 67233000, 
190000, 3326000, 4050900, 97663200, 233900, 10203000, 253100, 
325400, 2438700, 24111900, 405300, 319400, 1598100, 17572700, 
370900, 2510100, 143632700, 323900, 2521100, 3371700, 18591900, 
468600, 92084100, 317700, 155815100, 228200, 26215100, 260500, 
270400, 302800, 156915100, 104400, 172215100, 80900, 133516700, 
167800, 4845700, 22993100, 146900, 2938700, 19033100, 100500, 
47300, 134416700, 169400, 17296700, 62500, 929600, -68800, 1251600, 
265000, 1956600, 193700, 946600, 153100, 1032600, 15145000, 134300
)), row.names = c(NA, -66L), class = c("tbl_df", "tbl", "data.frame"
))

# 提取每个id的末尾数据点
end_points <- longer_t1 %>%
  group_by(id) %>%
  slice_tail(n = 1) %>%
  ungroup()

# 绘制折线图并添加末尾符号
ggplot(longer_t1, 
       aes(x = time_point, y = avg_rag, group = id, colour = id)) +
  geom_line(linewidth = 1) +
  scale_y_continuous(breaks = pretty_breaks()) +
  scale_x_discrete(name = "time in h") +
  theme_classic() +
  # 若你的Label列已存在,可保留此图层,否则注释掉
  # geom_label(aes(label = Label)) +
  geom_point(
    data = end_points,
    shape = "✝",  # 也可使用Unicode编码"\u271D"
    size = 5,
    position = position_nudge(x = 0.07)
  )

关键说明

  • slice_tail(n = 1)会在每个id分组中提取最后一行数据,精准定位每条折线的末尾点
  • 仅用end_points作为geom_point的数据源,确保符号只出现在折线末尾
  • 符号可直接使用字符"✝"或对应的Unicode编码"\u271D",两者效果一致

内容的提问来源于stack exchange,提问作者mr.raccoon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:45:03