2

How to create custom layout in d3.js ?

Any links or examples would help

I don't want standard layouts d3 uses , want to write my own .

khan
  • 117
  • 10
  • 2
    You may find this [link](http://stackoverflow.com/questions/13292573/creating-a-custom-d3-layout) helpful – Gilsha Feb 13 '15 at 09:45
  • 1
    If his answer works, you should mark it complete, or comment as to why not it does not satisfy your question. – Core May 06 '15 at 20:13

1 Answers1

13

A layout function could be a simple function that assign coordinates (and any additional data for the drawing like startAngle, endAngle, ...) to your data, and then return an array for the list of nodes. A quick example:

function myLayout(data) {
   var nodes = [];   // or reuse data directly depending on layout
   // for each element of data, assign a x,y coordinate)
   return nodes;
}

var nodes = myLayout(myData);
var g = d3.selectAll('g.node').data(nodes);
g.enter().append('g').attr('class', 'node');
g.attr('transform', function(d) {
   return 'translate(' + d.x + ',' + d.y + ')'});

This is the basic bare bone approach. If you want to follow d3's own code structure, the layout would return a function that does the same as above, but has additional functions to configure it:

function myLayout() {
   var space = 1;
   function compute(data) {
       // same as before
   }
   compute.space = function(s) {
       if (!arguments.length) return space;
       space = s;
       return this;   // chaining
   }
   return compute;
}
var layout = myLayout().space(10);
var nodes = layout(myData);
...
Damien Fayol
  • 948
  • 7
  • 16
manuBriot
  • 2,675
  • 10
  • 21