我想在 x 轴上添加自定义刻度标签,例如此模式中的 1,2,3,4,3,2,1。但是我使用的代码并没有显示减少的数字。
var margin = {
top: 100,
right: 100,
bottom: 100,
left: 100
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.domain([1, 2, 3, 4, 5, 4, 3, 2, 1])
.rangePoints([0, width]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
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")
.call(xAxis);
如有任何帮助,我们将不胜感激。谢谢。
最佳答案
解决这个问题需要一些技巧。
原因
- d3.scale.ordinal(),纯数学逻辑中的域计算。每个 与范围关联的域。 ( f(x)=y ).
- 不允许重复,否则会产生歧义
解决方案
- 创建线性刻度,轴上的总项目为域 [0, itemLength]
- 在创建轴时使用 tickFormat 找出元素的索引
var margin = {
top: 100,
right: 100,
bottom: 100,
left: 100
},
width = 560 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var xdata = ["1", "2", "3", "4", "5", "4", "3", "2", "1", "0"];
var linear = d3.scale.linear()
.domain([0, 10])
.range([0, width]);
var xAxis = d3.svg.axis()
.scale(linear)
.orient("bottom");
var axis = d3.svg.axis()
.scale(linear)
.orient("top")
.ticks(10)
.tickFormat(function (d) {
return xdata[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")
.call(axis);
.axis path, line {
fill: none;
stroke: #000;
stroke-linecap: round;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
关于javascript - 如何在 d3.js 中添加自定义刻度标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47918368/