javascript - 如何从 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 值,即1900、1950、 2000。我想知道每行从哪里开始,以便为每列添加一个图例。
感谢您的帮助。
解决方案
在 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>
推荐阅读
- apache-spark - 在 mapPartitions 中使用滑动,但结果在驱动程序中执行
- php - 设置漂亮的设计模式 php
- php - WooCommerce 购物车折扣:根据商品数量免费赠送一件商品
- c++ - 这个循环是如何工作的(检查数组循环中的重复)
- java - 如何更改键盘语言 - Java
- f# - 使用静态解析的类型参数链接中缀运算符
- bash - 自动化“git merge”提交消息
- angular - Angular 在隔离中使用 ngModel 设置错误
- kubernetes - 从 pod 内部访问 kubernetes 命名空间(值)
- php - 如何使 Symfony 序列化组在 php 中工作?