在multiforce布局中对d3.js中的节点进行分组

时间:2016-03-11 08:20:31

标签: javascript d3.js svg

您好我正在尝试将在下面的代码中生成为浮动图像的节点分组。对于分组我使用的数组arrInt []有很多值(0,1,2)。根据arrInt值,所有0,1和2应该在一起。我无法在刻度函数

上执行此操作
var fill = d3.scale.category10();

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);


d3.csv("data/Images.csv", function(error, data) {

    data.forEach(function(d) {

        arrFileUrl.push(d['FingerImageName']);
        arrBrightness.push(d['Brightness']);
        arrPattern.push(d['Pattern']);
        arrSize.push(d['Size']);

    });


    var boolBrig = arrBrightness.contains(brightness);
    var boolSize = arrSize.contains(pixel);

    if(boolBrig === true && boolSize === true){

        data.forEach(function(d){
            if(d['Brightness'] === brightness && d['Size'] === pixel && pattSelect.contains(d['Pattern'])){
                arrMatchFile.push(d['FingerImageName']);
            }

        }); 
    }


    for(j=0;j<arrPattern.length;j++){
        if(arrPattern[j] === "Arches"){
            arrInt[j] = 0;
        }
        if(arrPattern[j] === "Whorls"){
            arrInt[j] = 1;
        }
        if(arrPattern[j] === "Loops"){
            arrInt[j] = 2;  
        }
    }


    var nodes = d3.range(arrFileUrl.length).map(function(i) {
      return {index: arrInt[i]};
    });

    console.log(nodes);

    var force = d3.layout.force()
    .nodes(nodes)
    .gravity(0.02)
    //.charge(-1700)
    //.friction(0.5)
    .size([width, height])
    .on("tick", tick)
    .start();

    var node = svg.selectAll(".node")
    .data(nodes)
    .enter().append("image")
    .attr("xlink:href", function (d,i) {
                return arrFileUrl[i];
    })
    .attr("class", "node")
    .attr("width", 120)
    .attr("height", 160)
    .style("stroke", "black")
    .call(force.drag)
    .style("opacity", function(d,i){
        if(arrMatchFile.contains(arrFileUrl[i])) {
            return 5;
        } else {
            return 0.2;
        }           
    })
    .on("mousedown", function() { d3.event.stopPropagation(); });



    svg.transition()
    .duration(1000);

    d3.select("body")
    .on("mousedown", mousedown);


    function tick(e) {

      // Push different nodes in different directions for clustering.
      var k = 6 * e.alpha;
      nodes.forEach(function(o, i) {
        o.y += i & 1 ? k : -k;
        o.x += i & 2 ? k : -k;

      });

      node.attr("x", function(d) { return d.x; })
          .attr("y", function(d) { return d.y; }); 
    }


    function mousedown() {
      nodes.forEach(function(o, i) {
        o.x += (Math.random() - .5) * 40;
        o.y += (Math.random() - .5) * 40;
      });
      force.resume();
    }


});

1 个答案:

答案 0 :(得分:1)

 nodes.forEach(function(o, i) {
    o.y += i & 1 ? k : -k;
    o.x += i & 2 ? k : -k;

  });

您正在使用索引i进行群集...这不会起作用,您想要使用arrInt[i]代替:

 nodes.forEach(function(o, i) {
    o.y += arrInt[i] & 1 ? k : -k;
    o.x += arrInt[i] & 2 ? k : -k;
  });