Simple Treemap with D3 and Divs
by sijoma
CSS
@import url(https://fonts.googleapis.com/css?family=Source+Sans+Pro);
body {
font-family: 'Source Sans Pro', sans-serif;
margin: auto;
position: relative;
padding: 20px;
height: 100%;
}
form {
position: absolute;
right: 10px;
top: 10px;
}
.node {
border: solid 1px white;
line-height: 0.95;
overflow: hidden;
position: absolute;
border-radius: 6px;
background-image: -webkit-linear-gradient(top, hsla(0,0%,100%,.3), hsla(0,0%,100%,0));
background-image: -moz-linear-gradient(top, hsla(0,0%,100%,.3), hsla(0,0%,100%,0));
background-image: -ms-linear-gradient(top, hsla(0,0%,100%,.3), hsla(0,0%,100%,0));
background-image: -o-linear-gradient(top, hsla(0,0%,100%,.3), hsla(0,0%,100%,0));
background-image: linear-gradient(top, hsla(0,0%,100%,.3), hsla(0,0%,100%,0));
text-shadow: -1px -1px 2px hsla(0,0%,100%,0.25),
-1px -1px 2px hsla(0,0%,100%,0.25),
-1px 1px 2px hsla(0,0%,100%,0.25),
1px -1px 2px hsla(0,0%,100%,0.25),
-1px 0px 2px hsla(0,0%,100%,0.25),
1px 0px 2px hsla(0,0%,100%,0.25);
}
.node div {
padding: 6px 4%;
}
JavaScript
var tree = {
name: "tree",
children: [
{ name: "Cardiology", size: 3 },
{ name: "Neurology", size: 2 },
{ name: "Primary Care", size: 8 },
{ name: "Immunology", size: 4 },
{ name: "Podiatry", size: 1 },
{ name: "Pediatrics", size: 3 },
{ name: "Dentistry", size: 2 }
]
};
var width = innerWidth-40,
height = innerHeight-40,
color = d3.scale.linear()
.domain([1, 4, 8])
.range(["red", "yellow", "green"]),
div = d3.select("body").append("div")
.style("position", "relative");
var treemap = d3.layout.treemap()
.size([width, height])
.sticky(true)
.value(function(d) { return d.size; });
var node = div.datum(tree).selectAll(".node")
.data(treemap.nodes)
.enter().append("div")
.attr("class", "node")
.call(position)
.style("background-color", function(d) {
return d.name == 'tree' ? '#fff' : color(d.name); })
.append('div')
.style("font-size", function(d) {
// compute font size based on sqrt(area)
return Math.max(20, 0.18*Math.sqrt(d.area))+'px'; })
.text(function(d) { return d.children ? null : d.name; });
function position() {
this.style("left", function(d) { return d.x + "px"; })
.style("top", function(d) { return d.y + "px"; })
.style("width", function(d) { return Math.max(0, d.dx - 1) + "px"; })
.style("height", function(d) { return Math.max(0, d.dy - 1) + "px"; });
}