如何相对于 geom_point 图层制作注释图层

How to make an annotation layer relative to a geom_point layer

我希望此图表上的注释文本与折线图上的数据点相关,因为此报告已参数化,因此点会随着每次迭代而变化。如何使注释层相对于 geom_point 层? 这是我试过的...

degree_line <- degree_summary %>%
  ggplot(mapping = aes(x = chrt_grad, y = proportion, group = 1)) +
  geom_line(size = 1) +
  geom_point(shape = 1, stroke = 1.5) +
  scale_y_continuous(expand = expansion(mult = c(0, .1)),
                     labels = scales::percent,
                     limits = c(0, .4)) +
  annotate(geom = "text", x = 2016.8, y = degree_summary$proportion + .05, label = "4-year rate", 
           size = 3, hjust = 0, color = "#696969") +
  annotate(geom = "text", x = 2015.1, y = degree_summary$proportion + .05, label = "6-year rate", 
           size = 3, hjust = 1, color = "#696969") +
  labs(x = NULL,
       y = NULL)

但这就是我得到的...

dput(degree_summary)

structure(list(chrt_grad = 2014:2017, graduated = c("Y", "Y", 
"Y", "Y"), school = c("Bonita Vista Senior High", "Bonita Vista Senior High", 
"Bonita Vista Senior High", "Bonita Vista Senior High"), total = c(132L, 
122L, 117L, 92L), proportion = c(0.0172639288516872, 0.0167859108420473, 
0.0187259923175416, 0.0199522880069399)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -4L), groups = structure(list(
    chrt_grad = 2014:2017, graduated = c("Y", "Y", "Y", "Y"), 
    .rows = structure(list(1L, 2L, 3L, 4L), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, -4L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE))

我在您的数据中添加了一个包含所需标签的新列。然后你可以使用 geom_text 作为注释:

degree_summary %>%
  dplyr::mutate(
    label = dplyr::case_when(
      chrt_grad == 2015 ~ "6-year rate", 
      chrt_grad == 2017 ~ "4-year rate", 
      TRUE ~ ""
    )
  ) %>%
  ggplot(mapping = aes(x = chrt_grad, y = proportion, group = 1)) +
  geom_line(size = 1) +
  geom_point(shape = 1, stroke = 1.5) +
  geom_text(aes(label = label), nudge_y = 0.0005)
  scale_y_continuous(expand = expansion(mult = c(0, .1)),
                     labels = scales::percent,
                     limits = c(0, .4))