简体   繁体   English

节点数据更新d3.js v4力图

[英]Node data update d3.js v4 force diagram

Say we have a force diagram of 4 interlinked nodes (how they linked dont matter for this situation): 假设我们有一个4个相互链接的节点的力图(在这种情况下,它们如何链接并不重要):

{name: A, age: 15}
{name: B, age: 5}
{name: C, age: 4}
{name: D, age: 66}

Now I receive two nodes: 现在,我收到两个节点:

{name: E, age: 12}
{name: A, age: 7}

I am going to update the graph which is now going to have 5 nodes in total, but I also would like to update the age of matching nodes. 我将更新该图,该图现在总共将有5个节点,但我也想更新匹配节点的年龄。 So the end result (age) of node A would be 22. 因此,节点A的最终结果(寿命)为22。

The procedure I'm following is: 我要遵循的过程是:

node = svg             
        .selectAll(".node")
        .data(nodes, function (d) { return d.name; });

var nodeEnter = node
                        .enter()
                        .append("g")
                        .attr("class", "node");

                    nodeEnter
                        .append("circle")        
                        .attr("r", 5);

So somewhere in here Id like to sum the age property. 因此,我想在这里某处总结年龄属性。 Any ideas anyone ? 有任何想法吗?

Previously with D3, (before v4) you were not able to compare a node's old and new data values during the update step without storing the data as a javascript property of the DOM object for the element, similar to how data is stored in D3's data property. 在D3之前(在v4之前),您无法在更新步骤中比较节点的旧数据值和新数据值,而没有将数据存储为该元素的DOM对象的javascript属性,类似于在D3的数据中存储数据的方式属性。

This process of storing local variables has been made part of the library in v4 with the d3.local() method. 使用d3.local()方法,此存储局部变量的过程已成为v4中库的一部分

The way it works is you declare a local data variable a la var persistedData = d3.local(); 它的工作方式是您声明一个本地数据变量var persistedData = d3.local();

and then, call persistedData.set(this, d.age); 然后,调用persistedData.set(this, d.age); for each node and call persistedData.get(this) to retrieve that previous age data where you are appending the age data to the dom for presentation. 对于每个节点,并调用persistedData.get(this)以检索先前的年龄数据,在该年龄数据中,您要将年龄数据附加到dom上进行显示。

nodeEnter
  .append("text")
  .attr("dx", 12)
  .attr("dy", "2em")
  .text(function(d) {
   var oldAge = persistedData.get(this);
   return oldAge ? oldAge + d.age : d.age;
});

I believe what you need to implement is the General Update Pattern read more here . 我相信您需要实现的是“通用更新模式”, 更多信息请点击此处 And you'll need to use key functions on your .data() method. 而且,您需要在.data()方法上使用关键功能。 Mike has an example here . 迈克在这里有一个例子。 It shouldn't be too hard, let me know if you have some problems. 这应该不太困难,如果您有任何问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM