Kevin Waterson Kevin Waterson - 1 year ago 74
JSON Question

How to use JSON file with Cluster Force

I wish to use Cluster Force Layout as described by Mike here:

The example works fine for me, however, the problem is when I change the data source to a JSON file, which uses a different cluster name, things stop working. No errors, but does not display.

The goal is to group the names in each division into a cluster.

The JSON file is in the html... not sure if you can upload data for jsfiddle

Any direction here much appreciated.


This is where I try to recreate the nodes. The nodes appear in console.log, but never make it to the screen.

var nodes = d3.json("/r.json", function(error, data) {

for (var i = 0; i < data.length; i++) {
var obj = data[i];
for (var key in obj){
var rating = obj['rating']; // rating
var r = rating * 20; // radius
var n = obj['name']; // name
var div = obj['division']; // division
// d = {cluster: div, radius: r, name: n, division: div, rating: rating};
d = {cluster: div, radius: r};
// console.log(key+"="+obj[key]);
if (!clusters[i] || (r > clusters[i].radius)) clusters[i] = d;
// console.log(d);
return d;


Answer Source

First, you can use plunkr to add json file if you want to play with extra data file.
Second, I copied your code from fiddle to plunkr with json file, the console.log(nodes) didn't print out the data, it's because the code retrieving data here:

var nodes = d3.json("/r.json", function(error, data) {...})

is not exactly the same as in the example, because this is asynchronous request, so this line of code won't work:

var force = d3.layout.force()
.nodes(nodes) // data for nodes is not retrieved yet

Third, after I put d3 code into the request callback, there is circles in svg but not visible, I think it is because of the svg size setting (width, height) is not quite fit for the cx, cy of the circles, so I changed the svg to a smaller size, and it's visible. It depends on what you want to achieve at the end, but adjusting the position parameter for the circles can be helpful.

Working plunkr here. Hope this can help.