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

我与影子孤独终老i 提交于 2019-12-09 06:56:46

问题


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


来源:https://stackoverflow.com/questions/28915328/how-to-set-x-axis-in-dygraphs-for-r-to-show-just-month

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!