如何在Dygraphs中为R设置x轴以显示月份

时间:2015-03-07 13:24:57

标签: r dygraphs

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

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

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轴上显示月份而不是月份年份(例如“1月12日”)?而且,在情节的传说中,而不是显示月日年(例如2012年1月1日)以显示月日?

1 个答案:

答案 0 :(得分:8)

您可以修改所有轴标签并使用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))