javascript - 附加组将d3强制布局中的所有内容弄乱了

标签 javascript d3.js d3-force-directed

我有一个d3 force sim,如果要添加节点,如下所示:

node = node.data(nodes, function(d) { return d.id;});
       node.exit().remove();
       node = node.enter().append('circle')
            .attr("class", function(d) {return d.type;})
            .attr("r", 25)
            .merge(node);

一切正常-将圆圈添加到正确的位置,渲染的html看起来像这样:
<svg width="1280" height="960">
    <g transform="translate(640,480)">
        <g stroke="#000" stroke-width="1.5">
            <line x1="197.7877989370864" y1="16.96383936157134" x2="113.39655998594978" y2="176.9054238213185"></line>
            <line x1="-99.71642802229279" y1="182.82652731678513" x2="-206.38001140055673" y2="35.62690731557146"></line>
            <line x1="-111.21899770908817" y1="-104.07607869492837" x2="9.724648489851102" y2="-238.28831674029004"></line>
            <line x1="-111.21899770908817" y1="-104.07607869492837" x2="73.66744043019104" y2="-114.11648500001087"></line>
            <line x1="197.7877989370864" y1="16.96383936157134" x2="10.328317030872993" y2="37.5171491536661"></line>
            <line x1="-99.71642802229279" y1="182.82652731678513" x2="10.328317030872993" y2="37.5171491536661"></line>
            <line x1="-111.21899770908817" y1="-104.07607869492837" x2="10.328317030872993" y2="37.5171491536661"></line>
            <line x1="197.7877989370864" y1="16.96383936157134" x2="73.66744043019104" y2="-114.11648500001087"></line>
        </g>
        <g prop="nodes" stroke="#000" stroke-width="1.5">
            <circle fill="some_image.png" class="Net" r="25" cx="197.7877989370864" cy="16.96383936157134"></circle>
            <circle fill="some_image.png" class="Net" r="25" cx="-99.71642802229279" cy="182.82652731678513"></circle>
            <circle fill="some_image.png" class="Net" r="25" cx="-111.21899770908817" cy="-104.07607869492837"></circle>
            <circle fill="some_image.png" class="Inst" r="25" cx="113.39655998594978" cy="176.9054238213185"></circle>
            <circle fill="some_image.png" class="Inst" r="25" cx="-206.38001140055673" cy="35.62690731557146"></circle>
            <circle fill="some_image.png" class="Inst" r="25" cx="9.724648489851102" cy="-238.28831674029004"></circle>
            <circle fill="some_image.png" class="Inst" r="25" cx="73.66744043019104" cy="-114.11648500001087"></circle>
            <circle fill="some_image.png" class="Internet" r="25" cx="10.328317030872993" cy="37.5171491536661"></circle>
        </g>
    </g>
</svg>

JSfiddle example

但是,如果我想添加组(我的最终设计需要背景图片,标签和各种其他内容),则如下所示:
node = node.data(nodes, function(d) { return d.id;});
       node.exit().remove();
       node.enter().append('g')
           .attr('class', 'node')
           .append('image')
           .attr('xlink:href', 'some_image.png')
           .append('text')
           .text(function(d){return d.text;})
           ... and so on...

