ggplot2 中的阴影区域在同一图表中具有多个时间序列

Shaded area in ggplot2 with multiple time series in the same graph

我只需要使用 ggplot2 在图表中插入一个带阴影的小区域,就像那样

但我遇到了以下问题...

# R Packages

library(dplyr)
library(ggplot2)
library(plotly)

我的数据集:

# Loading and visualizing data

multiple_time_series <- read.csv(file = "https://raw.githubusercontent.com/rhozon/datasets/master/timeseries_diff.csv", head = TRUE, sep = ";") %>%
  mutate(
    dates = as.Date(dates, format = "%d/%m/%y")
  ) %>% glimpse()

如您所见,数据集具有以下时间序列 v1、v2、v3、v4 和 v5。 然后我试着画...

shade <- data.frame(
  x1 = "2022-05-04",
  x2 = "2022-05-05",
  y1 = 50, # Min y range
  y2 = 102  # Max y range
)

ggplotly(
  ggplot()+
  geom_line(aes(x = dates), data = multiple_time_series ) +
    geom_line(aes(y = v1), color = "black")+
    geom_line(aes(y = v2), color = "red")+
    geom_line(aes(y = v3), color = "blue")+
    geom_line(aes(y = v4), color = "green")+
    geom_line(aes(y = v5), color = "yellow")+
   geom_rect(data = shade, 
            mapping = aes(
              xmin = as.Date(x1),
              xmax = as.Date(x2),
              ymin = y1,
              ymax = y2), color = "blue", alpha = 0.5) + xlab("") +
  theme(axis.title.y = element_text(size = 7, angle = 90)) +
  ggtitle("Real data vs forecasted values")
)

它 return 以下错误消息:

Error in FUN(X[[i]],...'v1' object didn´t found Calls <Anonimous>...<Anonimous> -> f -> scales_add_defaults -> lapply -> FUN
 

如何在具有多个时间序列的图表中添加阴影?

我认为你得到那个错误是因为你只提供了 data = multiple_time_series 给你的第一个线层。后续层无法访问该数据(因此无法访问列 'v1' 等),因为您可以作为 ggplot(data = ...) 提供的全局数据不存在。

如果将数据重塑为长格式而不是宽格式,则可以简化绘图代码。

此外,如果您只想在图中注释特定的矩形,则不需要构造额外的 data.frame:annotate() 函数适用于这些类型的情况。

library(dplyr)
library(ggplot2)

multiple_time_series <- read.csv(file = "https://raw.githubusercontent.com/rhozon/datasets/master/timeseries_diff.csv", head = TRUE, sep = ";") %>%
  mutate(
    dates = as.Date(dates, format = "%d/%m/%y")
  )

df <- tidyr::pivot_longer(multiple_time_series, -dates)

ggplot(df, aes(dates, value, colour = name)) +
  geom_line() +
  annotate(
    geom = "rect",
    xmin = as.Date("2022-05-04"),
    xmax = as.Date("2022-05-05"),
    ymin = -Inf, ymax = Inf,
    fill = "blue", alpha = 0.5
  )

reprex package (v2.0.1)

于 2022-05-07 创建