Using R dygraphs for fractional timepoints?

260 views Asked by At

Is there a hack that exists in order to use the dygraphs package in R Shiny with fractional timepoints? I understand this pacakge is mainly for time-series data, but I think it would be extremely useful as a survival plot as well.

For example, say I have the following data:

samp.data <- data.frame(Months=seq(0,10,by=0.5), Surv=seq(1,0,length.out=21))

head(samp.data)

  Months Surv
1    0.0 1.00
2    0.5 0.95
3    1.0 0.90
4    1.5 0.85
5    2.0 0.80
6    2.5 0.75

I know I can do the following:

samp.xts <- xts(samp.data[,-1], order.by=as.Date(samp.data[,1]))
dygraph(samp.xts) 

But this gets rid of some information and the x-axis is a date instead of a value. I have been research the 'dygraphs' javascript library and there seems to be some functionality for non-time-series data as well, but I haven't found anything associated with the R package yet. Is there any javascript code I can call from the function?

Thanks for any help.

2

There are 2 answers

0
Mike.Gahan On BEST ANSWER

Alright, so after playing with it for a while, I think I have it figured out. You have to pass javascript functions to the valueFormatter and the axisLabelFormatter.

samp.data <- data.frame(Months=seq(0,10,by=0.5), Surv=seq(1,0,length.out=21))
samp.xts <- xts(samp.data[,-1], order.by=as.POSIXct(10*samp.data[,1],origin=as.Date("1970-01-01")))

And here is the graph:

dygraph( samp.xts ) %>%
  dyAxis(name="x",
         valueFormatter="function(d){ var date = new Date(d); return (date.getSeconds()/10) }",
         axisLabelFormatter="function(d){ return (d.getSeconds()/10) }"
  )

It is definitely a hack, but it gives me what I wanted to see. Note that valueFormatter returns a value, where axisLabelFormatter returns a date.

4
sdgfsdh On

I am going to assume that by "fractional timepoints" you mean intra-day data. dygraphs can be used with data indexed on POSIXct, which will allow you to place points within a day.

In your example you are converting the index to Date, which will strip off any times in the data.

Have you tried the following?

samp.xts <- xts(samp.data[,-1], order.by=as.POSIXct(samp.data[,1]))
dygraph(samp.xts) 

Note the as.POSIXct.