Annotation on only the first facet of ggplot in R?

女生的网名这么多〃 提交于 2020-12-15 02:00:05

问题


I have the following code that produce a ggplot that has text (i.e., "calibration") on both facets. I want the text be appeared on the first facet only. I tried a few things but didn't succeed. Any help would be appreciated.

library(ggplot2)
library(lubridate)

set.seed(123)

DF1 <- 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),
                  Loc = rep("Upstream", 60))

DF2 <- 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),
                  Loc = rep("Downstream", 60))

DF <- dplyr::bind_rows(DF1,DF2)

DF$Loc <- factor(DF$Loc, levels = c("Upstream","Downstream"))


ggplot(DF, aes(x = Date))+
  geom_ribbon(aes(ymin = L95, ymax = U95), fill = "grey30", alpha = 0.4)+
  geom_line(aes(y = Ob, color = "blue"), size = 1 )+
  geom_line(aes(y = Sim, color = "black"), size =  1, linetype = "dashed")+
  geom_vline(xintercept = as.Date("2004-12-01"),color = "red", size = 1.30)+
  facet_wrap(~ Loc, ncol = 1, scales = "free_y")+ 
  theme_bw()+
  annotate(geom = "text", x = as.Date("2002-01-01"), y = 4, label = "Calibration")


回答1:


Try this trick:

library(ggplot2)
#Code
ggplot(DF, aes(x = Date))+
  geom_ribbon(aes(ymin = L95, ymax = U95), fill = "grey30", alpha = 0.4)+
  geom_line(aes(y = Ob, color = "blue"), size = 1 )+
  geom_line(aes(y = Sim, color = "black"), size =  1, linetype = "dashed")+
  geom_vline(xintercept = as.Date("2004-12-01"),color = "red", size = 1.30)+
  facet_wrap(~ Loc, ncol = 1, scales = "free_y")+ 
  theme_bw()+
  geom_text(data=data.frame(Date=as.Date("2002-01-01"),y=4,
                            label = "Calibration",Loc='Upstream'),
            aes(y=y,label=label))

Output:

You can also use Loc=unique(DF$Loc)[1] in the geom_text() side. It will produce same output.



来源:https://stackoverflow.com/questions/64970528/annotation-on-only-the-first-facet-of-ggplot-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!