I'd like to do something a little bit out of the ordinary with force layouts (for visualizing graphs). Constellations and all are fun to look at, but for timeseries data, it's not that helpful. I'd like to be able to constrain the layout by some axis, for example, by laying out the nodes according to the time they appear in a dataset, while still retaining the "bouncyness" of the visualization. Is this possible using d3?
Asked
Active
Viewed 4,246 times
2 Answers
10
To elaborate on my comment, yes, this is perfectly possible. The force layout does not in fact position the nodes itself, it merely computes the positions. In the handler of the tick
event you usually provide the function that takes care of the positioning. There, you can add arbitrary constraints that restrict how the nodes can move.
Taking one of the stock examples, you could do things like the following to restrict the x coordinate to within +-10 of the intended position with unrestricted y.
force.on("tick", function() {
node.each(function(d) {
var intended = scale(d.value);
d.x = d.px = Math.min(intended + 10, Math.max(intended - 10, d.px));
});
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
Here is another example that uses the force layout to position labels. There, the x position is ignored (i.e. constant) and only the y is affected by the layout.

Lars Kotthoff
- 107,425
- 16
- 204
- 204
-
Thank you, Lars! Can I ask, is: `var intended = scale(d.value)` supposed to be replaced by `var xpos = scale(d.date)` in my case, where datetime is the value on which I wish to put on my x-axis? – ericmjl Dec 26 '13 at 18:14
-
1You haven't posted any code so I don't know what your variables are called but yes, this would designate the x position. – Lars Kotthoff Dec 26 '13 at 22:18
-
Thank you Lars! I was just able to test it out after fixing some other bugs in my code, and it works provisionally! Now to modify the scales to make sure it works properly. :-) Thanks again! – ericmjl Dec 26 '13 at 22:28
2
Webcola is a great tool for creating constraint-based layouts with D3.JS.

Ian Mercer
- 38,490
- 8
- 97
- 133
-
Agreed, ***but*** beware of [WebCola Missing documentation](https://stackoverflow.com/questions/33889372/webcola-missing-documentation) – Mawg says reinstate Monica Jan 22 '21 at 19:10