C2Task1ToyDendrogram
HTML
<div id="content"></div>
CSS
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 1.5px;
}
.node {
font: 10px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 1.5px;
}
#content {
padding: 50px;
}
JavaScript
var tree_data = {
"name": "root",
"children": [{
"name": "purpledog.com"
}, {
"name": "squishedfish.co.uk"
}, {
"name": "blogs",
"children": [{
"name": "political",
"children": [{
"name": "flatbat.com"
}, {
"name": "netfrog.co.uk"
}]
}, {
"name": "squarespider.com"
}
]
}]
};
var width = 500,
height = 500;
var svg = d3.select("#content").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(40,0)");
var cluster = d3.layout.tree()
.size([height, width - 160]);
var nodes = cluster.nodes(tree_data),
links = cluster.links(nodes);
var diagonal = d3.svg.diagonal()
.projection(function (d) {
return [d.y, d.x];
});
var link = svg.selectAll(".link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", diagonal);
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function (d) {
return "translate(" + d.y + "," + d.x + ")";
})
node.append("rect")
.attr("width", "80")
.attr("height", "80")
.attr("style", "fill:red;stroke:black;stroke-width:5;opacity:0.5");
node.append("text")
.attr("dx", function (d) {
return d.children ? -8 : 8;
})
.attr("dy", 3)
.style("text-anchor", function (d) {
return d.children ? "end" : "start";
})
.text(function (d) {
return d.name;
});