我想使用圆形节点而不是矩形节点从 D3 Sankey 图表重现该过程,但是,我只想选择某些节点从矩形更改为圆形。
例如,在示例中使用的这个jsfiddle中,您将如何只选择Node 4
并Node 7
转换为圆形?
我想使用圆形节点而不是矩形节点从 D3 Sankey 图表重现该过程,但是,我只想选择某些节点从矩形更改为圆形。
例如,在示例中使用的这个jsfiddle中,您将如何只选择Node 4
并Node 7
转换为圆形?
我更新了你的小提琴。
基本上你只需要一些方法来选择你想要改变的节点。我使用了唯一的类名,以便您也可以使用 CSS 设置它们的样式。我不想编写代码来仅选择 4 和 7(我很懒),所以我只选择了所有偶数节点。
// add in the nodes
var node = svg.append("g").selectAll(".node")
.data(graph.nodes)
.enter().append("g")
.attr("class", function (d, i) { return i % 2 ? "node rect" : "node circle";
})
然后您可以使用它来选择节点并添加圆形而不是矩形。
svg.selectAll(".node.circle").append("circle")
.attr("r", sankey.nodeWidth() / 2)
.attr("cy", function(d) { return d.dy/2; })
.attr("cx", sankey.nodeWidth() / 2)
.style("fill", function (d) {
还有另一种类似的方法,如下面的jsfiddle 所示。
我从这个小提琴(从你提到的另一个SO 问题)开始,其中所有节点都已转换为圆圈:
然后我修改了现有的并添加了一些新代码,这些代码涉及在创建圈子期间进行过滤:
// add the circles for "node4" and "node7"
node
.filter(function(d){ return (d.name == "node4") || (d.name == "node7"); })
.append("circle")
.attr("cx", sankey.nodeWidth()/2)
.attr("cy", function (d) {
return d.dy/2;
})
.attr("r", function (d) {
return Math.sqrt(d.dy);
})
.style("fill", function (d) {
return d.color = color(d.name.replace(/ .*/, ""));
})
.style("fill-opacity", ".9")
.style("shape-rendering", "crispEdges")
.style("stroke", function (d) {
return d3.rgb(d.color).darker(2);
})
.append("title")
.text(function (d) {
return d.name + "\n" + format(d.value);
});
// add the rectangles for the rest of the nodes
node
.filter(function(d){ return !((d.name == "node4") || (d.name == "node7")); })
.append("rect")
.attr("y", function (d) {
return d.dy/2 - Math.sqrt(d.dy)/2;
})
.attr("height", function (d) {
return Math.sqrt(d.dy);
})
.attr("width", sankey.nodeWidth())
.style("fill", function (d) {
return d.color = color(d.name.replace(/ .*/, ""));
})
.style("fill-opacity", ".9")
.style("shape-rendering", "crispEdges")
.style("stroke", function (d) {
return d3.rgb(d.color).darker(2);
})
.append("title")
.text(function (d) {
return d.name + "\n" + format(d.value);
});
必须修改类似的代码才能在矩形旁边准确定位文本。
我相信最终结果看起来很自然,尽管它失去了原始 Sankey 的一些品质(如更广泛的连接)。