Search code examples
rdygraphs

x.axis date and real date does not match in dygraph


here is a plot of mine using dygraph in R:

http://rpubs.com/victordongy/332717

Apparently, the x.axis does not match with the real date of each point, the dataset e_n is as following:

             ratio_en ratio_con_en ch_oil_manu_p ch_mineral_p ch_oil_gas_p
1929-12-31 0.03622237   0.04397706            NA           NA           NA
1930-12-31 0.04227732   0.04880694           NaN          NaN          NaN
1931-12-31 0.04754198   0.05297158           NaN          NaN          NaN
1932-12-31 0.05634319   0.06386555           NaN          NaN          NaN
1933-12-31 0.05670123   0.06643357           NaN          NaN          NaN
1934-12-31 0.05018593   0.06137725           NaN          NaN          NaN 

And the R code of mine is :

dygraph(merge(e_n$ratio_en,e_n$ratio_con_en), main = "Ratio of Energy Investment over GDP") %>% 
    dyAxis("x",valueRange = c(1929:2016)) %>%
    dyAxis("y", label = "Ratio")

The problem is that, as the date time is set to end with 12-31, so I figure the dygraph recognize each date as the nearest date of the next year, which would make the date time of each point to be the first day of the next year.

As what I have shown in my code, I have tried to use valueRange of c(1929,2016) or c("1929-12-31","2016-12-31") to at least show the exact year of the point, but nothing changed still.

Any idea would be helpful.


Solution

  • Your dygraph works properly. You have the impression that it's got the wrong year, but it's just plotting the last day of the year. If you zoom, you'll see that the points are a tiny bit on the left.

    If you want your points to be drawn at the beginning of the year, you need to convert your index accordingly.

    So if we call data_xts your time series.

    data_xts <- e_n[,c("ratio_en","ratio_con_en")]
    
    index(data_xts) <- as.Date(paste(format(index(test),"%Y"),"01/01",sep="/"))
    

    For example, we converted 1929-12-31 to 1929-01-01