如何在 R 中的 ggplot 的最上面插入注释?

How to insert annotation on the very top facet of ggplot in R?

我想要 annotation 在下面 ggplot 的第一个 facet 上。现在,代码在所有 facets 上绘制 annotation。无论如何转发将不胜感激。

library(ggplot2)
library(lubridate)

set.seed(123)

DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2005-12-31"), by = "1 month"),
                  Ob = runif(60,1,5), L95 =runif(60, 0,4), U95 = runif(60,2,7), Sim = runif(60,1,5)) %>% 
      pivot_longer(names_to = "Variable", values_to = "Value", -Date)

ggplot(data = DF, aes(x = Date))+
  geom_line(aes(y = Value))+
  facet_wrap(~ Variable, scales = "free_y", nrow = 4)+
  geom_vline(xintercept = as.Date("2004-12-01"),color = "red", size = 1.30)+
  annotate(geom = "text", x = as.Date("2002-01-01"), y = 3, label = "Calibration")+
  annotate(geom = "text", x = as.Date("2005-06-01"), y = 3, label = "Validation")

您可以使用 geom_text():

尝试像这样将数据坐标包装在构面顶部的值
library(ggplot2)
library(lubridate)
#Code
ggplot(data = DF, aes(x = Date))+
  geom_line(aes(y = Value,group=Variable))+
  facet_wrap(~ Variable, scales = "free_y", nrow = 4)+
  geom_vline(xintercept = as.Date("2004-12-01"),color = "red", size = 1.30)+
  geom_text(data=data.frame(Variable='L95',Date=as.Date("2002-01-01"),
                            label="Calibration",Value=max(DF$Value)),
            aes(y=Value,label=label))+
  geom_text(data=data.frame(Variable='L95',Date=as.Date("2005-06-01"),
                            label="Validation",Value=max(DF$Value)),
            aes(y=Value,label=label))

输出:

您可以使用 geom_text 执行此操作。为绘图创建一个单独的数据框。

library(ggplot2)

text_data <- data.frame(x = as.Date(c("2002-01-01", "2005-06-01")), 
                        y = 3.5, Variable = sort(unique(DF$Variable))[1], 
                        label = c("Calibration", "Validation"))

ggplot(data = DF, aes(x = Date))+
  geom_line(aes(y = Value))+
  facet_wrap(~ Variable, scales = "free_y", nrow = 4)+
  geom_vline(xintercept = as.Date("2004-12-01"),color = "red", size = 1.30) + 
  geom_text(data = text_data, aes(x, y, label = label), color = 'blue')