DyShading R dygraph
I am using a package dygraphs
and I would like to add some shaded areas using a function dyShading
. I would not like to manually specify the shaded area, as is done with a function:
dygraph(nhtemp, main = "New Haven Temperatures") %>%
dyShading(from = "1920-1-1", to = "1930-1-1") %>%
dyShading(from = "1940-1-1", to = "1950-1-1")
Cycle through the regions instead. It will look something like this (it doesn't work!):
data %>% dygraph() %>%
for( period in ok_periods ) dyShading(from = period$from , to = period$to )
Do you have any ideas? thank you very much
+3
source to share
1 answer
For example:
#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
If you have periods on the list:
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")
)
Pipe use
If you want to use a channel, you can define a new function
add_shades <- function(x, periods, ...) {
for( period in periods ) {
x <- dyShading(x, from = period$from , to = period$to, ... )
}
x
}
and use it in a chain:
dygraph(nhtemp, main = "New Haven Temperatures") %>%
add_shades(ok_periods, color = "#FFFFCC" )
+8
source to share