dyShading R 动态图

dyShading R dygraph

我正在使用 dygraphs 包,我想使用 dyShading 函数添加多个阴影区域。我不想手动指定阴影区域,因为它是在函数的帮助下完成的:

dygraph(nhtemp, main = "New Haven Temperatures") %>% 
  dyShading(from = "1920-1-1", to = "1930-1-1") %>%
  dyShading(from = "1940-1-1", to = "1950-1-1")

而是在区域上循环。它看起来像那样(那不起作用!):

data %>% dygraph()  %>%
for( period in ok_periods ) dyShading(from = period$from , to = period$to )

你有什么想法吗?非常感谢

例如:

#create dygraph
dg <- dygraph(nhtemp, main = "New Haven Temperatures")

#add shades
for( period in ok_periods ) {
  dg <- dyShading(dg, from = period$from , to = period$to )
}

#show graph
dg

如果列表中有句点:

ok_periods <- list(
  list(from = "1920-1-1", to = "1930-1-1"),
  list(from = "1940-1-1", to = "1950-1-1"),
  list(from = "1960-1-1", to = "1970-1-1")
)

使用管道

如果你想使用管道,你可以定义一个新函数

add_shades <- function(x, periods, ...) {
  for( period in periods ) {
    x <- dyShading(x, from = period$from , to = period$to, ... )
  }
  x
}

并在链中使用它:

dygraph(nhtemp, main = "New Haven Temperatures") %>% 
  add_shades(ok_periods, color = "#FFFFCC" )