Conditionally shade regions of dygraph time series when NA

Viewed 93

I'd like to add background shading where values in a time series are NA, without needing to specify the date range. The basic shading option in dygraphs works like this:

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

I would like to add background shading for ~50 regions of a time series that are missing, and so it wouldn't be feasible to do it manually. As a simple example, how could I tell dygraphs to add background shading for the missing values in this time series without specifying the date range?

nhtemp2 <- nhtemp
nhtemp2[10:20] <- NA
dygraph(nhtemp2, main = "New Haven Temperatures")
1 Answers

A possible solution :

library(dygraphs)

nhtemp2 <- nhtemp
nhtemp2[10:20] <- NA
nhtemp2[30:45] <- NA

# Convert years to DyShading date format
dates <- sprintf('%d-1-1',time(nhtemp2))

# find NA intervals
start = dates[which(diff(is.na(nhtemp2))==1)]
stop = dates[which(diff(is.na(nhtemp2))==-1)+1] 


g <- dygraph(nhtemp2, main = "New Haven Temperatures")

# Loop over NA intervals to add shading
for (i in 1:length(start)) {
  g <- dygraphs::dyShading(
    g,
    from  = start[i],
    to    = stop[i],
    color = 'lightgrey')
}
g

enter image description here

Please note that this only works if the time serie doesn't start with NA, but could be improved to cope with this.

Related