r - 使用 facet_zoom 放大时间序列图
问题描述
我正在尝试使用 facet_zoom 来“放大”到特定的年份 - 1985-86。分别为 1997-98、2010-11 和 2015-16。代码如下:
library(ggplot2)
library(dplyr)
library(lubridate)
library(tidyr)
library(tidyverse)
theme_set(theme_bw(base_size=14))
sst <- read.csv("FINALSST.csv", fileEncoding="UTF-8-BOM")
regions <- unique(sst$Region)
sst <- sst %>% mutate(Time=as.Date(Time, format="%d/%m/%Y"),
Region=factor(Region, levels=regions))
sst2 <- sst %>% mutate(Time=floor_date(Time, unit="month")) %>%
group_by(Time, Region, Variable) %>%
summarise(Value=mean(Value, na.rm=TRUE), .groups="drop")
ggplot(sst2, aes(Time, Value, col=Variable)) +
geom_line() +
facet_wrap(~Region, ncol=1) +
theme(legend.position="top")
# Now add el nino years
en_s <- as.Date(c("01/01/1997", "01/01/2015"), format="%d/%m/%Y")
en_e <- as.Date(c("31/12/1998", "31/12/2016"), format="%d/%m/%Y")
ln_s <- as.Date(c("01/01/1985", "01/01/2010"), format="%d/%m/%Y")
ln_e <- as.Date(c("31/12/1986", "31/12/2011"), format="%d/%m/%Y")
elnino <- data.frame(start=en_s, end=en_e, Time=en_s, Value=Inf, event="El Nino")
lanina <- data.frame(start=ln_s, end=ln_e, Time=en_s, Value=Inf, event="Non-El Nino")
library(ggforce)
ggplot(sst2, aes(Time, Value, col=Variable)) +
geom_rect(data=elnino, aes(xmin=start, xmax=end, ymin=Inf, ymax=-Inf),
col=NA, fill="lightpink") +
geom_rect(data=lanina, aes(xmin=start, xmax=end, ymin=Inf, ymax=-Inf),
col=NA, fill="lightblue") +
geom_line() +
facet_wrap(~Region, ncol=1) +
theme(legend.position="top") +
labs(title = "Monthly average SSTs from 1985 to 2017")
我将 facet_zoom 添加到最后一行,但它会产生错误“下标越界”。我试图实现的第一个“放大”是 01/01/1997 到 31/12/1998。我尝试了各种方法,但仍然会产生错误。在时间序列图上使用 facet_zoom 有什么建议吗?
谢谢!
解决方案
推荐阅读
- reactjs - 尽管直接在该组件中获取状态,但 Redux 状态并未传递给嵌套路由器组件
- r - Heroku 和 R 构建错误:“'LC_MESSAGES' 未声明”
- javascript - 以编程方式将 PDF 初始视图窗口选项设置为显示文档标题(而不是文件名)
- python - 使用格式将 CSV 文件复制到 XLSX
- python - 如何从 JSON 创建 Stripe 对象?
- swift - 如何从具有不同字体的文本视图中复制文本,并且当粘贴到其他应用程序(如消息)上时,它是相同的字体?
- c - apue代码第四章umask.c运行异常
- tfs - SSIS 项目不会显示添加的新文件夹
- continuous-integration - TeamCity 上的并行赛普拉斯测试
- c# - 如何在控制台应用程序中使用 Windows Burn-API