javascript - D3 v3 Force Layout - 优雅地添加/删除节点而无需刷新

标签 javascript d3.js force-layout d3-force-directed

场景:

我从标准 D3 v3 强制布局开始 我从网上的一个例子中获取的。

我想增强这一点,我的目标是:

  1. 当脚本加载时,调用一个函数来初始化并使用一些数据渲染图形
  2. 点击按钮更新页面上的图表,以优雅添加/删除节点和链接 - 即无需完全重新绘制,节点“飞”入。

我想要的行为类型的一个例子是这个奇妙的图表,其中拖动阈值 slider “弹出”链接进/出,无需完全重新渲染,因此很容易看到添加/删除的内容: http://jsfiddle.net/simonraper/TdHgx/?utm_source=website&utm_medium=embed&utm_campaign=TdHgx

问题:

  • 我不确定如何实现上述第 2 点。
  • 我无法通过完全重绘来更新我的图表
  • 我无法确定答案与我如何使用 D3 常规更新模式有关。

这是我迄今为止所拥有的示例:https://jsfiddle.net/samollason/uvqosxrr/3/

jsfiddle 代码:


html:

<body>

  <button id="update-button1">Update Data - Remove</button>
  <button id="update-button2">Update Data - Add</button>

</body>

js:

var width = 400,
    height = 500;

var force = d3.layout.force()
    .size([width, height])
    .charge(-400)
    .linkDistance(40)
    .on("tick", tick);

var drag = force.drag()
    .on("dragstart", dragstart);

//Set up the force layout
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var link = svg.selectAll(".link"),
    node = svg.selectAll(".node");

    //we call this function when we first draw graph
    var drawInit = function(graph){

    link = link.data(graph.links, function(d) { return d.id; })
        .enter().append("line")
        .attr("class", "link");

    node = node.data(graph.nodes, function(d) { return d.id; })
        .enter().append("circle")
        .attr("class", "node")
        .attr("r", 12)
        .on("dblclick", dblclick)
        .call(drag);

    force
        .nodes(graph.nodes)
        .links(graph.links)
        .start();
};

    //call this function whenever we want to update the graph
var update = function(graph){

    link = link.data(graph.links, function(d) { return d.id; });

    link.exit().remove();

    link
        .enter().append("line")
        .attr("class", "link");

    node = node.data(graph.nodes, function(d) { return d.id; });

    //Remove nodes not in new data set
    node.exit().remove();

    //For each datum in dataset that wasn't in old dataset append 
      circle
    node.enter().append("circle")
        .attr("class", "node")
        .attr("r", 12)
        .on("dblclick", dblclick)
        .call(drag);

    //Update the force layout graph
    force
        .nodes(graph.nodes)
        .links(graph.links)
        .start();
};

function tick() {
    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; });

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

function dblclick(d) {
    console.log("double clicked on " + d.name);
    d3.select(this).classed("fixed", d.fixed = false);
}

function dragstart(d) {
    d3.select(this).classed("fixed", d.fixed = true);
}

//data1 is used for our initial drawing
data1 = {
    "nodes": [
    {
        "id":0,
        "name": 0,
        "group": 1,
        "size": 10
    },
    {
        "id":1,
        "name": 1,
        "group": 1,
        "size": 10
    },
    {
        "id":2,
        "name": 2,
        "group": 1,
        "size": 20
    },
    {
        "id":3,
        "name": 3,
        "group": 1,
        "size": 30
    },
    {
        "id":4,
        "name": 4,
        "group": 1,
        "size": 25
    }
],
    "links": [
    {
        "source": 1, "target": 0, "value":1, "id":0
    },
    {
        "source": 1, "target": 2, "value":1, "id":1
    },
    {
        "source": 1, "target": 3, "value":1, "id":2
    },
    {
        "source": 1, "target": 4, "value":1, "id":3
    }
]

};

drawInit(data1);

//When user clicks on button update force layout graph *gracefully*
d3.select("#update-button1").on("click", function(e) {

    var data2 = {
        "nodes": [
            {
                "id": 0,
                "name": 0,
                "group": 1,
                "size": 10
            },
            {
                "id": 1,
                "name": 1,
                "group": 1,
                "size": 10
            },
            {
                "id": 2,
                "name": 2,
                "group": 1,
                "size": 20
            },
            {
                "id": 3,
                "name": 3,
                "group": 1,
                "size": 30
            }
        ],
        "links": [
            {
                "source": 1, "target": 0, "value": 1, "id": 0
            },
            {
                "source": 1, "target": 2, "value": 1, "id": 1
            },
            {
                "source": 1, "target": 3, "value": 1, "id": 2
            }
        ]
    };

        update(data2);
});

//When user clicks on button update force layout graph *gracefully*
d3.select("#update-button2").on("click", function(e) {

    //this simulates removing a node
    var data3 = {
        "nodes": [
            {
                "id": 0,
                "name": 0,
                "group": 1,
                "size": 10
            },
            {
                "id": 1,
                "name": 1,
                "group": 1,
                "size": 10
            },
            {
                "id": 2,
                "name": 2,
                "group": 1,
                "size": 20
            },
            {
                "id": 3,
                "name": 3,
                "group": 1,
                "size": 30
            },
            {
                "id": 4,
                "name": 4,
                "group": 1,
                "size": 30
            },
            {
                "id": 5,
                "name": 5,
                "group": 1,
                "size": 30
            }
        ],
        "links": [
            {
                "source": 1, "target": 0, "value": 1, "id": 0
            },
            {
                "source": 1, "target": 2, "value": 1, "id": 1
            },
            {
                "source": 1, "target": 3, "value": 1, "id": 2
            },
            {
                "source": 1, "target": 4, "value": 1, "id": 3
            },
            {
                "source": 1, "target": 5, "value": 1, "id": 4
            }
        ]
    };

    update(data3);
});

