r - 仅对 R 中 ggplot 的第一个方面进行注释?

标签 r ggplot2 text annotations facet-wrap

我有以下代码可以生成 ggplottext (即“校准”)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")

enter image description here

最佳答案

试试这个技巧:

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

输出:

enter image description here

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

关于r - 仅对 R 中 ggplot 的第一个方面进行注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64970528/

相关文章:

xml - 从文档中提取唯一的 HTML 标签

r - 在 R gganimate 中做动画时如何保留以前的数据层?

r - 如何在 ggplot 之后使用 %T>% 管道?

R:将 geom_text() 放置在相对于图边界而不是图上的固定位置

c - 如何在c中写入文件的特定行?

Android TextView 和获取文本行

java - 在 Android 中同时共享文本和图像

r - 将带有 facet_grid 的 ggplot2 对象的标题移到中间

javascript - 在 R Shiny 中使用 Enter 键和操作按钮

r - PostGIS 和 R - 更快、更小地获取数据