Reputation: 35
I want to create a Treemap with d3 but the enitities I want to show don't have a hierarchy. Is it still possible to create a Treemap?
My data includes crimes in Germany.
The I just wanted to show in the beginning all the crimes (Treemap not zoomed). then if I click on one of the boxes it will show me how many of them are male or female.
Sounds so easy but I really don't get it with my example.
I have tried so many examples but I dont get it because of the hierarchy.
Upvotes: 2
Views: 1036
Reputation: 63
You can arrange tabular data in a hierarchy using d3.nest()
. This function groups the data under multiple key fields, similar to a GROUP BY statement in SQL - more detail can be found in the nest documentation. For an introduction to using d3.nest()
, see this guide.
D3's treemap
requires data to be arranged in a hierarchy with a root node, so you should nest all table entries under a single 'root' value as well as any fields that you wish to use to subdivide the treemap. The following code will arrange your data into a hierarchy that splits it by Sexus only:
var nested_data = d3.nest()
// Create a root node by nesting all data under the single value "root":
.key(function () { return "root"; })
// Nest by other fields of interest:
.key(function (d) { return d.Sexus; })
.entries(data);
For example, the following code shows a single rectangle in the treemap for all crimes and displays the number of crimes by Sexus when the user clicks on the rectangle:
<script src="js/d3.v4.js"></script>
<script>
var margin = { top: 40, right: 10, bottom: 10, left: 10 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var color = d3.scaleOrdinal().range(d3.schemeCategory20c);
var treemap = d3.treemap().size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", (width + margin.left + margin.right) + "px")
.attr("height", (height + margin.top + margin.bottom) + "px");
d3.csv("data/GermanyCrimeData.csv", function (error, data) {
if (error) throw error;
var nested_data = d3.nest()
// Create a root node by nesting all data under the single value "root":
.key(function () { return "root"; })
// Nest by other fields of interest:
.key(function (d) { return d.Sexus; })
.entries(data);
var root = d3.hierarchy(nested_data[0], function (d) { return d.values; })
.sum(function (d) { return d.Tatverdaechtige_Insgesamt_deutsch; });
var tree = treemap(root);
var nodes = svg.selectAll(".node")
.data([tree]) // Bind an array that contains the root node only.
.enter().append("g")
.attr("class", "node")
.attr('transform', function (d) {
return 'translate(' + [d.x0, d.y0] + ')'
})
.on("click", function () {
d3.select(this).select("text").style("visibility", "visible");
//See https://stackoverflow.com/questions/44074031/d3-show-hide-text-of-only-clicked-node
});
nodes.append("rect")
.attr("width", function (d) { return Math.max(0, d.x1 - d.x0 - 1) + "px"; })
.attr("height", function (d) { return Math.max(0, d.y1 - d.y0 - 1) + "px"; })
.attr("fill", function (d) { return color(d.data.key); });
nodes.append("text")
.attr("dx", 4)
.attr("dy", 14)
.style("visibility", "hidden") //Initially the text is not visible
.text(function (d) {
// Create an array of Tatverdaechtige_Insgesamt_deutsch counts for each Sexus:
var array = d.children.map(function (elt) { // Here, map is a native Javascript function, not a D3 function
// Return "Sexus: Tatverdaechtige_Insgesamt_deutsch":
return elt.data.key + ": " + elt.value;
// Note that d.data.key and d.value were created by d3.nest()
});
// Return a string representation of the array:
return d.data.key + " - " + array.join(", ");
});
});
</script>
To subdivide the treemap by a given field, the data must be nested by that field and tree.children
must be bound to the DOM instead of [tree]
:
//...
d3.csv("data/GermanyCrimeData.csv", function (error, data) {
if (error) throw error;
var nested_data = d3.nest()
.key(function () { return "root"; })
.key(function (d) { return d.Straftat; })
.key(function (d) { return d.Sexus; })
.entries(data);
var root = d3.hierarchy(nested_data[0], function (d) { return d.values; })
.sum(function (d) { return d.Tatverdaechtige_Insgesamt_deutsch; });
var tree = treemap(root);
var nodes = svg.selectAll(".node")
.data(tree.children) // Bind the children of the tree's root node
.enter().append("g")
.attr("class", "node")
.attr('transform', function (d) {
return 'translate(' + [d.x0, d.y0] + ')'
})
.on("click", function () {
d3.select(this).select("text").style("visibility", "visible");
//See https://stackoverflow.com/questions/44074031/d3-show-hide-text-of-only-clicked-node
});
//...
A simple way to make the treemap zoomable is to place the code that draws the treemap in a function, then use on("click", ...)
to re-trigger the function whenever a rectangle is clicked, zooming in on the chosen node:
//...
d3.csv("data/GermanyCrimeData.csv", function (error, data) {
if (error) throw error;
var nested_data = d3.nest()
.key(function () { return "root"; })
.key(function (d) { return d.Stadt_Landkreis; })
.key(function (d) { return d.Straftat; })
.key(function (d) { return d.Sexus; })
.entries(data);
function drawTreemap(root) {
var hierarchical_data = d3.hierarchy(root, function (d) { return d.values; })
.sum(function (d) { return d.Tatverdaechtige_Insgesamt_deutsch; });
var tree = treemap(hierarchical_data);
// Clear the contents of the <svg>:
svg.selectAll("*").remove();
// Now populate the <svg>:
var nodes = svg.selectAll(".node")
.data(tree.children) //Bind the children of the root node in the tree
.enter().append("g")
.attr("class", "node")
.attr('transform', function (d) {
return 'translate(' + [d.x0, d.y0] + ')'
})
.on("click", function (d) {
if (d.children) { //The user clicked on a node that has children
drawTreemap(d.data);
} else { // The user clicked on a node that has no children (i.e. a leaf node).
// Do nothing.
}
});
nodes.append("rect")
.attr("width", function (d) { return Math.max(0, d.x1 - d.x0 - 1) + "px"; })
.attr("height", function (d) { return Math.max(0, d.y1 - d.y0 - 1) + "px"; })
.attr("fill", function (d) { return color(d.data.key); });
nodes.append("text")
.attr("dx", 4)
.attr("dy", 14)
//.style("visibility", "hidden") //Initially the text is not visible
.text(function (d) {
if (d.children) {
return d.data.key;
} else {
return d.data.Stadt_Landkreis + ", "
+ d.data.Straftat + ", "
+ d.data.Sexus + ": "
+ d.data.Tatverdaechtige_Insgesamt_deutsch;
}
});
}; // end of drawTreemap()
// Now call drawTreemap for the first time:
drawTreemap(nested_data[0]);
});
</script>
Finally, to animate the transitions, the following code is a zoomable treemap based on Mike Bostock's example, where flare.json
has been replaced with the data from your CSV file, arranged with d3.nest()
and d3.hierarchy()
(this example uses D3 v3):
<!DOCTYPE html>
<html>
<head>
<style>
#chart {
width: 960px;
height: 500px;
background: #ddd;
}
text {
pointer-events: none;
}
.grandparent text {
font-weight: bold;
}
rect {
fill: none;
stroke: #fff;
}
rect.parent,
.grandparent rect {
stroke-width: 2px;
}
.grandparent rect {
fill: orange;
}
.grandparent:hover rect {
fill: #ee9700;
}
.children rect.parent,
.grandparent rect {
cursor: pointer;
}
.children rect.parent {
fill: #bbb;
fill-opacity: .5;
}
.children:hover rect.child {
fill: #bbb;
}
</style>
</head>
<body>
<script src="js/d3.v3.js"></script>
<script>
var margin = {top: 20, right: 0, bottom: 0, left: 0},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
formatNumber = d3.format(",d"),
transitioning;
var x = d3.scale.linear()
.domain([0, width])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, height])
.range([0, height]);
var treemap = d3.layout.treemap()
.children(function(d, depth) { return depth ? null : d._children; })
.sort(function(a, b) { return a.value - b.value; })
.ratio(height / width * 0.5 * (1 + Math.sqrt(5)))
.round(false);
var svg = d3.select("body").append("svg")
.attr("id", "chart") // Apply the #chart style to the <svg> element
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.bottom + margin.top)
.style("margin-left", -margin.left + "px")
.style("margin.right", -margin.right + "px")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.style("shape-rendering", "crispEdges");
var grandparent = svg.append("g")
.attr("class", "grandparent");
grandparent.append("rect")
.attr("y", -margin.top)
.attr("width", width)
.attr("height", margin.top);
grandparent.append("text")
.attr("x", 6)
.attr("y", 6 - margin.top)
.attr("dy", ".75em");
d3.csv("data/GermanyCrimeData.csv", function (error, data) {
if (error) throw error;
var nested_data = d3.nest()
.key(function () { return "root"; })
.key(function (d) { return d.Stadt_Landkreis; })
.key(function (d) { return d.Straftat; })
.key(function (d) { return d.Sexus; })
.entries(data);
// In D3 v3, the syntax for arranging the data in a hierarchy is different:
var my_hierarchy = d3.layout.hierarchy()
.children(function (d) { return d.values; })
.value(function (d) { return d.Tatverdaechtige_Insgesamt_deutsch; });
// Apply the hierarchy to the nested data:
my_hierarchy(nested_data[0]); // This changes nested_data in-place
var root = nested_data[0];
initialize(root);
// my_hierarchy() has already added the aggregate values to each node
// in the tree, so instead we only need to add d._children to each node:
addUnderscoreChildren(root);
layout(root);
display(root);
function initialize(root) {
root.x = root.y = 0;
root.dx = width;
root.dy = height;
root.depth = 0;
}
// NEW FUNCTION:
function addUnderscoreChildren(d) {
if (d.children) {
// d has children
d._children = d.children;
d.children.forEach(addUnderscoreChildren);
}
}
/* NOT NEEDED:
// Aggregate the values for internal nodes. This is normally done by the
// treemap layout, but not here because of our custom implementation.
// We also take a snapshot of the original children (_children) to avoid
// the children being overwritten when when layout is computed.
function accumulate(d) {
return (d._children = d.children)
? d.value = d.children.reduce(function(p, v) { return p + accumulate(v); }, 0)
: d.value;
}*/
// Compute the treemap layout recursively such that each group of siblings
// uses the same size (1×1) rather than the dimensions of the parent cell.
// This optimizes the layout for the current zoom state. Note that a wrapper
// object is created for the parent node for each group of siblings so that
// the parent’s dimensions are not discarded as we recurse. Since each group
// of sibling was laid out in 1×1, we must rescale to fit using absolute
// coordinates. This lets us use a viewport to zoom.
function layout(d) {
if (d._children) {
treemap.nodes({_children: d._children});
d._children.forEach(function(c) {
c.x = d.x + c.x * d.dx;
c.y = d.y + c.y * d.dy;
c.dx *= d.dx;
c.dy *= d.dy;
c.parent = d;
layout(c);
});
}
}
function display(d) {
grandparent
.datum(d.parent)
.on("click", transition)
.select("text")
.text(name(d));
var g1 = svg.insert("g", ".grandparent")
.datum(d)
.attr("class", "depth");
var g = g1.selectAll("g")
.data(d._children)
.enter().append("g");
g.filter(function(d) { return d._children; })
.classed("children", true)
.on("click", transition);
g.selectAll(".child")
.data(function(d) { return d._children || [d]; })
.enter().append("rect")
.attr("class", "child")
.call(rect);
g.append("rect")
.attr("class", "parent")
.call(rect)
.append("title")
.text(function(d) { return formatNumber(d.value); });
g.append("text")
.attr("dy", ".75em")
// Replace d.name with d.key; use a function to provide
// a key for leaf nodes, because nest() does not set their
// 'key' property:
.text(function(d) { return d.key || keyOfLeafNode(d); })
.call(text);
// NEW FUNCTION:
function keyOfLeafNode(d) {
return d.Stadt_Landkreis + " "
+ d.Straftat + " "
+ d.Sexus + ": "
+ d.value;
}
function transition(d) {
if (transitioning || !d) return;
transitioning = true;
var g2 = display(d),
t1 = g1.transition().duration(750),
t2 = g2.transition().duration(750);
// Update the domain only after entering new elements.
x.domain([d.x, d.x + d.dx]);
y.domain([d.y, d.y + d.dy]);
// Enable anti-aliasing during the transition.
svg.style("shape-rendering", null);
// Draw child nodes on top of parent nodes.
svg.selectAll(".depth").sort(function(a, b) { return a.depth - b.depth; });
// Fade-in entering text.
g2.selectAll("text").style("fill-opacity", 0);
// Transition to the new view.
t1.selectAll("text").call(text).style("fill-opacity", 0);
t2.selectAll("text").call(text).style("fill-opacity", 1);
t1.selectAll("rect").call(rect);
t2.selectAll("rect").call(rect);
// Remove the old node when the transition is finished.
t1.remove().each("end", function() {
svg.style("shape-rendering", "crispEdges");
transitioning = false;
});
}
return g;
}
function text(text) {
text.attr("x", function(d) { return x(d.x) + 6; })
.attr("y", function(d) { return y(d.y) + 6; });
}
function rect(rect) {
rect.attr("x", function(d) { return x(d.x); })
.attr("y", function(d) { return y(d.y); })
.attr("width", function(d) { return x(d.x + d.dx) - x(d.x); })
.attr("height", function(d) { return y(d.y + d.dy) - y(d.y); });
}
function name(d) {
// d3.nest() gives each node the property 'key' instead of 'name',
// so replace 'd.name' with 'd.key':
return d.parent
? name(d.parent) + "." + d.key
: d.key;
}
});
</script>
</body>
</html>
Upvotes: 2