使用d3.js,我发现当使用x轴的时间刻度时,主要的刻度标记会在新月边界上搞乱。它似乎在新月上创建一个新的刻度线,即使这会导致刻度太接近前一个刻度。这不仅会扰乱沿轴的均匀间距,还会使刻度标签重叠并且看起来很丑陋。
请参阅问题底部的演示以显示我的意思(向右滚动以查看问题区域)。
我是否需要a custom multi-scale time format来处理此案件?或者我在这里缺少一些选择? (这被认为是一个错误吗?)
编辑:我尝试了自定义多时间格式,它确实可以将额外的标签从“六月”更改为与其他标签相匹配,但它仍然显示在不应该的位置。问题是那里根本不应该有刻度线;它应该在始终存在的刻度之间保持相同的2天间距,而事实并非如此。我倾向于称这是一个错误。这是一个发生这种情况的演示:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 12px Arial;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path, .axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
</style>
<body>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.2.2/d3.v3.min.js"></script>
<script type="text/javascript">
var data = {
"values" : [40, 80, 94, 95, 10, 81, 89, 70, 43, 56, 86, 72, 39, 38, 84, 5, 0, 38, 68, 16, 23, 6, 45, 7, 79, 59, 51, 33, 44, 18],
"labels" : ["2013,05,07", "2013,05,08", "2013,05,09", "2013,05,10", "2013,05,11", "2013,05,12", "2013,05,13", "2013,05,14", "2013,05,15", "2013,05,16", "2013,05,17", "2013,05,18", "2013,05,19", "2013,05,20", "2013,05,21", "2013,05,22", "2013,05,23", "2013,05,24", "2013,05,25", "2013,05,26", "2013,05,27", "2013,05,28", "2013,05,29", "2013,05,30", "2013,05,31", "2013,06,01", "2013,06,02", "2013,06,03", "2013,06,04", "2013,06,05"]
};
var margin = { top : 15, right : 15, bottom : 40, left : 50 },
width = 750 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom;
// Parse dates
data.parsedDates = [];
data.labels.forEach(function(d) {
var parsed = d3.time.format("%Y,%m,%d").parse(d);
data.parsedDates.push(parsed);
});
var x = d3.time.scale()
.range([0, width])
.domain(d3.extent(data.parsedDates));
var y = d3.scale.linear()
.range([height, 0])
.domain(d3.extent(data.values));
var xAxis = d3.svg.axis().scale(x)
.ticks(8).tickSize(5, 0, 0);
var line = d3.svg.line()
.x(function(d,i) {
return x(data.parsedDates[i]); })
.y(function(d,i) {
return y(d); });
// Create chart
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 + ")");
// Graph points
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", function(d) { return line(d.values) });
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
</script>
</body>
答案 0 :(得分:0)
似乎对于当前的D3版本(答案日期为5.12.0),手动选择日期是唯一可行的解决方案(提及here的PS解决方案):
const xValues = data.filter((d, i) => i % interval === 0).map(d => d.date);
const xAxis = d3.axisBottom(x)
.tickFormat(d3.timeFormat('%b %d'))
// .ticks(d3.timeDay.every(interval))
.tickValues(xValues);