我使用dygraphs
包来绘制每周数据的图表。 dygraphs
会自动选择每周默认轴。但是,我希望有一种方法可以让默认轴(星期日)与我的数据(星期一)对齐。
# Required packages
library("magrittr")
library("dygraphs")
library("xts")
# Data
daily <- structure(c(4000, 5000, 3000, 7000, 2000, 5000, 7000,
2000, 3000, 6000, 5000, 9000, 2000, 2000, 2000,
7000, 9000, 2000, 1000, 13000), .Dim = c(10L, 2L), .Dimnames = list(
NULL, c("col1", "col2")), index = structure(c(1476032400,
1476637200, 1477242000, 1477846800, 1478451600, 1479056400, 1479661200,
1480266000, 1480870800, 1481475600), tzone = "Asia/Saigon", tclass = c("POSIXct",
"POSIXt")), class = c("xts", "zoo"), .indexCLASS = c("POSIXct",
"POSIXt"), tclass = c("POSIXct", "POSIXt"), .indexTZ = "Asia/Saigon", tzone = "Asia/Saigon")
# Graph
dygraph(daily, main = "Stackoverflow") %>%
dyRangeSelector() %>%
dyOptions(useDataTimezone = TRUE)
答案 0 :(得分:1)
您可以尝试使用自定义ticker
功能,该功能从数据的第一天开始,每隔七天打一次。
这是一个受dygraph-tickers.js
Dygraph.getDateAxis
函数启发的示例:
dygraph(daily, main = "Stackoverflow") %>%
dyRangeSelector() %>%
dyAxis("x",ticker='function(start_time, end_time, pixels, opts, dygraph, vals) {
var formatter = opts("axisLabelFormatter");
var ticks = [];
var t;
//spacing is a week in milliseconds
var spacing = 1000 * 604800;
for (t = start_time; t <= end_time; t += spacing) {
ticks.push({ v:t,
label: formatter(new Date(t), Dygraph.WEEKLY, opts, dygraph)
});
}
return ticks;
}') %>%
dyOptions(useDataTimezone = TRUE)
答案 1 :(得分:1)
解决方法是通过JavaScript函数重新格式化dyAxis
标签值(当然,考虑到您唯一需要的是更改默认的一周中的第一天)。
看看:
# libs and daily object ...
# the x values are passed as milliseconds, turn them into a date and extract day and month
getMonthDay <- 'function(d) {
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var date;
if (typeof d == "number") { // value
date = new Date(d);
} else { // label
date = new Date(d.toString().substring(0, 15));
}
date.setDate(date.getDate() + 1);
return date.getUTCDate() + " " + monthNames[date.getMonth()];
}'
# Graph
dygraph(daily, main = "Stackoverflow") %>%
dyRangeSelector() %>%
dyAxis(
"x",
valueFormatter = JS(getMonthDay),
axisLabelFormatter = JS(getMonthDay),
rangePad = 40 # the rangePad would adapt by itself
) %>%
dyOptions(useDataTimezone = TRUE)
请注意,我们有条件检查type
对象的d
。那是因为
valueFormatter
- 返回valueOf
the date对象; axisLabelFormatter
- 返回实际的date
本身因此,如果d
参数为:
number
( valueFormatter ),我们只是创建一个新的Date
对象; object
( axisLabelFormatter ) - 是的,它将参数作为Object
发送;所以,我们需要将其转换为适当的Date
。需要substring()
方法,因为dygraphs会像这样发送对象:
Sun Oct 09 2016 00:00:00 GMT+0700
...而且,由于00的时间,一旦你尝试转换为日期,JavaScript将返回
Sat Oct 08 2016 14:00:00 GMT-0300 (Local Standard Time)
这样,我们将始终只考虑日,月和年。此外,您已正确应用rangePad
: