r - 仅对 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")
解决方案
试试这个技巧:
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()
侧面使用。它将产生相同的输出。
推荐阅读
- elasticsearch - 使用模糊优化弹性搜索查询的时间
- javascript - 如何在 javascript 中获得独特的页面浏览量
- python-3.x - Watson Python SDK:“DetailedResponse”对象不可下标
- database - 如何在 Pymongo 的 id 范围内采样?
- r - 从 csv 文件导入数据并创建散点图
- xslt-2.0 - 从 XSLT 中的函数返回元素的值类型
- c - 我的十进制到二进制转换打印出额外的数字
- migration - 我在哪里可以下载 Salesforce 迁移工具的 Summer 18 版本?
- node.js - 坚持如何将数据推入嵌套数组
- javascript - 超过 2 个值的三元运算符替代方案