gpt4 book ai didi

javascript - 如何从 x 轴获取刻度的 X 值?

转载 作者:行者123 更新时间:2023-11-29 22:44:46 25 4
gpt4 key购买 nike

你好,我正在尝试了解 this examplethis other example将网格线添加到堆叠区域。

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。我想知道每行从哪里开始,以便添加图例对于每一列。

enter image description here

感谢您的帮助。

最佳答案

在 D3 中,轴生成器使用传递的 scale 来定位刻度。因此,您需要做的就是将 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>

关于javascript - 如何从 x 轴获取刻度的 X 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58966211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com