Hydro
Hydro

Reputation: 1117

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

I would like to have the annotation on the very first facet of the following ggplot. right now, the code draws annotation on all facets. Anyway forward would be appreciate.

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

enter image description here

Upvotes: 1

Views: 387

Answers (2)

Duck
Duck

Reputation: 39595

You can try something like this wrapping data coordinates for the value on top of facets using 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))

Output:

enter image description here

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

You can do this with geom_text. Create a separate dataframe for plotting.

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

enter image description here

Upvotes: 1

Related Questions