How to set x-axis in dygraphs for R to show just m

2019-03-22 12:12发布

问题:

I have the following time series (data.in. that starts on 2012-01-01 and ends 2012-12-31):

       ts.rmean ts.rmax
2012-01-01 3.163478    5.86
2012-01-02 3.095909    4.67
2012-01-03 3.112000    6.01
2012-01-04 2.922800    5.44
2012-01-05 2.981154    5.21
2012-01-06 3.089167    5.26

and I am using dygraph for R for plotting:

library(dplyr)
library(digraphs)
dygraph(data.in, main = "Title") %>%
  dySeries("ts.rmean", drawPoints = TRUE, color = "blue") %>%
  dySeries("ts.rmax", stepPlot = TRUE, fillGraph = TRUE, color = "red") %>%
  dyHighlight(highlightSeriesOpts = list(strokeWidth = 3))

It is possible to show on the x-axis just the month and not Month Year (e.g. "Jan 12")? And also, in the legend of the plot instead of showing Month Day Year (e.g. Jan 01 2012) to show Month Day?

回答1:

You can modify all the axis labels and format the values using javascript functions.

For example:

library(dygraphs)
library(xts)
library(htmlwidgets)

#the axis label is passed as a date, this function outputs only the month of the date
getMonth <- 'function(d){
               var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
               return monthNames[d.getMonth()];
               }'

#the x values are passed as milliseconds, turn them into a date and extract month and day
getMonthDay <- 'function(d) {
                var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
                date = new Date(d);
                return monthNames[date.getMonth()] + " " +date.getUTCDate(); }'

#set the value formatter function and axis label formatter using the functions above
#they are wrapped in JS() to mark them as javascript    
dygraph(data.in, main = "Title") %>%
        dySeries("ts.rmean", drawPoints = TRUE, color = "blue") %>%
        dySeries("ts.rmax", stepPlot = TRUE, fillGraph = TRUE, color = "red") %>%
        dyHighlight(highlightSeriesOpts = list(strokeWidth = 3)) %>%
        dyAxis("x",valueFormatter=JS(getMonthDay), axisLabelFormatter=JS(getMonth))


标签: r dygraphs