【问题标题】:How to highlight time series in some date ranges in R如何在 R 中突出显示某些日期范围内的时间序列
【发布时间】: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


    【解决方案1】:

    在最终使用图和 xblocks 的注释中使用可重现的 xts 对象。要指定不同的颜色,请使用 adjustcolor("blue", 0.2) 代替 grey(...)。对于许多其他方法,谷歌 R 阴影衰退

    library(xts)
    
    plot(as.zoo(aapl))
    xblocks(aapl, ifelse(time(aapl) %in% time(aapl[period]), grey(.2, .2), NA))
    

    注意

    library(quantmod)
    getSymbols("AAPL")
    period <- "2020-01/2020-03"
    aapl <- Cl(AAPL)
    

    【讨论】:

    • 谢谢@G。格洛腾迪克!但是,我尝试使用这个period &lt;- "2020-01/2020-03" plot(as.zoo(df_xts)) xblocks(df_xts, ifelse(time(df_xts) %in% time(df_xts[period]), grey(.2, .2), NA)),但它不能突出显示日期范围。
    • 问题是关于在 single 面板中根据时间绘制 one 列,但您正试图在 two 中绘制多面板图从而引入了问题。 (1)选择要绘制的列,例如df_xts[, 1] 或 (2) 通过将 screen = 1 作为参数添加到绘图命令来告诉它在同一面板中绘制两者。
    • 怎么样:period &lt;- "2020-01/2020-03" plot(as.zoo(df_xts$prices_usa)) xblocks(df_xts$prices_usa, ifelse(time(df_xts) %in% time(df_xts[period]), grey(.2, .2), NA))
    • 我通过使用 ggplot2 包使用了这个命令:library(ggplot2) library(plotly) ggplotly( ggplot() + geom_rect(data = df, aes(xmin = as.numeric(as.Date(c("2019-02-01"))), xmax = as.numeric(as.Date(c("2019-02-05"))), ymin = 300, ymax = 800), alpha = 0.15) + geom_line(data = df, aes(dates, prices_usa)) + ggtitle('timeseries with weekends highlighted') ) 但图中的日期看起来是错误的......有人知道如何解决它吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2014-02-18
    • 2019-06-23
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多