尽管我的代码似乎可以正确解释(我将这些组附加,将图像和标签附加到它们),但是这些组保持静态,并且它们彼此之间保持在sim卡的中间。似乎坐标转换也转到图像而不是组,这就是我打破模拟的原因:
<svg width="1280" height="960">
    <g transform="translate(640,480)">
        <g stroke="#000" stroke-width="1.5">
            <line x1="197.77682810226557" y1="16.981901068622136" x2="113.3585440445384" y2="176.90457630748227"></line>
            <line x1="-99.99450481197604" y1="182.94091641902205" x2="-206.13047480355274" y2="35.36287517221039"></line>
            <line x1="-111.19343747422879" y1="-103.71666033252438" x2="9.543859895654657" y2="-238.10758089494877"></line>
            <line x1="-111.19343747422879" y1="-103.71666033252438" x2="73.69734375869983" y2="-114.13138675745854"></line>
            <line x1="197.77682810226557" y1="16.981901068622136" x2="10.344170477990337" y2="37.84621823186521"></line>
            <line x1="-99.99450481197604" y1="182.94091641902205" x2="10.344170477990337" y2="37.84621823186521"></line>
            <line x1="-111.19343747422879" y1="-103.71666033252438" x2="10.344170477990337" y2="37.84621823186521"></line>
            <line x1="197.77682810226557" y1="16.981901068622136" x2="73.69734375869983" y2="-114.13138675745854"></line>
        </g>
    <g prop="nodes" stroke="#000" stroke-width="1.5">
        <g class="node"><image xlink:href="some_image.png" x="0" y="0" height="72" width="72" style="z-index: 3;"></image></g>
        <g class="node"><image xlink:href="some_image.png" x="-7.373688780783198" y="6.754902942615239" height="72" width="72" style="z-index: 3;"></image></g>
        <g class="node"><image xlink:href="some_image.png" x="1.2363864559502138" y="-14.087985964343622" height="72" width="72" style="z-index: 3;"></image></g>
        <g class="node"><image xlink:href="some_image.png" x="10.538470205147267" y="13.745568221620495" height="72" width="72" style="z-index: 3;"></image></g>
        <g class="node"><image xlink:href="some_image.png" x="-19.694269706308575" y="-3.4836390075862327" height="72" width="72" style="z-index: 3;"></image></g>
        <g class="node"><image xlink:href="some_image.png" x="18.866941955758957" y="-12.001604111035421" height="72" width="72" style="z-index: 3;"></image></g>
        <g class="node"><image xlink:href="some_image.png" x="-6.358980820385529" y="23.65509169134563" height="72" width="72" style="z-index: 3;"></image></g>
        <g class="node"><image xlink:href="some_image.png" x="-12.194453649142762" y="-23.479678451778437" height="72" width="72" style="z-index: 3;"></image></g>
        </g>
    </g>
</svg>

JSfiddle example

我非常肯定团体的使用会弄乱一切,但无法正确使用它们。

感谢任何帮助。

这是摘要形式的完整布局:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Parse tester</title>
    <script src="https://d3js.org/d3.v4.min.js" type="text/javascript"></script>
</head>
<body>
<script>
    var nodes = [
    {id:0 , label:'branch1' , name:'branch1'},
    {id:1 , label:'branch2' , name:'branch2'},
    {id:2 , label:'branch3' , name:'branch3'},
    {id:3 , label:'leaf1' , name:'leaf1'},
    {id:4 , label:'leaf2' , name:'leaf2'},
    {id:5 , label:'leaf3' , name:'leaf3'},
    {id:6 , label:'center' , name:'center'},
    {id:7 , label:'leaf23' , name:'leaf23'}
    ];
    var links = [
    {source:0 ,target:3, distance:150, weight:1},
    {source:1 ,target:4, distance:150, weight:1},
    {source:2 ,target:5, distance:150, weight:1},
    {source:7 ,target:0, distance:150, weight:1},
    {source:7 ,target:1, distance:150, weight:1},
    {source:7 ,target:2, distance:150, weight:1},
    {source:1 ,target:6, distance:150, weight:1},
    {source:2 ,target:6, distance:150, weight:1}
    ];

    //D3 stuff
    var width=640, height = 480;

    // add a SVG to the body for our viz
    var svg=d3.select('body').append('svg')
        .attr('width', width)
        .attr('height', height);

    var simulation = d3.forceSimulation(nodes)
        .force("charge", d3.forceManyBody().strength(-1000))
        .force("link", d3.forceLink(links).distance(200))
        .force("x", d3.forceX())
        .force("y", d3.forceY())
        .alphaTarget(1)
        .on("tick", ticked);

    var g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"),
        link = g.append("g").attr("stroke", "#000").attr("stroke-width", 1.5).selectAll(".link"),
        node = g.append("g").attr("stroke", "#000").attr("stroke-width", 1.5).selectAll(".node");
    
    restart();
        function restart() {

            // Apply the general update pattern to the nodes.
            node = node.data(nodes, function(d) { return d.id;});
            node.exit().remove();
            node = node.enter()
            			.append('g')
            			.append('image')
                  .attr('xlink:href', 'http://i.imgur.com/Rx4N3wh.png')
                  .attr('width',25)
                  .attr('height',25)
                  .attr('x', function (d) {return d.x;})
                  .attr('y', function (d) {return d.y;})
                  .merge(node);
            
            node.enter().selectAll('g').append('text')
            .attr('text-anchor', 'middle')
            .attr('dy', '.35em')
            .attr('y', -40)
            .text(function (d) {
                return d.label
            });
            
            // Apply the general update pattern to the links.
            link = link.data(links, function(d) { return d.source.id + "-" + d.target.id; });
            link.exit().remove();
            link = link.enter().append("line").merge(link);

            // Update and restart the simulation.
            simulation.nodes(nodes);
            simulation.force("link").links(links);
            simulation.alpha(1).restart();
        }
