ggplot 线条的选择性标记

Selective labeling for ggplot lines

总体目标: 使用 ggplot 有选择地仅标记最后一个点高于特定 y 值的线。

潜力 Functions/Packages: 我知道 geom_text() 函数和 directlabels 包,但我无法在他们的文档中找到一种方法来选择性地按照我上面描述的方式标记行。

示例数据

ID <- c(rep("ID1", 5), rep("ID2", 5), rep("ID3", 5), rep("ID4", 5), rep("ID5", 5))
Y <- c(1, 2, 3, 4, 5, 
       10, 20, 30, 40, 1, 
       5, 10, 15, 10, 60, 
       50, 30, 20, 25, 10,
       20, 25, 30, 35, 50)
Year <- c(rep(seq(2000 ,2004), 5))
DATA <- data.frame(ID, Year, Y)

绘图数据

ggplot(data=DATA, aes(Year, Y)) + 
  geom_line(aes(y=Y, x=Year, color=ID)) + 
  theme_bw()

情节

问题

在上图的情况下,有没有办法使用 gg_text()、directlabels 或任何其他函数来自动(而不是手动)仅标记最后一个点为 [=14= 的线](紫线和绿线)根据他们的ID?

非常感谢您的帮助!

最简单的方法是根据条件将标签添加到数据框中,然后绘图。

library(tidyverse)
DATA %>% 
  mutate(label = ifelse(Y >= 50 & Year == max(Year), ID, NA)) %>%
  ggplot(aes(Year, Y)) + 
    geom_line(aes(color = ID)) + 
    geom_text(aes(label = label))

如果您愿意,您可以动态添加标签,方法是过滤数据以获得适当的标签位置。例如:

ggplot(data=DATA, aes(Year, Y, color=ID)) + 
  geom_line() + 
  geom_text(data=DATA %>% group_by(ID) %>% 
              arrange(desc(Year)) %>% 
              slice(1) %>% 
              filter(Y >= 50),
            aes(x = Year + 0.03, label=ID), hjust=0) +
  theme_bw() +
  guides(colour=FALSE) +
  expand_limits(x = max(DATA$Year) + 0.03)