我想重現D3 Sankey chart using circle node instead of rectangle node的過程,但是,我想只選擇某些節點從矩形切換到圓形。將D3 Sankey圖表中的某些節點從矩形轉換爲圓形
例如,在此示例中使用的jsfiddle中,您將如何選擇Node 4
和Node 7
以將其轉換爲圓形?
我想重現D3 Sankey chart using circle node instead of rectangle node的過程,但是,我想只選擇某些節點從矩形切換到圓形。將D3 Sankey圖表中的某些節點從矩形轉換爲圓形
例如,在此示例中使用的jsfiddle中,您將如何選擇Node 4
和Node 7
以將其轉換爲圓形?
我更新了fiddle。
基本上你只需要一些方法來選擇你想做出不同的節點。我使用了獨特的類名,以便您可以使用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。
我從this fiddle開始(從另一個SO question你merntioned)),其中所有的節點已經轉化爲界:
然後我修改現有的和增加了一些新的代碼,涉及創建圈子時進行過濾:
// 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的一些品質(如更廣泛的連接)。