gpt4 book ai didi

d3.js - d3js : make new parent data descend into child nodes

转载 作者:行者123 更新时间:2023-12-03 10:57:46 25 4
gpt4 key购买 nike

我不知道如何最好地将发生在父节点(例如 SVG g 元素)上的数据更改传递给它的子节点(例如 SVG circle 元素)。

我已阅读 thisthis但还是想不通。

这是一个最小的工作示例。该示例假设您有一个名为 svg 的对象。它指的是包含 SVG 元素的 d3 选择。

data = [{"id":"A","name":"jim"},{"id":"B","name":"dave"},{"id":"C","name":"pete"}];

g = svg.selectAll("g").data(data, function(d) { return d.id; }).enter().append("g");

g.append("circle")
.attr("r", 3)
.attr("cx", 100)
.attr("cy", function(d,i) {return 100 + (i * 30);})

// The data gets passed down to the circles (I think):
console.log("circle data:");
d3.selectAll("g circle").each(function(d) { console.log(d.name); });

// Now change the data, and update the groups' data accordingly
data = [{"id":"A","name":"carol"},{"id":"B","name":"diane"},{"id":"C","name":"susan"}];
svg.selectAll("g").data(data, function(d) { return d.id;});

// These are the results of the change:
console.log("after change, the group has:");
d3.selectAll("g").each(function(d) { console.log(d.name); });
console.log("but the circles still have:");
d3.selectAll("g circle").each(function(d) { console.log(d.name); });

谁能帮我找到一种简洁的方法来将新名称放入组的所有子元素中?在我现实生活中的例子中,每个 g包含许多 circle s。

最佳答案

有两种方法可以将数据从父级传播到子级:

  • selection.select将隐式地执行此操作。 (selection.appendselection.insert 的实现实际上是基于selection.select 内部的)
    svg.selectAll("g").select("circle")
  • 您可以使用函数显式地重做数据连接以接收父数据并在子数组中返回它。
    svg.selectAll("g").selectAll("circle")
    .data(function(d) { return [d]; });

  • 这些等同于同一件事。第一个选项依赖于 select 中的一些特殊行为,因此一开始可能有点令人惊讶,但它的好处在于它使节点更新模式与通过插入/附加创建节点的模式对称。如果您需要对正在传播的数据应用任何更改,则第二个选项很有用。

    这是您未链接到的另一篇文章,它也可能有用: Thinking with Joins

    关于d3.js - d3js : make new parent data descend into child nodes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18831949/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com