d3.js - 在D3js中,如何累积添加每个第n个绑定(bind)数据值?

标签 d3.js call modulo

我有这段代码,它输出一条由一堆线段组成的直线:

var width = 400;
var height = 100;
var data = [1,1,1,1,1,1,1,1,1,1];
var lineSegments = data.length + 1;

d3.select("body").append("svg")
        .attr({
            width: width,
            height: height
        })
    .selectAll("line")
    .data(data)
    .enter()
        .append("line")
            .attr({
                x1: function (d, i) { return i * (width / lineSegments); },
                x2: function (d, i) { return (i + 1) * (width / lineSegments); },
                y1: function (d, i) { return height / 2; },
                y2: function (d, i) { return height / 2; },
                stroke: "black",
                "stroke-width": 2
            });

我希望每个 3d 段在 y 方向上偏移,比如说 10px,并且我需要偏移量是累积的,即 3d 元素应该偏移 10px,第 6 个元素应该偏移 20px,等等。

这应该会产生这样的行:

enter image description here

我应该如何修改代码才能使其正常工作?有没有特殊的 d3 方法可以做到这一点?

最佳答案

您可以使用 d3 的 selection.each()以每个 3D 片段为目标。该方法有一些有用的变量来执行各种功能。

line.each(function(d, i) {
  console.log(i); // prints the current index
  console.log(d); // prints the data at the current index
  console.log(this); // prints the current DOM element
}

在您的具体情况下,i 变量对您很有用。您可以在 if 语句内部使用它来更改每个第三个元素的属性。您修改后的代码可能是...

var width = 400;
var height = 100;
var data = [1,1,1,1,1,1,1,1,1,1];
var lineSegments = data.length + 1;

var offset = 5;

d3.select("body").append("svg")
        .attr({
            width: width,
            height: height
        })
    .selectAll("line")
    .data(data)
    .enter()
        .append("line")
            .attr({
                x1: function (d, i) { return i * (width / lineSegments); },
                x2: function (d, i) { return (i + 1) * (width / lineSegments); },
                y1: function (d, i) { return height / 2; },
                y2: function (d, i) { return height / 2; },
                stroke: "black",
                "stroke-width": 2
            })
            .each(function(d,i) {
                if (i !== 0 && i % 3 === 0) {
                   d3.select(this).attr('transform', 'translate(0,' + offset + ')');
                   offset += 5;
                }
            })

Here is a working codepen.

关于d3.js - 在D3js中,如何累积添加每个第n个绑定(bind)数据值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32340326/

相关文章:

javascript - d3.js - 用线连接形状(不使用力或其他布局)

javascript - D3 SVG 图表中的现有元素未更新 - 全部被视为 exit() 和 Enter() 集

javascript - D3 和​​ Leaflet - svg 圆圈不显示

C++/错误“没有匹配的调用函数

python - 为什么 Python 在不应该返回 False 语句时返回?

kotlin - 如何为 Kotlin 中的每个数字类型实现 floor 模数?

javascript - D3js Force Layout barrier 和 fall in

java - 可以使用数组调用具有任意数量参数的方法吗?

javascript - 'call/apply' 和 'bind' 有什么区别

c - 带有 unsigned char 的 Mod 运算符