Reputation: 2115
Following up on this question, what if I have a node color, how do I access it? Put it in the nodeByName function somehow?
How to convert to D3's JSON format?
I have CSV:
source,target,target_node_color
A1,A2,green
A2,A3,blue
A2,A4,blue
And I'm drawing my tree exactly like answer above:
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});
}
});
Upvotes: 0
Views: 319
Reputation: 1018
You can access the color by adding another parameter for color in the nodeByName function. Look at this plnkr. See the console to view the color for a node.
var parent = link.source = nodeByName(link.source,link.target_node_color),
child = link.target = nodeByName(link.target,link.target_node_color);
...
console.log( nodesByName)
function nodeByName(name,color) {
return nodesByName[name] || (nodesByName[name] = {name: name, color : color}) ;
}
Upvotes: 1