将列表中的值打印到每个 ID 的绘图中

Printing values from a list to a plot for each ID

我有一个列表,列表中的每个值都有一个分配给数字的 ID。我想让每个 ID 的值都显示在图上。我不确定如何重现情节,所以我会尝试解释一下。我有每个 ID 的图,我希望这些值在图上显示为文本(我们只说线图的图)。因此,对于 ID "A" 的图,我希望 11 都出现在图上,因为在列表中,两个 A 都被赋予了值 1。对于 ID“B”,我希望 22 都出现在 ID“B”的地块上,对于另一个 ID s.

library(lubridate)
library(tidyverse)

date <- rep_len(seq(dmy("01-01-2010"), dmy("31-12-2013"), by = "days"),1000)
ID <- rep(c("A","B","C", "D", "E"), 100)

df <- data.frame(date = date,
                 x = runif(length(date), min = 60000, max = 80000),
                 y = runif(length(date), min = 800000, max = 900000),
                 ID)

df1 <- df %>% group_split(ID)
l <- list(1,2,3,4,5,1,2,3,4,5)
l <- setNames(l, c(unique(df$ID), unique(df$ID)))

像这样:

您可以传递 geom_text() 一种 label 审美,它会被 facet_wrap() 很好地分隔开,例如

library(tidyverse)
set.seed(47L)

df <- tibble(
  date = rep_len(seq(as.Date("2010-01-01"), as.Date("2013-12-31"), by = "days"), 1000),
  x = runif(length(date), min = 60000, max = 80000),
  y = runif(length(date), min = 800000, max = 900000),
  ID = rep(c("A","B","C", "D", "E"), 200)
)

id_labels <- tibble(
  ID = rep(unique(df$ID), 2),
  id_val = rep(1:5, 2)
) %>% 
  # make desired labels for each facet
  group_by(ID) %>%
  summarise(label = paste(ID, id_val, sep = ": ", collapse = '\n'))

df %>% 
  gather(var, val, x:y) %>% 
  ggplot(aes(date, val)) + 
  geom_line(aes(color = var)) + 
  geom_text(
    # hardcode position
    aes(x = as.Date('2010-04-01'), y = 500000, label = label),
    data = id_labels  # pass in data frame of labels
  ) +
  facet_wrap(~ID)