JSFiddle - React, Tailwind, and code Playground
by sijoma
HTML
<script src="http://d3js.org/d3.v2.js"></script>
<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
<p id="chart">
<p id="rawdata">
CSS
#chart {
width: 820px;
height: 700px;
background: #bbb;
margin: 1px auto;
position: relative;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
text {
pointer-events: none;
}
.grandparent text { /* header text */
font-weight: bold;
font-size: medium;
font-family: "Open Sans", Helvetica, Arial, sans-serif;
}
rect {
fill: none;
stroke: #fff;
}
rect.parent,
.grandparent rect {
stroke-width: 2px;
}
.grandparent rect {
fill: #fff;
}
.children rect.parent,
.grandparent rect {
cursor: pointer;
}
rect.parent {
pointer-events: all;
}
.children:hover rect.child,
.grandparent:hover rect {
fill: #aaa;
}
.textdiv { /* text in the boxes */
font-size: x-small;
padding: 5px;
font-family: "Open Sans", Helvetica, Arial, sans-serif;
}
JavaScript
function reSortRoot(root,value_key) {
//console.log("Calling");
for (var key in root) {
if (key == "key") {
root.name = root.key;
delete root.key;
}
if (key == "values") {
root.children = [];
for (item in root.values) {
root.children.push(reSortRoot(root.values[item],value_key));
}
delete root.values;
}
if (key == value_key) {
root.value = parseFloat(root[value_key]);
delete root[value_key];
}
}
return root;
}
$( document ).ready(function() {
// You can comment out the whole csv section if you just have a JSON file.
// loadJSONFile('data/portaldata.json');
d3.csv("https://raw.githubusercontent.com/sijoma0/Treemap/master/Home_Office_Air_Travel_Data_2011.csv", function(csv_data){
// Add, remove or change the key values to change the hierarchy.
var nested_data = d3.nest()
.key(function(d) { return d.Destination; })
.key(function(d) { return d.Supplier_name; })
.key(function(d) { return d.Ticket_class_description; })
.entries(csv_data);
// Creat the root node for the treemap
var root = {};
// Add the data to the tree
root.key = "Data";
root.values = nested_data;
// Change the key names and children values from .next and add values for a chosen column to define the size of the blocks
root = reSortRoot(root,"Paid_fare");
// DEBUG
// $("#rawdata").html(JSON.stringify(root));
loadData(root);
});
});
var margin = {top: 20, right: 0, bottom: 0, left: 0},
width = 820,
height = 700 - margin.top - margin.bottom,
formatNumber = d3.format(".2s"),
transitioning;
/* create x and y scales */
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 -...