Search code examples
rdygraphs

R dygraph skip missing value for multiple graph display


I meet one issue in plotting multiple line with dgraph,

I have one dataframe as below, it contain time, channel and SNR value, I want to display SNR value for each channel, and I expect the dygraph display 8 Line(it have 8 channel)in dataset.

 head(gateSNR_df)
                 time channel  SNR
1 2015-09-03 02:40:44       6 -125
2 2015-09-03 02:40:49       3  -95
3 2015-09-03 02:40:54       0   22
4 2015-09-03 02:40:59       0   28
5 2015-09-03 02:41:04       5 -125
6 2015-09-03 02:41:09       2  -52
........
.........

So I use reshape2:dcast to do the reshape

gateSNR_c <- dcast(gateSNR_df, time~channel, value.var="SNR")
head(gateSNR_c)
                 time  0  1   2   3  4    5    6  7
1 2015-09-03 02:40:44 NA NA  NA  NA NA   NA -125 NA
2 2015-09-03 02:40:49 NA NA  NA -95 NA   NA   NA NA
3 2015-09-03 02:40:54 22 NA  NA  NA NA   NA   NA NA
4 2015-09-03 02:40:59 28 NA  NA  NA NA   NA   NA NA
5 2015-09-03 02:41:04 NA NA  NA  NA NA -125   NA NA
6 2015-09-03 02:41:09 NA NA -52  NA NA   NA   NA NA

I then change to XTS object for dygraph display

> gateSNR_xts <- xts(gateSNR_c[,-1], as.POSIXct(gateSNR_c[,1]))
> 
> 
> head(gateSNR_xts)
                     0  1   2   3  4    5    6  7
2015-09-03 02:40:44 NA NA  NA  NA NA   NA -125 NA
2015-09-03 02:40:49 NA NA  NA -95 NA   NA   NA NA
2015-09-03 02:40:54 22 NA  NA  NA NA   NA   NA NA
2015-09-03 02:40:59 28 NA  NA  NA NA   NA   NA NA
2015-09-03 02:41:04 NA NA  NA  NA NA -125   NA NA
2015-09-03 02:41:09 NA NA -52  NA NA   NA   NA NA
> 

Somehow, dygraph(gateSNR_xts) not working properly due to the NA value, I can't just omit NA because it might losing the entire entry.

Q1: Is there anyway for R to plot each line and skipping the NA value? Q2: If not, I can generate 8 xts instead. how can I display the 8 xts line in one dygraph?

Thanks for your help James


Solution

  • You need to use dygraphs::dyOptions and set option connectSeparatedPoints to TRUE.

    Example

    set.seed(123)
    library(dygraphs)
    mdeaths[sample(seq_along(mdeaths), 20)] <- NA
    ldeaths[sample(seq_along(ldeaths), 20)] <- NA
    lungDeaths <- cbind(ldeaths, mdeaths)
    
    dygraph(lungDeaths) %>% 
      dyOptions(connectSeparatedPoints = TRUE)
    

    More information: dygraphs official documentation http://dygraphs.com/options.html#connectSeparatedPoints