简体   繁体   English

D3 v4 - 获取轴上每个刻度的值?

[英]D3 v4 - Get the value of the each tick present on an axis?

Using D3.js version 4, is there a way to get an array of the values for each tick on an axis?使用 D3.js 版本 4,有没有办法获取轴上每个刻度的值数组?

Edit:编辑:

From D3 documentation来自 D3文档

# axis.tickValues([values]) <> #axis.tickValues([values]) <>

If a values array is specified, the specified values are used for ticks rather than using the scale's automatic tick generator.如果指定了 values 数组,则指定的值将用于刻度,而不是使用刻度的自动刻度生成器。 If values is null, clears any previously-set explicit tick values and reverts back to the scale's tick generator.如果 values 为空,则清除任何先前设置的显式刻度值并恢复到刻度的刻度生成器。 If values is not specified, returns the current tick values, which defaults to null.如果未指定值,则返回当前刻度值,默认为空。

I am using the automatic tick generator so if I call我正在使用自动滴答生成器,所以如果我打电话

var tickValues = axis.tickValues();

tickValues is null tickValues值为null

If you have a reference to the axis , you can use:如果您有对的引用,则可以使用:

axis.scale().ticks()

If you want them all formatted out, I'd get them from the DOM:如果你想让它们全部格式化,我会从 DOM 中获取它们:

d3.selectAll(".tick>text")
  .nodes()
  .map(function(t){
    return t.innerHTML;
  })

Running code:运行代码:

 <!DOCTYPE html> <meta charset="utf-8"> <svg width="960" height="500"></svg> <script src="//d3js.org/d3.v4.min.js"></script> <script> var svg = d3.select("svg"), margin = {top: 20, right: 0, bottom: 20, left: 0}, width = svg.attr("width") - margin.left - margin.right, height = svg.attr("height") - margin.top - margin.bottom, g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var x = d3.scalePoint() .domain([0, 1, 2]) .range([0, width]) .padding(1); var y = d3.scaleLinear() .domain([-1e6, 2e6]) .range([height, 0]); var axis = d3.axisLeft(y) .ticks(20, "s"); g.append("g") .attr("transform", "translate(" + x(0) + ",0)") .attr("class", "axis") .call(axis); console.log( axis.scale().ticks() ); console.log( d3.selectAll(".tick>text") .nodes() .map(function(t){ return t.innerHTML ; }) ); </script>

I found the answer of Mark above was not correct for my case, I changed a bit from his inspiration and it worked我发现上面马克的答案不适合我的情况,我从他的灵感中改变了一点,它奏效了

// I am using d3-scale
const yScale = scaleLinear().domain(realYDomain).range([30, 170]);
// I am using d3-axis
const yAxis = axisLeft(yScale); // Not declare axisLeft(scale).ticks(number) here, but below line instead
const tickValues = yAxis.scale().ticks(5);
console.log(tickValues);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM