我使用d3.js-v3
时间标度d3.time.scale()
绘制了x轴。
我的轴刻度线间距不相等。
我怎么有等间距的刻度线?
这是我的代码
var customTimeFormat = d3.time.format("%d %b");
var margin = {
top: 0,
right: 20,
bottom: 20,
left: 20
},
width = 550 - margin.left - margin.right,
height = 20 - margin.top - margin.bottom;
var x = d3.time.scale()
.domain([new Date("08/21/2019"), new Date("09/5/2019")])
.range([0, width]);
var xAxis = d3.svg.axis()
.scale(x)
.tickFormat(customTimeFormat);
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);
.axis text {
font: 10px sans-serif;
}
.axis line,
.axis path {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
答案 0 :(得分:0)
通过将其添加到轴定义中,您可以每隔2天获取一次滴答声
.ticks(d3.timeDay.filter(d => d3.timeDay.count(0,d)%2 === 0))
请参阅d3 v5.7.0的代码段
var customTimeFormat = d3.timeFormat("%d %b");
var margin = {
top: 0,
right: 20,
bottom: 20,
left: 20
},
width = 550 - margin.left - margin.right,
height = 20 - margin.top - margin.bottom;
var x = d3
.scaleTime()
.domain([new Date("08/20/2019"), new Date("09/7/2019")])
.range([0, width]);
var xAxis = d3
.axisBottom()
.scale(x)
.ticks(d3.timeDay.filter(d => d3.timeDay.count(0, d) % 2 === 0))
.tickFormat(customTimeFormat);
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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<html>
<body>
</body>
</html>
答案 1 :(得分:-1)
d3.time.scale
每两天创建一个刻度,但是在每月的第一天重置刻度,给人一种不必要的印象,即刻度不均匀。
可以通过使用ticks
函数来控制此行为,如下所示。
.ticks(d3.time.day, 1)
每天显示一格。
var customTimeFormat = d3.time.format("%d %b");
var margin = {
top: 0,
right: 20,
bottom: 20,
left: 20
},
width = 550 - margin.left - margin.right,
height = 20 - margin.top - margin.bottom;
var x = d3.time.scale()
.domain([new Date("08/20/2019"), new Date("09/05/2019")])
.range([0, width]);
var xAxis = d3.svg.axis()
.scale(x)
.tickFormat(customTimeFormat)
.ticks(d3.time.day, 1);
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);
.axis text {
font: 10px sans-serif;
}
.axis line,
.axis path {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
<script src="https://d3js.org/d3.v3.min.js"></script>