A treemap of counties by state. Counties are colored green if they’re growing and red if they’re shrinking.
<!DOCTYPE html>
<head>
<title>County Treemap</title>
</head>
<meta charset="utf-8">
<style>
svg {
height: 500px;
width: 1000px;
}
</style>
<body>
<div id="viz">
<svg></svg>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.16/d3.min.js" charset="utf-8" type="text/javascript"></script>
<script>
d3.csv("PEP_2014_PEPANNRES_with_ann.csv", cleanCensus);
function cleanCensus(data){
data.forEach(function (county) {
county.name = county.label.split(", ")[0]
county.state = county.label.split(", ")[1]
county.pop = parseInt(county["pop2014"]);
county.trend = county["pop2014"] - county["pop2010"] > 0 ? "growth" : "loss";
county.leafColor = county["pop2014"] - county["pop2010"] > 0 ? "green" : "red";
county.leafData = parseInt(county["pop2014"]);
})
packableData = nesting(data);
treemap(packableData);
}
function nesting(data) {
nestedData = d3.nest()
.key(function (d) {
return d.state;
})
.key(function (d) {
return d.trend
})
.entries(data);
return packableData = {id: "root", key: "root", values: nestedData}
}
function treemap(data) {
treemap = d3.layout.treemap();
treemap
.size([500,500])
.children(function(d) {return d["values"]})
.padding(function (d) {return d["values"] ? 2 : 1})
.value(function(d) {return d.leafData ? d.leafData : 1})
treemapData = treemap(data);
var chartG = d3.select("svg")
.append("g")
.attr("class", "dendrogram")
.attr("transform", "translate(0,0)");
chartG.selectAll("rect")
.data(treemapData)
.enter()
.append("rect")
.attr("x", function (d) {return d.x})
.attr("y", function (d) {return d.y})
.attr("height", function (d) {return d.dy})
.attr("width", function (d) {return d.dx})
.style("fill", function (d) {return d.leafColor ? d.leafColor : "grey"})
.style("fill-opacity", function (d) {return d.leafColor ? 1 : .1})
.style("stroke", function (d) {return d.leafColor ? d3.rgb(d.leafColor).darker() : "black"})
chartG.selectAll("text")
.data(treemapData.filter(function (d) {return d.depth === 1}))
.enter()
.append("text")
.attr("x", function (d) {return d.x})
.attr("y", function (d) {return d.y + 15})
.text(function (d) {return d["key"] ? d["key"].substr(0, parseInt(d.dx / 8)) : ""})
}
</script>