ggplot线的选择性标记

时间:2018-03-22 21:41:34

标签: r plot ggplot2 label line-plot

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

潜在的功能/包:我了解geom_text()功能和直接标签包但我无法在其文档中找出一种方法来有选择地标记行我上面描述的方式。

示例数据

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(),直接标记或任何其他函数自动(而不是手动)仅标记最后一个点为Y >= 50的行(紫色和绿色的线条根据他们的ID?

非常感谢你的帮助!

2 个答案:

答案 0 :(得分:2)

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

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))

enter image description here

答案 1 :(得分:2)

如果您愿意,可以通过过滤数据来获取相应的标签位置,从而动态添加标签。例如:

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)

enter image description here