I am using the dygraphs
package and I would like to add multiple shaded regions using the dyShading
function. I would like not to have to specify manually the shaded region as it is done in the help of the 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")
But instead, make a loop on the regions. It would look like something like that (that does not work!):
data %>% dygraph() %>%
for( period in ok_periods ) dyShading(from = period$from , to = period$to )
Do you have any ideas? Thanks you very much
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 in a 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")
)
If you want to use pipe, you could 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" )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With