我只需要使用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")
)
它回傳以下錯誤訊息:
Error in FUN(X[[i]],...'v1' object didn′t found Calls <Anonimous>...<Anonimous> -> f -> scales_add_defaults -> lapply -> FUN
如何在具有多個時間序列的圖表中添加陰影?
uj5u.com熱心網友回復:
我認為您會收到該錯誤,因為您只提供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 包創建于 2022-05-07 (v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/471565.html