//*/


    function ticked() {
        node.attr("cx", function(d) { return d.x; })
            .attr("cy", function(d) { return 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; });
    }

</script>

最佳答案

首先,我进行了第二个小提琴工作,在链接方法之间有一个额外的}和两个逗号:fiddle

因此,根据我的理解,在第一个小提琴中,一切工作都很好:链接和节点按照力的布局移动。在第二小节中,链接继续移动,但是现在带有图像的g的节点不移动内容。

据我了解,关键问题是“为什么g节点会破坏力的布局?”但是似乎还存在一些关于滴答函数和每个g节点中的嵌套元素的潜在问题。

强制刻度功能和更新模式

让我们看看您同时使用这两个函数:

function ticked() {
    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return 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; });
}

滴答函数称为每个滴答,它根据其基准更新每个节点。力模拟不会操纵视觉元素,而是操纵节点数据数组。初始化时,d3强制为数据数组中的每个节点创建新属性,例如代表速度和位置的那些属性。因此,d3正在更新您的数据,而不是元素。这就是为什么我们需要一个滴答功能。

现在,以上内容不是d3中的典型更新模式(但对于d3力而言是标准的)。典型的更新模式通常如下所示:
d3.selectAll(".node")
 .data(data)
 .attr("...")
 .attr("...")...

可以通过插入/退出/合并选择来拆分链

但是,对于对象(即数据数组中的节点),d3不会复制数据以将其绑定(bind)到每个元素,d3实际上将每个元素链接到数据数组中的项目。这意味着对于node.attr("cx", function(d) {d引用数据数组中链接/绑定(bind)的更新项,不需要selection.data()

我之所以提及这一点,是因为它是非典型的,在我看来并不为人所知,并且在示例或教程中也没有解释为什么部队使用(或可以使用)不同的更新模式。同样,考虑到您的评论“坐标由sim卡确定并不断动态地重新计算。这可能使我感到困惑”,这可能会引起困惑。

什么是node

选择node应该是g元素的选择,但实际上是选择了image元素:
node = node.enter()      
   .append('g')      // returns a selection of `g` elements
   .append('image')  // returns a selection of `image` elements.
   ...

您选择的元素不是g,但它们是子image元素。并且将它们与其他元素合并可能会引起问题。断开链接,将node保留为您的节点选择,在本例中为g元素。然后,我们可以轻松地将所需数量的子项附加到每个节点。

(为此,这是一个fiddle进行了更改,但是我们还没有解决为什么什么都没动的问题)。

是什么打断了滴答声?

正如我在评论中指出的那样,您已将节点从circle更改为g,并且您注意到节点最初已放置,但未更新。这是因为您需要更改刻度功能。您可以这样更新节点:
    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });  

但是,node现在是对g的选择,并且g不在cxcy属性的位置。让我们将其更改为:
node.attr("transform", function(d) { return "translate("+[d.x,d.y]+")"; })

这是一个更新的fiddle,其中节点随每个udpate移动。但是,现在需要固定位置。

定位

现在我们更新每个刻度的节点,并转换每个节点的g,使得[0,0]是该节点的中心。我看到的图像为25像素见方,因此要使图像居中,我们需要为每个图像(fiddle)的x和y位置使用负12.5。

我没有使用dx或dy来放置图像,就像在您的第二个小提琴中一样,因为通过放置g,我可以相对于该节点更轻松地放置所有内容,并且我只需要为每个刻度更新每个元素一个元素,即g 。否则,我必须在每个刻度上更新所有标签,图像等。

上面括号中的小提琴最初也不会放置节点-您可以执行此操作,但a)不放置它们会更容易,b)您必须非常鹰眼才能看到它们在第一个刻度之前放错了位置-但有些人非常鹰眼,因此将它们放置在输入中不会有任何危害(我在这里不为简洁起见)。

为什么标签不出现

到目前为止,我还没有留下标签代码,只是残留的代码块(起初我没有看到),但是现在我们可以仔细看一下:
      node.enter().selectAll('g').append('text')
        .attr('text-anchor', 'middle')
        .attr('dy', '.35em')
        .attr('y', -40)
        .text(function (d) {
            return d.label
        });
