Skip to content Skip to sidebar Skip to footer

Convert D3.js Bubbles Into Forced/gravity Based Layout

I have a set of data that I am visualizing using d3.js. I am representing data points in the form of bubbles, where the configuration for bubbles is as follows: var dot = svg.selec

Solution 1:

I think you were almost there but the specification of your dot variable is not the best one. I would transform it like this:

var dot = svg.selectAll(".dot")
        .data(data)
        .enter()

Afterwards, once the circles have been plotted, what you do is that you create a force layout, instantiate it with the nodes you just created, add a on("tick") method, and then start the layout. An example is the following:

var force = d3.layout.force().nodes(data).size([width, height])
            .gravity(0)
            .charge(0)
            .on("tick", function(e){
                dot
                .each(gravity(.2 * e.alpha))
                    .each(collide(.5))
                    .attr("cx", function (d) {return d.x;})
                    .attr("cy", function (d) {return d.y;});
            })
            .start();

To have a complete answer, I will add also the gravity and collide methods from your fiddle (with adjusted variable names)

functiongravity(alpha) {
        returnfunction (d) {
            d.y += (d.cy - d.y) * alpha;
            d.x += (d.cx - d.x) * alpha;
        };
    }   

    functioncollide(alpha) {
        var padding = 6var quadtree = d3.geom.quadtree(dot);
        returnfunction (d) {
            var r = d.r + radiusp.domain()[1] + padding,
                nx1 = d.x - r,
                nx2 = d.x + r,
                ny1 = d.y - r,
                ny2 = d.y + r;
            quadtree.visit(function (quad, x1, y1, x2, y2) {
                if (quad.point && (quad.point !== d)) {
                    var x = d.x - quad.point.x,
                        y = d.y - quad.point.y,
                        l = Math.sqrt(x * x + y * y),
                        r = d.r + quad.point.r + (d.color !== quad.point.color) * padding;
                    if (l < r) {
                        l = (l - r) / l * alpha;
                        d.x -= x *= l;
                        d.y -= y *= l;
                        quad.point.x += x;
                        quad.point.y += y;
                    }
                }
                return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
            });
        };
    }

I think the problem you had was that perhaps you were applying the force layout to the g element of each of the circles, which unfortunately was not working. I hope this will give you an idea how to proceed. Your last line of the dot declaration was adding a g element for each circle, which was a little difficult to handle.

Thanks.

PS I assume that the x, y, and r attributes of your data contain the x,y, and radius.

Post a Comment for "Convert D3.js Bubbles Into Forced/gravity Based Layout"