我正在使用d3,在我的图表中,我的刻度是UTC格式的时间刻度。
xScale = d3.time.scale.utc().range([0, chartWidth]);
我需要动态指定刻度线,并动态更改域,以避免刻度线标签混乱。
我正在基于域计算滴答声,并将滴答声设置为最接近的5的倍数。但是,我注意到一个问题,即有时在更改域时滴答声位置不一致。见下图:
在某个论坛上浏览时,我看到可以通过功能
tickValues(d3.range(starting value, end value, interval))
设置刻度值。 See this post by mbostock。现在我不确定-如何在我的时间范围内做同样的事情?
如果我想为自己的xAxis(在UTC中使用时间标度)计算自己的刻度值,该怎么办?
谢谢。
最佳答案
您要每N分钟强制滴答答答吗?或N [时间单位]?
您可以使用:
var startDate = new Date(2016, 0, 1, 2, 0, 0),
endDate = new Date(2016, 0, 1, 4, 0, 0),
millisecondsBetweenTicks = 300000; //<-- 5 minutes
var x = d3.time.scale.utc()
.domain([startDate, endDate])
.range([0, width]);
var xAxis = d3.svg.axis()
.scale(x)
.tickValues(d3.range(startDate, endDate, millisecondsBetweenTicks )
.map(function(d){ return new Date(d) }) //<-- remap to dates
);
完整示例:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.axis text {
font: 10px sans-serif;
}
.axis line,
.axis path {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 250, right: 40, bottom: 250, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
startDate = new Date(2016, 0, 1, 2, 0, 0),
endDate = new Date(2016, 0, 1, 4, 0, 0);
var x = d3.time.scale.utc()
.domain([startDate, endDate])
.range([0, width]);
var xAxis = d3.svg.axis()
.scale(x)
.tickValues(d3.range(startDate, endDate, 300000)
.map(function(d){ return new Date(d) })
);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.attr("y", 0)
.attr("x", 9)
.attr("dy", ".35em")
.attr("transform", "rotate(90)")
.style("text-anchor", "start");
</script>