d3.js - 根据子节点 d.data.type 将 link 颜色更改为子节点

d3.js - Change link colour to child node depending on child d.data.type

我想根据子节点的 d.data.type 将 link 的颜色从父节点更改为子节点。

请注意,这只适用于父子之间的link,不能回溯到祖先。

因此在下面的示例中,从 A 到 A4 的 link 将是节点 A4 的描边颜色(紫色)。

如果这个从父色渐变到子色就更好了,但不是绝对必要。

节点描边的颜色设置在d.data.type,例如:

   .style("stroke", function(d) {
            if (d.class !== "found") {
                if(d.data.type == "unit1") return "brown";
                if(d.data.type == "unit2") return "purple";
             }
                if (d.class === "found") {
                    return "#ff4136"; //red
                } else {
                    return colourScale(findParent(d));
                }
            });

fiddle

您可以对 links 使用相同的函数:

  // Transition back to the parent element position
  linkUpdate.transition()
            .duration(duration)
            .attr('d', function(d) {
                return diagonal(d, d.parent)
            })
            .style( "stroke", function ( d ) {
                        if(d.data.type == "unit1") return "brown";
                        if(d.data.type == "unit2") return "purple";
                        if ( d.class === "found" ) {
                            return "#ff4136";
                        } else {
                            return colourScale( findParentLinks( d ) );
                        }
                    } );

Fiddle

使用 d3.js 版本 3.4.11,我必须使用:

  link.transition()
            .duration(duration)
            .attr('d', function(d) {
                return diagonal(d, d.parent)
            })
            .style("stroke", function(d) {
                    if(d.target.type == "learning_event") return "#809eff";
                    if(d.target.type == "assessment") return "#74c26a";
                if (d.target.class === "found") {
                    return "#ff4136";
                } else {
                    return colourScale(findParentLinks(d));
                }
            });