首页 > 解决方案 > 使用 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 有什么建议吗?

谢谢!

标签: rggplot2

解决方案


推荐阅读