首页 文章

R Dygraphs从每月到每年的X轴粒度

提问于
浏览
1

我正在使用dygraphs,并希望将x轴粒度从每日更改为每年 . 我有几个每日数据点,格式为c(“2009-01-01”,“2010-01-01”,“2011-01-01”),x轴刻度出现在2009年1月,2009年6月,2010年1月,2010年6月我希望x轴只显示为“2009,2010,2011”,对应于实际存在的数据点 .

我有以下代码:

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() }")

它返回x轴上每个日期的年份,但这意味着有多年如“2009年1月,2009年6月,2010年1月,2010年6月”成为“2009年,2009年,2010年,2010年”

或者,另一个代码显示:

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() }")

除了y轴之外,根本不返回任何图形 .

我该如何解决这个问题?

hhinfl是一个xts文件,构造如下:

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)

1 回答

  • 1

    很近!在我注意到你上面的"Alternatively, another code shows:"之前,我编写的代码基本上与你的相同(来自http://jsfiddle.net/kaliatech/P8ehg/),并得到了相同的消隐图表 .

    然后我偶然发现https://github.com/danvk/dygraphs/blob/master/src/dygraph-tickers.js#L221,看到参数应该是 ANNUAL ,而不是 YEARLY .

    所以这对我来说非常好:

    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...
                            }")
    

相关问题