首页 > 解决方案 > 仅对 R 中 ggplot 的第一个方面进行注释?

问题描述

我有以下代码产生一个在两者上ggplot都有text(即“校准”)的代码facets。我只想text出现在第一个facet。我尝试了几件事,但没有成功。任何帮助,将不胜感激。

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

在此处输入图像描述

标签: rggplot2textannotationsfacet-wrap

解决方案


试试这个技巧:

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

输出:

在此处输入图像描述

您也可以Loc=unique(DF$Loc)[1]geom_text()侧面使用。它将产生相同的输出。


推荐阅读