【发布时间】:2021-12-31 21:17:25
【问题描述】:
我需要在我的时间序列图表中突出显示一些日期范围,但我不能继续。
使用的数据集如下:
library(dplyr)
library(xts)
library(zoo)
df <- read.csv("https://github.com/rhozon/datasets/raw/master/dataset_1a.csv", header = TRUE, sep =",") %>%
mutate(
dates = as.Date(dates)
) %>%
filter(
dates >= "2019-01-01"
) %>%
glimpse()
df_xts <- xts(df[,-1, drop = FALSE], order.by = df[,1]) %>% as.xts()
class(df_xts)
head(df_xts)
然后我尝试了以下PerfomanceAnalytics 命令:
library(PerformanceAnalytics)
# Create period to hold the 3 months of 2020
period <- c("2020-01/2020-03")
# Highlight the first three months of 2020
chart.TimeSeries(df$prices_usa, period.areas = period, period.color = "lightgrey")
没有成功...
Error in try.xts(x, error = "'x' needs to be timeBased or xtsible") :
'x' needs to be timeBased or xtsible
通过使用dygraphs 包...
library(dygraphs)
dygraph( df$prices_usa ) %>%
dyShading(from = "2020-06-30", to = "2020-09-01") %>%
dyAnnotation("2020-08-01", text = "X", tooltip = "date range") %>%
dyAxis("x", drawGrid = TRUE) %>%
dyEvent("2020-06-30", "Jul 2020", labelLoc = "bottom") %>%
dyEvent("2020-09-01", "Sep 2020", labelLoc = "bottom") %>%
dyOptions(drawPoints = FALSE, pointSize = 2) #%>%
我又发现了另一个问题:
Error in dygraph(df$prices_usa) : Unsupported type passed to argument 'data'.
我没有尝试使用 ggplot2 包,因为我需要将它与交互性一起使用。
有人可以向我推荐一个解决这些问题的方法或者更简单的方法(即使使用 ggplot2+plotly),这对我在我的时间序列图中划分或突出某些日期/期间范围很有用?
【问题讨论】:
标签: r ggplot2 time-series highlight dygraphs