node.enter()返回需要输入的每个节点的占位符(与g父代使用的占位符相同。但是,这些占位符不包含任何g,因此node.enter().selectAll("g")将为空,因此文本将不会附加到任何元素。

我们希望每个节点都有文本,并且每个节点都在选择node中,因此我们只使用:
node.append("text")....

这是带有标签的updated fiddle

您可以通过这种方式将其他任何子节点附加到example上。

您无需为子代使用.data()或其他任何东西,因为d3将为每个子代提供与其父代相同的数据。

即使您在第二个小提琴中使用了node.append()node也代表了image的选择-并且您无法在图像上附加文本-因此看不到任何文本。

为了使答案更加自我,以下是最终结果的摘要:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Parse tester</title>
    <script src="https://d3js.org/d3.v4.min.js" type="text/javascript"></script>
</head>
<body>
<script>
    var nodes = [
    {id:0 , label:'branch1' , name:'branch1'},
    {id:1 , label:'branch2' , name:'branch2'},
    {id:2 , label:'branch3' , name:'branch3'},
    {id:3 , label:'leaf1' , name:'leaf1'},
    {id:4 , label:'leaf2' , name:'leaf2'},
    {id:5 , label:'leaf3' , name:'leaf3'},
    {id:6 , label:'center' , name:'center'},
    {id:7 , label:'leaf23' , name:'leaf23'}
    ];
    var links = [
    {source:0 ,target:3, distance:150, weight:1},
    {source:1 ,target:4, distance:150, weight:1},
    {source:2 ,target:5, distance:150, weight:1},
    {source:7 ,target:0, distance:150, weight:1},
    {source:7 ,target:1, distance:150, weight:1},
    {source:7 ,target:2, distance:150, weight:1},
    {source:1 ,target:6, distance:150, weight:1},
    {source:2 ,target:6, distance:150, weight:1}
    ];

    //D3 stuff
    var width=640, height = 480;

    // add a SVG to the body for our viz
    var svg=d3.select('body').append('svg')
        .attr('width', width)
        .attr('height', height);

    var simulation = d3.forceSimulation(nodes)
        .force("charge", d3.forceManyBody().strength(-1000))
        .force("link", d3.forceLink(links).distance(200))
        .force("x", d3.forceX())
        .force("y", d3.forceY())
        .alphaTarget(1)
        .on("tick", ticked);

    var g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"),
        link = g.append("g").attr("stroke", "#000").attr("stroke-width", 1.5).selectAll(".link"),
        node = g.append("g").attr("stroke", "#000").attr("stroke-width", 1.5).selectAll(".node");
    
    restart();
        function restart() {

            // Apply the general update pattern to the nodes.
            node = node.data(nodes, function(d) { return d.id;});
            node.exit().remove();
            node = node.enter()
            			.append('g')
                  .attr("class","node")
                  .merge(node)
                  
                  
            node.append('image')
                  .attr('xlink:href', 'http://i.imgur.com/Rx4N3wh.png')
                  .attr('width',25)
                  .attr('height',25)
                  .attr('x', -12.5)
                  .attr('y', -12.5)
                  
            
            node.append('text')
            .attr('text-anchor', 'middle')
            .attr('dy', '.35em')
            .attr('y', -40)
            .text(function (d) {
                return d.label
            });
            
            node.append("rect")
              .attr("x", -12.5)
              .attr("y", -12.5)
              .attr("width",25)
              .attr("height",25)
              .attr("stroke-width", 4)
              .attr("stroke","steelblue")
              .attr("fill","none")
            
            // Apply the general update pattern to the links.
            link = link.data(links, function(d) { return d.source.id + "-" + d.target.id; });
            link.exit().remove();
            link = link.enter().append("line").merge(link);

            // Update and restart the simulation.
            simulation.nodes(nodes);
            simulation.force("link").links(links);
            simulation.alpha(1).restart();
        }
//*/


    function ticked() {
        node.attr("transform", function(d) { return "translate("+[d.x,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; });
    }

</script>

关于javascript - 附加组将d3强制布局中的所有内容弄乱了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50899081/

相关文章:

javascript - 使用 svg 变换更新位置时,力模拟会出现抖动

javascript - 如何在力导向图中禁用动画?

javascript - 将已填写表单字段的 pdf 转换为图像

javascript - 在 nvd3 多条形图中为条形图绘制水平线

javascript - 如何使用 html/javascript/php 将 'Sign Up' 页面链接到 'Log In'

javascript - D3.js桑基图: Add title (text) above each column of nodes

javascript - 如何使用格式 SI 前缀四舍五入到小数点后两位?

javascript - d3.js 力定向图 : How to make node size depends on the value of the links?

javascript - 查看对象的隐藏属性

javascript - Safari 浏览器的网络摄像头支持