如何在 R 的 dygraphs 中设置 x 轴以仅显示月份

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

我有以下时间序列(data.in。从 2012 年 1 月 1 日开始到 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

我正在使用 R 的 dygraph 进行绘图:

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))

是否可以在 x 轴上只显示月份而不显示月份年份(例如 "Jan 12")?而且,在情节的图例中而不是显示月日年(例如 2012 年 1 月 1 日)来显示月日?

您可以修改所有轴标签并使用 javascript 函数格式化值。

例如:

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))