Trouble embedding (&understanding) JSON data into Treemap - javascript

so Im really new to d3 and Im just getting started with data visualizations. So im trying to use mike bostok treemap to visualize with my data. I have some understanding of parent nodes and children nodes but im at a lost when it comes to understanding or writing a code related to nodes.
bostoks JSON data has multiple levels or depths while mine has one root node and an array of objects all at the same depth.
JSON file
Javascript code
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var fader = function(color) { return d3.interpolateRgb(color, "#fff")(0.2); },
color = d3.scaleOrdinal(d3.schemeCategory20.map(fader)),
format = d3.format(",d");
var treemap = d3.treemap()
.tile(d3.treemapResquarify)
.size([width, height])
.round(true)
.paddingInner(1);
d3.json("data.json", function(data) {
var root = d3.hierarchy(data)
.eachBefore(function(d) {
d.data.id = (d.parent ? d.parent.data.id + "." : "") + d.data.name; })
.sum(sumBySize)
.sort(function(a, b) {
return b.height - a.height || b.value - a.value; });
treemap(root);
console.log(d.data.id);
var cell = svg.selectAll("g")
.data(root.leaves())
.enter().append("g")
.attr("transform", function(d) { return "translate(" + d.x0 + "," + d.y0 + ")"; });
cell.append("rect")
.attr("id", function(d) { return d.data.id; })
.attr("width", function(d) { return d.x1 - d.x0; })
.attr("height", function(d) { return d.y1 - d.y0; })
//.attr("fill", function(d) { return color(d.parent.data.id); });
cell.append("clipPath")
.attr("id", function(d) { return "clip-" + d.data.id; })
.append("use")
.attr("xlink:href", function(d) { return "#" + d.data.id; });
cell.append("text")
.attr("clip-path", function(d) { return "url(#clip-" + d.data.id + ")"; })
.selectAll("tspan")
.data(function(d) { return d.data.name.split(/(?=[A-Z][^A-Z])/g); })
.enter().append("tspan")
.attr("x", 4)
.attr("y", function(d, i) { return 13 + i * 10; })
.text(function(d) { return d; });
cell.append("title")
.text(function(d) { return d.data.id + "\n" + format(d.value); });
d3.selectAll("input")
.data([sumBySize, sumByCount], function(d) { return d ? d.name : this.value; })
.on("change", changed);
var timeout = d3.timeout(function() {
d3.select("input[value=\"sumByCount\"]")
.property("checked", true)
.dispatch("change");
}, 2000);
function changed(sum) {
timeout.stop();
treemap(root.sum(sum));
cell.transition()
.duration(750)
.attr("transform", function(d) { return "translate(" + d.x0 + "," + d.y0 + ")"; })
.select("rect")
.attr("width", function(d) { return d.x1 - d.x0; })
.attr("height", function(d) { return d.y1 - d.y0; });
}
});
function sumByCount(d) {
return d.children ? 0 : 1;
}
function sumBySize(d) {
return d.size;
}
could someone help me with this . I think it has to do with the hierarchy.
I think I might need to change something here
d3.json("data.json", function(data) {
var root = d3.hierarchy(data)
.eachBefore(function(d) {
d.data.id = (d.parent ? d.parent.data.id + "." : "") + d.data.name; })
I appreciate any help

Related

Dynamically update two dataset with d3.js treemap

My task is to switch two datasets with d3.js treemap.
But now I can only this if I remove all exiting treemap like the following code.
I also try to add treemap.sticky(false), but it doesn't work and the error shows that"sticky() function is not defined."
Sorry, I'm new to D3.js!
Thanks!
d3.select("form").on("change", function() {
switch(event.target.value) {
case "a":
d3.json(url1).then( function(data){
svg.selectAll("g").remove();
buildTreemap(data);
});
break;
case "b":
d3.json(url2).then( function(data){
svg.selectAll("g").remove();
buildTreemap(data);
});
break;
default:
}
});
d3.json(url1).then( function(data){
buildTreemap(data);
});
function buildTreemap(data){
console.log(data);
root = d3.hierarchy(data)
.sum(function(d) { return d.value; })
.sort(function(a, b) { return b.height - a.height || b.value - a.value; });
var treemap = d3.treemap()
.size([width, height])
.padding(1)
.round(true);
treemap(root);
var cells = d3.select("svg")
.selectAll("g")
.data(root.leaves())
.enter()
.append("g")
.attr("class", function(d) { return "node level-" + d.depth; })
.attr("title", function(d) { return d.data.name ? d.data.name : "null"; })
.attr("transform", function(d) { return "translate(" + (d.x0)/2 + "," + (d.y0) + ")"; });
rect=cells.append("rect");
rect.style("fill", function(d) {
while(d.depth > 1) d = d.parent;
return color(d.data.name);
})
.style("opacity", 0.7)
.attr("width", 0)
.attr("height", 0)
.transition()
.duration(1000)
.attr("width", function(d) {
return (d.x1 - d.x0)/2; })
.attr("height", function(d) { return (d.y1 - d.y0); });
cells.append("text")
.attr("text-anchor", "start")
.attr("x", 5)
.attr("dy", 30)
.attr("width",cells.width)
.attr("class", "node-label")
.text(function (d) { return d.children ? null : (d.x1-d.x0)<130 ? null: d.data.name})
.style("font-size",function(d){
return (d.x1-d.x0)<110 ? 5+"px" : (d.x1-d.x0)<130 ? 10+"px" : 15+"px"})
.style("width", function(d) { return (d.x1 - d.x0)/2; });
}

In d3.js treemap layout how to make the last child clickable and fill the entire treemap layout

Im using d3.js treemap layout . In the treemap , on clicking the parent segment with the children property it transitions into its respective child sub segments . But on clicking the last child without any children property it wont make the transition happens to fill only that child node in the entire layout . In the code that im working on I can redirect to a new window on click of the last child but not sure how to make the transition happening .
Find my code in the link https://codesandbox.io/s/affectionate-thunder-l024x
class TreemapChart extends React.Component {
componentDidMount() {
const self = this;
var margin = { top: 20, right: 0, bottom: 0, left: 0 },
width = 960,
height = 500 - margin.top - margin.bottom,
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("#chart")
.append("svg")
.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");
// .on("mousemove", function (d) {
// tool.style("left", d3.event.pageX + 10 + "px")
// tool.style("top", d3.event.pageY - 20 + "px")
// tool.style("display", "inline-block");
// tool.html(d.children ? null : d.name + "<br>" );
// }).on("mouseout", function (d) {
// tool.style("display", "none");
// });
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", ".35em");
function dataMap(root) {
initialize(root);
accumulate(root);
accumulateCount(root);
layout(root);
display(root);
function initialize(root) {
root.x = root.y = 0;
root.dx = width;
root.dy = height;
root.depth = 0;
}
// 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;
}
function accumulateCount(d) {
return (d._children = d.children)
? (d.count = d.children.reduce(function(p, v) {
return p + accumulateCount(v);
}, 0))
: d.count;
}
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) {
// console.log(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)
.on("click", function(d) {
if (!d._children) {
window.open(d.url);
}
})
.append("title")
.text(function(d) {
return `${d.name} (${d.count})`;
});
g.append("text")
.attr("dx", "1rem")
.attr("dy", "2rem")
.text(function(d) {
return `${d.name}`;
})
.call(text);
function transition(d) {
self.props.onClickSegment(d.metricsValue);
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) {
return d.parent ? name(d.parent) + " / " + d.name : d.name;
}
}
dataMap(dataObj);
}
handleClick = d => {
// this.props.onClickSegment(d.metricsValue);
console.log("The text", d.metricsValue);
};
render() {
return <p id="chart" />;
}
}
I need to click the last child and on clicking the last child should fill the layout with the respective breadcrumb like in the code.

How to dynamicly update a d3 pack

I'm very new to D3, and I don't understand all the logic of it.
I try to use examples, but it seems to be so many way to do things that it confuses me...
Anyway, I try to make this example dynamic.
Here is the code I have right now :
<!DOCTYPE html>
<meta charset="utf-8">
<style>
text {
font: 12px sans-serif;
text-anchor: middle;
}
.titre {
font-size: 18px;
}
.node--hover circle {
stroke: #000;
stroke-width: 1.2px;
}
#csv {
float: left;
}
</style>
<form>
<textarea name="csv" id="csv" cols="50" rows="30">id,taille,titre
D3,
D3.one,2000
D3.two,2000</textarea>
</form>
<svg width="400" height="400"><g transform="translate(1,1)"></g></svg>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var format = d3.format(",d");
var color = d3.scaleSequential(d3.interpolateMagma)
.domain([-4, 4]);
var stratify = d3.stratify()
.parentId(function(d) { return d.id.substring(0, d.id.lastIndexOf(".")); });
var pack = d3.pack()
.size([width - 2, height - 2])
.padding(3);
var csv = $("#csv").val();
data = d3.csvParse(csv);
var root = stratify(data)
.sum(function(d) { return d.taille; })
.sort(function(a, b) { return b.taille - a.taille; });
pack(root);
var node = svg.select("g")
.selectAll("g")
.data(root.descendants())
.enter().append("g")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.attr("class", function(d) { return "node" + (!d.children ? " node--leaf" : d.depth ? "" : " node--root"); })
.each(function(d) { d.node = this; });
node.append("circle")
.attr("id", function(d) { return "node-" + d.id; })
.attr("r", function(d) { return d.r; })
.style("fill", function(d) {
return color(d.depth);
});
var leaf = node.filter(function(d) { return !d.children; });
leaf.append("clipPath")
.attr("id", function(d) { return "clip-" + d.id; })
.append("use")
.attr("xlink:href", function(d) { return "#node-" + d.id + ""; });
leaf.append("text")
.attr("clip-path", function(d) { return "url(#clip-" + d.id + ")"; }).attr("class", function(d) { return d.data.titre=="1" ? "titre" : ""})
.selectAll("tspan")
.data(function(d) { return d.id.substring(d.id.lastIndexOf(".") + 1).split(/(?=[A-Z][^A-Z])/g); })
.enter().append("tspan")
.attr("x", 0)
.attr("y", function(d, i, nodes) { return 13 + (i - nodes.length / 2 - 0.5) * 20; })
.text(function(d) { return d; });
$(function() {
$("#csv").blur(function()
{
update();
});
});
function update()
{
var csv = $("#csv").val();
data = d3.csvParse(csv);
var root = stratify(data)
.sum(function(d) { return d.taille; })
.sort(function(a, b) { return b.taille - a.taille; });
pack(root);
//console.log(root.descendants());
node = node.data(root.descendants(), function(d) {return d});
console.log(node);
//node.exit().remove();
node.enter().append("g")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.attr("class", function(d) { return "node" + (!d.children ? " node--leaf" : d.depth ? "" : " node--root"); })
.each(function(d) { d.node = this; });
node.append("circle")
.attr("id", function(d) { return "node-" + d.id; })
.attr("r", function(d) { return d.r; })
.style("fill", function(d) {
return color(d.depth);
});
var leaf = node.filter(function(d) { return !d.children; });
leaf.append("clipPath")
.attr("id", function(d) { return "clip-" + d.id; })
.append("use")
.attr("xlink:href", function(d) { return "#node-" + d.id + ""; });
leaf.append("text")
.attr("clip-path", function(d) { return "url(#clip-" + d.id + ")"; }).attr("class", function(d) { return d.data.titre=="1" ? "titre" : ""})
.selectAll("tspan")
.data(function(d) { return d.id.substring(d.id.lastIndexOf(".") + 1).split(/(?=[A-Z][^A-Z])/g); })
.enter().append("tspan")
.attr("x", 0)
.attr("y", function(d, i, nodes) { return 13 + (i - nodes.length / 2 - 0.5) * 20; })
.text(function(d) { return d; });
}
</script>
You can test it on bl.ocks :
https://bl.ocks.org/matthieubrunet/79ef9968e2eaaba7f0718a373d240025
The update is supposed to happen on blur.
I think my problem is around the enter function (in the update function), which returns all elements instead of only new ones.
As ou can see, I commented out the exit, because it removes all the childs circles.
Thanks a lot
One of the most confusing things with d3 is how to handle the enter, update and exit pattern. I won't provide you a tutorial on it as there are a number of great resources already - out there. But I've taken the time to re-factor your update function to handle the situations properly:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
text {
font: 12px sans-serif;
text-anchor: middle;
}
.titre {
font-size: 18px;
}
.node--hover circle {
stroke: #000;
stroke-width: 1.2px;
}
#csv {
float: left;
}
</style>
<form>
<textarea name="csv" id="csv" cols="50" rows="30">id,taille,titre
D3,
D3.one,2000
D3.two,2000</textarea>
</form>
<svg width="400" height="400">
<g transform="translate(1,1)"></g>
</svg>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var format = d3.format(",d");
var color = d3.scaleSequential(d3.interpolateMagma)
.domain([-4, 4]);
var stratify = d3.stratify()
.parentId(function(d) {
return d.id.substring(0, d.id.lastIndexOf("."));
});
var pack = d3.pack()
.size([width - 2, height - 2])
.padding(3);
update();
$(function() {
$("#csv").blur(function() {
update();
});
});
function update() {
var csv = $("#csv").val();
data = d3.csvParse(csv);
var root = stratify(data)
.sum(function(d) {
return d.taille;
})
.sort(function(a, b) {
return b.taille - a.taille;
});
pack(root);
// data-binding
var node = svg.selectAll(".node").data(root.descendants(), function(d){
return d;
});
// exiting nodes
node.exit().remove();
// entering nodes
var nodeEnter = node.enter().append("g")
.attr("class", function(d) {
return "node" + (!d.children ? " node--leaf" : d.depth ? "" : " node--root");
});
// add circles
nodeEnter.append("circle")
.attr("id", function(d) {
return "node-" + d.id;
});
// update + enter
node = nodeEnter.merge(node);
// position everyone
node.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
// update circles
node.select("circle")
.attr("r", function(d) {
return d.r;
})
.style("fill", function(d) {
return color(d.depth);
});
// handle enter of leafs
var leafEnter = nodeEnter.filter(function(d) {
return !d.children;
});
leafEnter.append("clipPath")
.attr("id", function(d) {
return "clip-" + d.id;
})
.append("use")
.attr("xlink:href", function(d) {
return "#node-" + d.id + "";
});
leafEnter.append("text")
.attr("clip-path", function(d) {
return "url(#clip-" + d.id + ")";
}).attr("class", function(d) {
return d.data.titre == "1" ? "titre" : "";
});
node.select("text")
.selectAll("tspan")
.data(function(d) {
return d.id.substring(d.id.lastIndexOf(".") + 1).split(/(?=[A-Z][^A-Z])/g);
})
.enter().append("tspan")
.attr("x", 0)
.attr("y", function(d, i, nodes) {
return 13 + (i - nodes.length / 2 - 0.5) * 20;
})
.text(function(d) {
return d;
});
}
</script>

