D3力导向布局与边界框

37

我是D3的新手,正在尝试设置我的力导向布局边界。我已经从示例中拼凑出了我想要的东西,但我需要图形被包含在内。在tick函数中,使用transform/translate可以正确地显示我的图形,但当我使用Math.max/min和cx和cy时(请参见注释代码),节点固定在左上角,而线条正确地被包含。

下面是我的代码,请问我做错了什么?

var w=960, h=500, r=8,  z = d3.scale.category20();

var color = d3.scale.category20();

var force = d3.layout.force()
       .linkDistance( function(d) { return (d.value*180) } )
       .linkStrength( function(d) { return (1/(1+d.value)) } )
       .charge(-1000)
       //.gravity(.08)
       .size([w, h]);

var vis = d3.select("#chart").append("svg:svg")
       .attr("width", w)
       .attr("height", h)
       .append("svg:g")
       .attr("transform", "translate(" + w / 4 + "," + h / 3 + ")");

vis.append("svg:rect")
   .attr("width", w)
   .attr("height", h)
   .style("stroke", "#000");


d3.json("miserables.json", function(json) {

       var link = vis.selectAll("line.link")
               .data(json.links);

       link.enter().append("svg:line")
               .attr("class", "link")
               .attr("x1", function(d) { return d.source.x; })
               .attr("y1", function(d) { return d.source.y; })
               .attr("x2", function(d) { return d.source.x; })
               .attr("y2", function(d) { return d.source.y; })
               .style("stroke-width", function(d) { return (1/(1+d.value))*5 });

       var node = vis.selectAll("g.node")
               .data(json.nodes);

       var nodeEnter = node.enter().append("svg:g")
               .attr("class", "node")
               .on("mouseover", fade(.1))
               .on("mouseout", fade(1))
               .call(force.drag);

       nodeEnter.append("svg:circle")
               .attr("r", r)
               .style("fill", function(d) { return z(d.group); })
               .style("stroke", function(d) { return
d3.rgb(z(d.group)).darker(); });

       nodeEnter.append("svg:text")
               .attr("text-anchor", "middle")
               .attr("dy", ".35em")
               .text(function(d) { return d.name; });

       force
       .nodes(json.nodes)
       .links(json.links)
       .on("tick", tick)
       .start();

       function tick() {

       // This works
               node.attr("transform", function(d) { return "translate(" + d.x + ","
+ d.y + ")"; });

       // This contains the lines within the boundary, but the nodes are
stuck in the top left corner
               //node.attr("cx", function(d) { return d.x = Math.max(r, Math.min(w
- r, d.x)); })
               //      .attr("cy", function(d) { return d.y = Math.max(r, Math.min(h -
r, d.y)); });

       link.attr("x1", function(d) { return d.source.x; })
               .attr("y1", function(d) { return d.source.y; })
               .attr("x2", function(d) { return d.target.x; })
               .attr("y2", function(d) { return d.target.y; });
       }

       var linkedByIndex = {};

   json.links.forEach(function(d) {
       linkedByIndex[d.source.index + "," + d.target.index] = 1;
   });

       function isConnected(a, b) {
       return linkedByIndex[a.index + "," + b.index] ||
linkedByIndex[b.index + "," + a.index] || a.index == b.index;
   }

       function fade(opacity) {
       return function(d) {
           node.style("stroke-opacity", function(o) {
                       thisOpacity = isConnected(d, o) ? 1 : opacity;
                       this.setAttribute('fill-opacity', thisOpacity);
               return thisOpacity;
                       });

                       link.style("stroke-opacity", opacity).style("stroke-opacity",
function(o) {
               return o.source === d || o.target === d ? 1 : opacity;
               });
       };
       }

});

我已经尝试了一些参数,并决定除非有更好的解决方案,否则我将只使用大量的.gravity()。如果图形非常大,则仍可能存在问题,但除此之外应该可以很好地包含节点。 - Michael Wilson
3个回答

68

我在讲述力学布局中有一个边界框示例。位置Verlet积分允许您在“tick”事件侦听器内定义几何约束(例如边界框和碰撞检测); 只需移动节点以符合约束条件,模拟将相应地适应。

话虽如此,重力显然是处理此问题的更灵活的方式,因为它允许用户暂时将图形拖出边界框,然后图形将恢复。根据图形的大小和显示区域的大小,您应该尝试使用不同的引力和电荷(排斥力)相对强度来使您的图形适合。


20
关键在于添加以下代码:node.attr("cx", function(d) { return d.x = Math.max(r, Math.min(width - r, d.x)); }) .attr("cy", function(d) { return d.y = Math.max(r, Math.min(height - r, d.y)); });如果你使用path而不是line,你还需要为attr('d', function () {...});添加边界检查。 - Limin
@mbostock,有没有办法提供边界的坐标(仅在定义的四个角落内移动)? - Rishi0405
1
女士们先生们,这就是为什么我们不仅仅发布链接,而是提供实际的答案:近10年来,其中三个链接中有两个已经失效了。 - Basti

6

自定义力也是一种可能的解决方案。我更喜欢这种方法,因为不仅重新定位了显示的节点,而且整个模拟都使用了边界力。

let simulation = d3.forceSimulation(nodes)
    ...
    .force("bounds", boxingForce);

// Custom force to put all nodes in a box
function boxingForce() {
    const radius = 500;

    for (let node of nodes) {
        // Of the positions exceed the box, set them to the boundary position.
        // You may want to include your nodes width to not overlap with the box.
        node.x = Math.max(-radius, Math.min(radius, node.x));
        node.y = Math.max(-radius, Math.min(radius, node.y));
    }
}

我非常喜欢这个功能,因为它可以与手动模拟中的tick(N)一起使用,快速计算静态力导向布局(当你使用.on('tick')监听器时是不可能的)。 - undefined

2

注释代码适用于 Node,它是一个 SVG 的 g(分组)元素,并且不操作 cx/cy 属性。选择节点内的圆形元素以使这些属性生效:

node.select("circle") // select the circle element in that node
    .attr("cx", function(d) { return d.x = Math.max(r, Math.min(w - r, d.x)); })
    .attr("cy", function(d) { return d.y = Math.max(r, Math.min(h - r, d.y)); });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接