0
跟進這個問題,如果我有一個節點顏色,我該如何訪問它?以某種方式將其放入nodeByName函數中?D3 CSV到JSON鄰接列表,如何訪問節點顏色?
How to convert to D3's JSON format?
我有CSV:
source,target,target_node_color
A1,A2,green
A2,A3,blue
A2,A4,blue
而且我畫我的樹一模一樣的答案以上:
var margin = {top: 40, right: 40, bottom: 40, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var tree = d3.layout.tree()
.size([height, width]);
var diagonal = d3.svg.diagonal()
.projection(function(d) {
return [d.y, d.x]; });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("atlas16.csv", function(error, links) {
if (error) throw error;
var nodesByName = {};
// Create nodes for each unique source and target.
links.forEach(function(link) {
var parent = link.source = nodeByName(link.source),
child = link.target = nodeByName(link.target);
if (parent.children) parent.children.push(child);
else parent.children = [child];
});
// Extract the root node and compute the layout.
var nodes = tree.nodes(links[0].source);
// Create the link lines.
svg.selectAll(".link")
.data(links)
.enter().append("path")
.attr("class", function (d) {
return "link";})
.attr("d", diagonal);
// Create the node circles.
svg.selectAll(".node")
.data(nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 4.5)
.attr("fill", "red")
.attr("cx", function(d) {
return d.y; })
.attr("cy", function(d) { return d.x; });
function nodeByName(name) {
return nodesByName[name] || (nodesByName[name] = {name: name});
}
});