Take input for treemap using json objects not to read from csv file

I'm trying to build a Zoomable TreeMap using d3 js. I need to take an array of JSON objects from the server and pass it to tha treeMap and let the treemap handle it. But in doing so I'm not able to parse it
Here's my code for the tremap:
$rootScope.loadTreeMap = function(path_to_data,dom_element_to_append_to){
var w = $(dom_element_to_append_to).width() - 80,
h = 800 - 180,
x = d3.scale.linear().range([0, w]),
y = d3.scale.linear().range([0, h]),
color = d3.scale.category20c(),
root,
node;
console.log("W" + w);
console.log("h " + h);
var treemap = d3.layout.treemap()
.round(false)
.size([w, h])
.sticky(true)
.value(function(d) { return d.size; });
var svg = d3.select(dom_element_to_append_to).append("div")
.attr("class", "chart")
.style("width", w + "px")
.style("height", h + "px")
.append("svg:svg")
.attr("width", w)
.attr("height", h)
.append("svg:g")
.attr("transform", "translate(.5,.5)");
d3.json(path_to_data, function(data) {
node = root = data;
var nodes = treemap.nodes(root)
.filter(function(d) { return !d.children; });
var cell = svg.selectAll("g")
.data(nodes)
.enter().append("svg:g")
.attr("class", "cell")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.on("click", function(d) { return zoom(node == d.parent ? root : d.parent); });
cell.append("svg:rect")
.attr("width", function(d) { return d.dx - 1; })
.attr("height", function(d) { return d.dy - 1; })
.style("fill", function(d) { return color(d.parent.name); });
cell.append("svg:text")
.attr("x", function(d) { return d.dx / 2; })
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; })
.style("opacity", function(d) { d.w = this.getComputedTextLength(); return d.dx > d.w ? 1 : 0; });
d3.select(window).on("click", function() { zoom(root); });
d3.select("select").on("change", function() {
treemap.value(this.value == "size" ? size : count).nodes(root);
zoom(node);
});
});
function size(d) {
return d.size;
}
function count(d) {
return 1;
}
function zoom(d) {
var kx = w / d.dx, ky = h / d.dy;
x.domain([d.x, d.x + d.dx]);
y.domain([d.y, d.y + d.dy]);
var t = svg.selectAll("g.cell").transition()
.duration(d3.event.altKey ? 7500 : 750)
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
t.select("rect")
.attr("width", function(d) { return kx * d.dx - 1; })
.attr("height", function(d) { return ky * d.dy - 1; })
t.select("text")
.attr("x", function(d) { return kx * d.dx / 2; })
.attr("y", function(d) { return ky * d.dy / 2; })
.style("opacity", function(d) { return kx * d.dx > d.w ? 1 : 0; });
node = d;
d3.event.stopPropagation();
}
}
`
Basically it is working fine if I load the data from a csv file stored in my system, but I want to read an array of objects from the server and then build the graph on it.
Basically here's my function which reads from the file and parses the JSON objects:
d3.json(path_to_data, function(data) {
/*console.log("data");
console.log(data);
console.log("data");
data = JSON.parse(inputData);
console.log(data);*/
node = root = data;
var nodes = treemap.nodes(root)
.filter(function(d) { return !d.children; });
var cell = svg.selectAll("g")
.data(nodes)
.enter().append("svg:g")
.attr("class", "cell")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.on("click", function(d) { return zoom(node == d.parent ? root : d.parent); });
cell.append("svg:rect")
.attr("width", function(d) { return d.dx - 1; })
.attr("height", function(d) { return d.dy - 1; })
.style("fill", function(d) { return color(d.parent.name); });
cell.append("svg:text")
.attr("x", function(d) { return d.dx / 2; })
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; })
.style("opacity", function(d) { d.w = this.getComputedTextLength(); return d.dx > d.w ? 1 : 0; });
d3.select(window).on("click", function() { zoom(root); });
d3.select("select").on("change", function() {
treemap.value(this.value == "size" ? size : count).nodes(root);
zoom(node);
});
});
But I want to do something different like
node = root = inputdata ; here input data is array of json objects fetched from server
var nodes = treemap.nodes(root).filter(function(d) { return !d.children; });
var cell = svg.selectAll("g")
i figured the solution to this just remove the d3.csv function ( but don't remove the body of function as your graph will generate with the body of functions only) and pass your own variable conatining the JSON objects as required by the graphs type. This will work in approximately all graphs in which data is taken through d3.csv or d3.json here's a working code
$rootScope.loadTreeMap = function(path_to_data,dom_element_to_append_to){
var w = $(dom_element_to_append_to).width() - 80,
h = 800 - 180,
x = d3.scale.linear().range([0, w]),
y = d3.scale.linear().range([0, h]),
color = d3.scale.category20c(),
root,
node;
console.log("W" + w);
console.log("h " + h);
var treemap = d3.layout.treemap()
.round(false)
.size([w, h])
.sticky(true)
.value(function(d) { return d.size; });
var svg = d3.select(dom_element_to_append_to).append("div")
.attr("class", "chart")
.style("width", w + "px")
.style("height", h + "px")
.append("svg:svg")
.attr("width", w)
.attr("height", h)
.append("svg:g")
.attr("transform", "translate(.5,.5)");
/* d3.json(path_to_data, function(data) {*/
remove the above line and insert your own JSON object variable like
data = inputData(your own JSON variable)
node = root = data;
var nodes = treemap.nodes(root)
.filter(function(d) { return !d.children; });
var cell = svg.selectAll("g")
.data(nodes)
.enter().append("svg:g")
.attr("class", "cell")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.on("click", function(d) { return zoom(node == d.parent ? root : d.parent); });
cell.append("svg:rect")
.attr("width", function(d) { return d.dx - 1; })
.attr("height", function(d) { return d.dy - 1; })
.style("fill", function(d) { return color(d.parent.name); });
cell.append("svg:text")
.attr("x", function(d) { return d.dx / 2; })
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; })
.style("opacity", function(d) { d.w = this.getComputedTextLength(); return d.dx > d.w ? 1 : 0; });
d3.select(window).on("click", function() { zoom(root); });
d3.select("select").on("change", function() {
treemap.value(this.value == "size" ? size : count).nodes(root);
zoom(node);
});
});
function size(d) {
return d.size;
}
function count(d) {
return 1;
}
function zoom(d) {
var kx = w / d.dx, ky = h / d.dy;
x.domain([d.x, d.x + d.dx]);
y.domain([d.y, d.y + d.dy]);
var t = svg.selectAll("g.cell").transition()
.duration(d3.event.altKey ? 7500 : 750)
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
t.select("rect")
.attr("width", function(d) { return kx * d.dx - 1; })
.attr("height", function(d) { return ky * d.dy - 1; })
t.select("text")
.attr("x", function(d) { return kx * d.dx / 2; })
.attr("y", function(d) { return ky * d.dy / 2; })
.style("opacity", function(d) { return kx * d.dx > d.w ? 1 : 0; });
node = d;
d3.event.stopPropagation();
}
}

Prevent loop in D3js Sankey chart

I'm trying to create a sankey chart using the d3 sankey plugin with dynamic shipping data. It works great most of the time except when I get a data set like this:
[{"DeparturePort":"CHARLESTON","ArrivalPort":"BREMERHAVEN","volume":5625.74},{"DeparturePort":"CHARLESTON","ArrivalPort":"ITAPOA","volume":2340},{"DeparturePort":"PT EVERGLADES","ArrivalPort":"PT AU PRINCE","volume":41.02},{"DeparturePort":"BREMERHAVEN","ArrivalPort":"CHARLESTON","volume":28}]
The key to my issue is the first and last entry in the data set. It seems that having opposite directions in the same sankey chart sends the javascript into an infinite loop and kills the browser. Any ideas on how to prevent this from happening?
Here's my chart code where raw would be the object above:
var data = raw;
var units = "Volume";
var margin = { top: 100, right: 0, bottom: 30, left: 0 },
width = $("#"+divID).width() - margin.left - margin.right,
height = divID == "enlargeChart" ? 800 - margin.top - margin.bottom : 600 - margin.top - margin.bottom;
var formatNumber = d3.format(",.0f"), // zero decimal places
format = function (d) { return ""; },
color = d3.scale.ordinal()
.range(["#0077c0", "#FF6600"]);
// append the svg canvas to the page
var svg = d3.select("#"+divID).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.style("font-size", "12px")
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Set the sankey diagram properties
var sankey = d3.sankey(width)
.nodeWidth(10)
.nodePadding(10)
.size([width, height]);
var path = sankey.link();
// load the data (using the timelyportfolio csv method)
//d3.csv("sankey.csv", function (error, data) {
//set up graph in same style as original example but empty
graph = { "nodes": [], "links": [] };
var checklist = [];
data.forEach(function (d) {
if ($.inArray(d.DeparturePort, checklist) == -1) {
checklist.push(d.DeparturePort)
graph.nodes.push({ "name": d.DeparturePort });
}
if ($.inArray(d.ArrivalPort, checklist) == -1) {
checklist.push(d.ArrivalPort)
graph.nodes.push({ "name": d.ArrivalPort });
}
graph.links.push({
"source": d.DeparturePort,
"target": d.ArrivalPort,
"value": +d.volume
});
});
// return only the distinct / unique nodes
graph.nodes = d3.keys(d3.nest()
.key(function (d) { return d.name; })
.map(graph.nodes));
// loop through each link replacing the text with its index from node
graph.links.forEach(function (d, i) {
graph.links[i].source = graph.nodes.indexOf(graph.links[i].source);
graph.links[i].target = graph.nodes.indexOf(graph.links[i].target);
});
//now loop through each nodes to make nodes an array of objects
// rather than an array of strings
graph.nodes.forEach(function (d, i) {
graph.nodes[i] = { "name": d };
});
sankey
.nodes(graph.nodes)
.links(graph.links)
.layout(32);
// add in the links
var link = svg.append("g").selectAll(".link")
.data(graph.links)
.enter().append("path")
.attr("class", "link")
.attr("d", path)
.style("stroke-width", function (d) { return Math.max(1, d.dy); })
.sort(function (a, b) { setTimeout(function () { return b.dy - a.dy; }, 10);});
// add the link titles
link.append("title")
.text(function (d) {
return d.source.name + " → " +
d.target.name + "\n" + d.value.toFixed(0) + " TEU";
});
$("#" + divID + " .loading").addClass("hide");
// add in the nodes
var node = svg.append("g").selectAll(".node")
.data(graph.nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function (d) {
//setTimeout(function () {
return "translate(" + d.x + "," + d.y + ")";
//}, 10);
})
.call(d3.behavior.drag()
.origin(function (d) { return d; })
.on("dragstart", function () {
this.parentNode.appendChild(this);
})
.on("drag", dragmove));
// add the rectangles for the nodes
node.append("rect")
.attr("height", function (d) { if (d.dy < 0) { d.dy = (d.dy * -1); } return d.dy; })
.attr("width", sankey.nodeWidth())
.style("fill", function (d) {
return d.color = color(d.name);
})
.style("stroke", function (d) {
return d3.rgb(d.color);
})
.append("title")
.text(function (d) {
return d.name + "\n" + format(d.value);
});
// add in the title for the nodes
node.append("text")
.attr("x", -6)
.attr("y", function (d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "end")
.style("stroke", function (d) { return "#000000" })
.attr("transform", null)
.text(function (d) { return d.name; })
.filter(function (d) { return d.x < width / 2; })
.attr("x", 6 + sankey.nodeWidth())
.attr("text-anchor", "start");
// the function for moving the nodes
function dragmove(d) {
d3.select(this).attr("transform",
"translate(" + d.x + "," + (
d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))
) + ")");
sankey.relayout();
link.attr("d", path);
}
}, 0)
It's an issue with the sankey.js script.
See this commit (on a fork of sankey.js) which fixed it:
https://github.com/soxofaan/d3-plugin-captain-sankey/commit/0edba18918aac3e9afadffd4a169c47f88a98f81
while (remainingNodes.length) {
becomes:
while (remainingNodes.length && x < nodes.length) {
That should prevent the endless loop.

Categories