在D3中,可以使用band.bandwidth()
返回两个波段之间的宽度。
对于给定的域,如果您已经在轴上设置了刻度,那么d3是否与这个等价呢?
因此,如果您的tickValues域是[-2,-1,0,1,2]
,scaleLinear.tickWidth()
将为您提供scaleLinear(0)
和scaleLinear(1)
(或scaleLinear(-2)
和scaleLinear(-1)
)之间的区别,或者您设置的滴答之间的差异。
发布于 2019-01-04 01:20:25
如你所知,没有这样的方法。而且,对于线性尺度来说,带宽(不携带任何信息)的概念也没有什么意义。
但有趣的是,您的问题不是关于线性标度本身,而是关于--使用该标度生成的轴(正如您所说的"...provided在轴上设置了刻度“)。
在D3中,当我们使用刻度时生成的轴是非常不可预测的(即蜱数及其值),特别是在使用时间尺度时。此外,您还可以使用axis.ticks()
或axis.tickArguments()
更改滴答。因此,使用scale.ticks()
获取滴答值并不是一种准确的方法。
尽管如此,您可以使用传递轴组本身的函数( SVG <g>
元素),就像我刚才写的这个函数:
function tickWidth(selection) {
const ticks = selection.selectAll(".tick text")
.nodes()
.map(function(d) {
return +d.textContent;
});
return scale(ticks[1]) - scale(ticks[0]);
}
它所做的基本上是获取.ticks
组中的所有.ticks
元素,将它们转换为数字(它们是字符串),并返回比例上的差异。
下面是一个演示:
const svg = d3.select("svg");
const scale = d3.scaleLinear()
.range([50, 450])
.domain([0, 100]);
const axis = d3.axisBottom(scale);
const axisGroup = svg.append("g")
.attr("transform", "translate(0,50)")
.call(axis);
const bandwidth = tickWidth(axisGroup);
console.log("the bandwidth is: " + bandwidth + " pixels")
function tickWidth(selection) {
const ticks = selection.selectAll(".tick text").nodes().map(function(d) {
return +d.textContent;
});
return scale(ticks[1]) - scale(ticks[0]);
}
<svg width="500" height="100"></svg>
<script src="https://d3js.org/d3.v5.min.js"></script>
正如您所看到的,这种方法考虑到了像axis.ticks()
这样的方法,这些方法修改了滴答:
const svg = d3.select("svg");
const scale = d3.scaleLinear()
.range([50, 450])
.domain([0, 100]);
const axis = d3.axisBottom(scale)
.ticks(5);
const axisGroup = svg.append("g")
.attr("transform", "translate(0,50)")
.call(axis);
const bandwidth = tickWidth(axisGroup);
console.log("the bandwidth is: " + bandwidth + " pixels")
function tickWidth(selection) {
const ticks = selection.selectAll(".tick text").nodes().map(function(d) {
return +d.textContent;
});
return scale(ticks[1]) - scale(ticks[0]);
}
<svg width="500" height="100"></svg>
<script src="https://d3js.org/d3.v5.min.js"></script>
https://stackoverflow.com/questions/54026482
复制相似问题