首页 > 解决方案 > 如何从 x 轴获取刻度的 X 值?

问题描述

您好,我正在尝试理解这个示例另一个示例,以将网格线添加到堆叠区域。

tiksArray = [1900, 1950, 2000, 2010];
keys = ["Amanda", "Ashley", "Betty", "Deborah"];

// Add X axis
const dX = d3.extent(nbrOfBabies, d => d.year);
const x = d3.scaleLinear()
  .domain(dX)
  .range([0, this.width]);

svg.append("g")
  .attr("class", "grid")
  .attr("transform", `translate(0,${this.height})`)
  .call(this.make_x_gridlines(x)
    .tickSize(-this.height)
    .tickFormat(null)
  );

// gridlines in x axis function
make_x_gridlines(x) {
 const bttm = d3.axisBottom(x)
    .tickValues(this.tiksArray);
 return bttm;
}

我得到这张图。我想知道这些刻度的 X 值,即19001950、 2000。我想知道每行从哪里开始,以便为每列添加一个图例。

在此处输入图像描述

感谢您的帮助。

标签: javascriptd3.jssvg

解决方案


在 D3 中,轴生成器使用传递的刻度来定位刻度。因此,您需要做的就是将您的这些值传递tiksArray到相同的比例(在您的情况下,x)。

这是一个非常基本的演示:

const ticksArray = [1900, 1950, 2000, 2010];
const svg = d3.select("svg")
const x = d3.scaleLinear()
  .domain([1880, 2020])
  .range([50, 450]);

svg.append("g")
  .attr("transform", `translate(0,${100})`)
  .call(d3.axisBottom(x)
    .tickValues(ticksArray)
    .tickSizeInner(-100)
  );

ticksArray.forEach(d => {
  console.log("The SVG position of the tick " + d + " is: " + x(d))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="500" height="200"></svg>


推荐阅读