如何标记使用 ggrepel 拆分获得的行

How to label lines obtained using split with ggrepel

我正在尝试标记按变量 cc 的值分组的 4 行。为了标记我使用 ggrepel 的线条,但我得到了所有 4 个标签,而不是每个图形的 2 个。如何更正此错误?

标签的位置在此示例中是最后一个日期,但我想要更灵活的东西:我想在我选择的特定点中定位 4 个标签中的每一个(例如 b 在日期 1 , a 在日期 2 等)。怎么做?

library(tidyverse)
library(ggrepel)
library(cowplot)

set.seed(1234)
df <- tibble(date = c(rep(1,4), rep(2,4), rep(3,4), rep(4,4)),
             country = rep(c('a','b','c','d'),4),
             value = runif(16),
             cc = rep(c(1,1,2,2),4))

df$cc <- as.factor(df$cc)

# make list of plots
ggList <- lapply(split(df, df$cc), function(i) {
  ggplot(i, aes(x = date, y = value, color = country)) +
    geom_line(lwd = 1.1) +
    geom_text_repel(data = subset(df, date == 4),
                    aes(label = country)) +
    theme(legend.position = "none")
})

# plot as grid in 1 columns
cowplot::plot_grid(plotlist = ggList, ncol = 1,
                   align = 'v', labels = levels(df$cc))


Created on 2021-08-18 by the reprex package (v2.0.0)

在这里我做了一个小标题来保存颜色和位置偏好,并将其加入 df

geom_text_repel 行可能应该使用 i 而不是 df,这样它的拆分方式与该行相同。唯一的麻烦是这迫使我们预先指定我们需要四种颜色,否则每个图表只会使用它需要的两种颜色。

set.seed(1234)
df <- tibble(date = c(rep(1,4), rep(2,4), rep(3,4), rep(4,4)),
             country = rep(c('a','b','c','d'),4),
             value = runif(16),
             cc = rep(c(1,1,2,2),4))

label_pos <- tibble(country = letters[1:4], 
                    label_pos = c(2, 1, 3, 2),
                    color = RColorBrewer::brewer.pal(4, "Set2")[1:4])
df <- df %>% left_join(label_pos)


df$cc <- as.factor(df$cc)

# make list of plots
ggList <- lapply(split(df, df$cc), function(i) {
  ggplot(i, aes(x = date, y = value, color = color)) +
    geom_line(lwd = 1.1) +
    geom_text_repel(data = subset(i, date == label_pos),
                    aes(label = country), box.padding = unit(0.02, "npc"), direction = "y") +
    scale_color_identity() +
    theme(legend.position = "none")
})

# plot as grid in 1 columns
cowplot::plot_grid(plotlist = ggList, ncol = 1,
                   align = 'v', labels = levels(df$cc))