Reputation: 269
I'm using dygraphs and would like to change the x axis granularity from daily to yearly. I have a few daily data points all in the format c("2009-01-01", "2010-01-01", "2011-01-01"), and the x axis ticks appears at Jan 2009, June 2009, Jan 2010, June 2010 I want the x axis to only appear as "2009, 2010, 2011" corresponding to data points that actually exist..
I have the following code:
dygraph(hhinfl) %>% dyLegend(width=400, show="auto") %>% dyOptions(drawPoints=TRUE, pointSize=3) %>% dySeries("Household Inflation", color="#0174DF") %>% dySeries("date", color="#FFFFFF")%>% dySeries("Average Inflation", color="#DF0101") %>% dyAxis("y", label="Inflation Rate (%)") %>% dyAxis("x", drawGrid = FALSE, axisLabelFormatter="function(d) { return d.getFullYear() }")
which returns the YEAR of each date on the x-axis, but that means there are multiple years like "Jan 2009, June 2009, Jan 2010, June 2010" becomes "2009, 2009, 2010, 2010"
Alternatively, another code shows:
dygraph(hhinfl) %>% dyLegend(width=400, show="auto") %>% dyOptions(drawPoints=TRUE, pointSize=3) %>% dySeries("Household Inflation", color="#0174DF") %>% dySeries("date", color="#FFFFFF")%>% dySeries("Average Inflation", color="#DF0101") %>% dyAxis("y", label="Inflation Rate (%)") %>% dyAxis("x", drawGrid = FALSE, ticker= " function (a, b, pixels, opts, dygraph, vals) {return Dygraph.getDateAxis(a, b, Dygraph.YEARLY, opts, dygraph);}", axisLabelFormatter="function(d) { return d.getFullYear() }")
Does not return any graph at all, except for the y-axis.
How may I resolve this issue?
hhinfl is an xts file constructed as follows:
dateseq<- seq(from=as.Date("2010-01-01"),to=as.Date("2013-12-31"),by="year")
household<- c(2.3, 2.4, 2.5, 3.1)
avg<- c(2.5, 2.6, 2.7, 3.1)
hhinfl<- data.frame(date=dateseq, hh=household, average=avg)
colnames(hhinfl)<- c("date", "Household Inflation", "Average Inflation")
hhinfl<-xts(hhinfl, order.by=hhinfl$date)
Upvotes: 3
Views: 1525
Reputation: 1069
So close! Before I noticed your "Alternatively, another code shows:" above, I wrote code essentially identical to yours (cribbing from http://jsfiddle.net/kaliatech/P8ehg/) and got the same blanked-out chart.
Then I stumbled into https://github.com/danvk/dygraphs/blob/master/src/dygraph-tickers.js#L221 and saw that the parameter should be ANNUAL
, not YEARLY
.
So here's what turns out well for me:
dygraph(hhinfl) %>%
dyLegend(width=400, show="auto") %>%
dyOptions(drawPoints=TRUE, pointSize=3) %>%
dySeries("Household Inflation", color="#0174DF") %>%
dySeries("date", color="#FFFFFF") %>%
dySeries("Average Inflation", color="#DF0101") %>%
dyAxis("y", label="Inflation Rate (%)") %>%
dyAxis("x", drawGrid = FALSE) %>%
dyAxis("x", axisLabelFormatter="function(d) { return d.getFullYear() }") %>%
dyAxis("x", ticker="function(a, b, pixels, opts, dygraph, vals) {
return Dygraph.getDateAxis(a, b, Dygraph.ANNUAL, opts, dygraph)
// or TWO_HOURLY or SIX_HOURLY...
}")
Upvotes: 4