dyShading R dygraph

时间:2015-06-12 14:03:51

标签: r dygraphs

我正在使用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 )

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

1 个答案:

答案 0 :(得分:9)

例如:

#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" )