仅对 R 中 ggplot 的第一个方面进行注释? [英] Annotation on only the first facet of ggplot in R?

查看:33
本文介绍了仅对 R 中 ggplot 的第一个方面进行注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码生成一个 ggplot,它在两个 facet 上都有 text(即校准").我希望 text 只出现在第一个 facet 上.我尝试了几件事,但没有成功.任何帮助将不胜感激.

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

推荐答案

试试这个技巧:

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

输出:

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

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

这篇关于仅对 R 中 ggplot 的第一个方面进行注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