D3 v4-获取轴上每个刻度的值? [英] D3 v4 - Get the value of the each tick present on an axis?

查看:141
本文介绍了D3 v4-获取轴上每个刻度的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用D3.js版本4,是否可以获取轴上每个刻度的值数组?

Using D3.js version 4, is there a way to get an array of the values for each tick on an axis?

来自D3 文档

#axis.tickValues([values])<>

如果指定了一个值数组,则指定的值将用于刻度线,而不是使用刻度的自动刻度线生成器.如果value为null,则清除任何先前设置的显式刻度值,并返回到刻度的刻度生成器.如果未指定values,则返回当前的刻度值,默认为null.

# 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. If values is null, clears any previously-set explicit tick values and reverts back to the scale’s tick generator. 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();

tickValuesnull

推荐答案

如果您引用了,您可以使用:

If you have a reference to the axis, you can use:

axis.scale().ticks()

如果您希望它们全部格式化,我将从DOM中获取它们:

If you want them all formatted out, I'd get them from the DOM:

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

运行代码:

<!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>

这篇关于D3 v4-获取轴上每个刻度的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