ggplot 线的选择性标记

fir*_*139 3 plot label r ggplot2 line-plot

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

潜在的函数/包:我知道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)
Run Code Online (Sandbox Code Playgroud)

绘制数据

ggplot(data=DATA, aes(Year, Y)) + 
  geom_line(aes(y=Y, x=Year, color=ID)) + 
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

阴谋

问题

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

非常感谢你的帮助!

eip*_*i10 5

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

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述