我是 d3.js 的新手。现在我有一个问题,如何在开始位置和结束位置添加刻度。
那么如何在第一次报价时加 1,在最后报价时加 99?我想不通。
<!DOCTYPE html>
<html lang="en">
<body>
<div id="d3">
</div>
<script src="https://d3js.org/d3.v4.js"></script>
<script>
let margin = {top: 40, right: 80, bottom: 40, left: 80 },
width = 600 - margin.right - margin.left,
height = 360 - margin.top - margin.bottom;
let svg = d3.select('#d3')
.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 + ")");
let xScale = d3.scaleLinear()
.domain([1, 99])
.range([0, width]);
let xAxisGenerator = d3.axisBottom(xScale);
let xAxis = svg.append('g')
.call(xAxisGenerator);
</script>
</body>
</html>
最佳答案
首先,您可以使用 d3.ticks()
获取默认报价,其形式为:
d3.ticks(start,stop,number)
一个轴的默认刻度数是 10,我们可以使用它。然后插入域中的最小值和最大值作为起始值和终止值,然后在数组中获取默认刻度值。现在我们可以将您域中的最小值和最大值添加到此数组中,可能类似于:
let ticks = [...xScale.domain(),...d3.ticks(...xScale.domain(),10)]
我使用扩展运算符 (...
) 意味着这将不兼容 IE,但返工并不难
然后我们将这些刻度传递给轴:
let xAxisGenerator = d3.axisBottom(xScale)
.tickValues(ticks);
现在我们有了原始刻度加上 1 和 99 的刻度。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="d3">
</div>
<script src="https://d3js.org/d3.v4.js"></script>
<script>
let margin = {top: 40, right: 80, bottom: 40, left: 80 },
width = 600 - margin.right - margin.left,
height = 360 - margin.top - margin.bottom;
let svg = d3.select('#d3')
.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 + ")");
let xScale = d3.scaleLinear()
.domain([1, 99])
.range([0, width]);
let ticks = [...xScale.domain(),...d3.ticks(...xScale.domain(),10)]
let xAxisGenerator = d3.axisBottom(xScale)
.tickValues(ticks);
let xAxis = svg.append('g')
.call(xAxisGenerator);
</script>
</body>
</html>
关于javascript - d3.js 轴添加刻度值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65756874/