Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dygraph legend time-date format change to include day of week

Tags:

r

shiny

dygraphs

Hello I am using the R dygraphs package, and would like to be able to change the legend time-date format to include the day of the week (i.e. "%a")

I have looked in dyOptions and dyLegend but cannot see anything that would help me with this...

Below is a simple example...but would ideally like it to be in shiny app...

library(dygraphs)
library(xts)
dygraph(xts(rnorm(100),Sys.time()+seq(100)),main='random_graph')

To give a bit of additional detail...I would like the a format like: "Wed 22 Jan 2020 08:35:05" for both the axis and the legend.

like image 502
h.l.m Avatar asked Jul 12 '16 13:07

h.l.m


1 Answers

It is possible. You need to supply the axisLabelFormatter parameter of dygraphs::dyAxis with a Javascript function that takes a date argument and returns a string based on that date. The function is just passed in as a string.

I'm not sure you can access any of the javascript libraries that dygraph imports, so to keep it simple I have included a vanilla javascript snippet that gives the date in the format I assume you wanted. It can easily be expanded or modified using the javascript functions getYear() getFullYear() getHours() getMinutes() and getSeconds()

library(dygraphs)
library(xts)

my_js <- 'function(d)
          {
            var d = new Date(d.getTime() + 7200*1000);
            var weekday = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
            var months  = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
                           "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
            var result = ""
            result += weekday[d.getDay()] + " " + d.getDate()
            result += " " + months[d.getMonth()] + " " + d.getFullYear();
            return result;
          }'

set.seed(69)
dg <- dygraph(xts(rnorm(100), Sys.time() + seq(100)*10000), main = 'random_graph')
dyAxis(dg, name = "x", axisLabelFormatter = my_js)

enter image description here

like image 110
Allan Cameron Avatar answered Nov 15 '22 11:11

Allan Cameron