最佳答案

我找到了问题的解决方案。本质上,为了实现“优雅”更新,必须改变最初分配给强制布局对象“节点”/“链接”属性的数据而不是重新分配和覆盖它们。

这是我创建的示例:https://jsfiddle.net/thedev19/z3rwpcxp/27/

人们仍然可以从添加/删除了一些节点/链接的外部源加载数据,然后新提供的数据与分配给力布局“节点”和“链接”的当前数据进行比较“属性”。然后适本地添加/删除节点/链接,以变异最初分配给其属性中的力布局图的“节点”/“链接”数据。

jsfiddle 代码:

<body>

<p>Click and drag nodes to 'stick' them to a desired location</p>
<p>Click button to see how we can 'gracefully' update the graph <br>
    and add data without completely re-loading</p>

  <button id="update1">Update - Click to add nodes</button>
</body>

js:

//Variables to set up SVG container
var width = 400,
    height = 350;

//We initialise the force layout object here
var force = d3.layout.force()
    .size([width, height])
    .charge(-400)
    .linkDistance(40)
    .on("tick", tick);

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

//Create a "g" container elements and create selections to reference throughout
var link = svg.append("g").selectAll(".link");
var node = svg.append("g").selectAll(".node");

var update = function(){

    //Create an UPDATE selection by joining data with "link" element selection
    link = link.data(graphData.links, function(d){ return d.id});

    //Access ENTER selection (hangs off UPDATE selection)
    //This represents newly added data that dont have DOM elements
    //so we create and add a "line" element for each of these data
    link
        .enter().append("line")
        .attr("class", "link");

    //Access EXIT selection (hangs off UPDATE selection)
    //This represents DOM elements for which there is now no corresponding data element
    //so we remove these from DOM
    link
        .exit().remove();

    //same update pattern for nodes
    node = node.data(graphData.nodes);

    node.
    enter().append("circle")
        .attr("class", "node")
        .attr("r", 12)
        .on("dblclick", dblclick)
        .call(drag);

    node.exit().remove();

    force
        .start();

};

function tick() {
    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; });

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

function dblclick(d) {
    d3.select(this).classed("fixed", d.fixed = false);
}

function dragstart(d) {
    d3.select(this).classed("fixed", d.fixed = true);
}

function init(){

    var data1 = {
        "nodes": [
            {
                "id":0,
                "name": 0,
                "group": 1,
                "size": 10
            },
            {
                "id":1,
                "name": 1,
                "group": 1,
                "size": 10
            },
            {
                "id":2,
                "name": 2,
                "group": 1,
                "size": 20
            },
            {
                "id":3,
                "name": 3,
                "group": 1,
                "size": 30
            }
        ],
        "links": [
            {
                "source": 0, "target": 1, "value":1, "id":0
            },
            {
                "source": 0, "target": 2, "value":1, "id":1
            },
            {
                "source": 0, "target": 3, "value":1, "id":2
            }
        ]

    };

    graphData = data1;
    drag = force.drag()
        .on("dragstart", dragstart);

    force.links(graphData.links);
    force.nodes(graphData.nodes);

    update()
}

init();

d3.select("#update1").on("click", function() {

    //randomly select a (currently existing) node that our new node will link to
    var sourceNodeId = Math.floor(Math.random() * (graphData.nodes.length-1));

    //if there are n nodes currently (before we add a new one, below) then
    //the new target node will be the (n+1)th node with an id of n (zero-indexing)
    var newNodeId = graphData.nodes.length;

    // if there are currently n links (before we add a new one, below) then
    // the new link will have an id of n (first link has an id of 0)
    var linkId = graphData.links.length;

    graphData.links.push({
        "source": sourceNodeId , "target": newNodeId, "value": 1, "id": linkId
    });

    graphData.nodes.push({
        "id": newNodeId,
        "name": newNodeId,
        "group": 1,
        "size": 30
    });

    update()

});

CSS:

.link {
    stroke: #000;
    stroke-width: 1.5px;
}

.node {
    cursor: move;
    fill: #ccc;
    stroke: #000;
    stroke-width: 1.5px;
}

.node.fixed {
    fill: #f00;
}

关于javascript - D3 v3 Force Layout - 优雅地添加/删除节点而无需刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46467114/

相关文章:

javascript - 如何在页面加载时向 Owl-item 添加类?

javascript - 如果 id 有破折号,如何访问本地 DOM 中的元素?

javascript - 如何在折线图中显示最新值

javascript - D3 Uncaught TypeError : path. 数据不是函数

javascript - 具有展开和折叠功能的强制定向图 (d3.js)

javascript - d3 强制布局,组为 "nodes"

javascript - 在 Meteor.JS Handlebars 中将对象转换为数组后无法拆分字符串

javascript - 将 data-* 属性转换为对象

d3.js - D3js 强制布局矩形文本组重叠

javascript - d3.js 中的图形方向和节点定位