Skip to content Skip to sidebar Skip to footer

Force Simulation Of Texts On Bubble-chart Does Not Work

I have a script in which I make circles and then append text to them. I want to use force simulation so that texts of different circles don't overlap. The issue that I am currentl

Solution 1:

It's very hard to provide a working answer without seeing your data or a minimum running code. But some mistakes are obvious, and this is a general solution:

First, you have to specify the positions you want for the texts in the forceY and forceX functions:

simulation = d3.forceSimulation()
    .force("x", d3.forceX(function(d) {
        returnxscale(+d.student_percentile);
    }))
    .force("y", d3.forceY(function(d) {
        returnyscale(+d.rank);
    }))
    .force("collide", d3.forceCollide(20)); 

Then, in the tick function, you just use the x and y properties created by the simulation:

simulation.nodes(data).on("tick", function() {
    texts.attr("x", function(d) {
            return d.x;
        })
        .attr("y", function(d) {
            return d.y;
        });
});

Post a Comment for "Force Simulation Of Texts On Bubble-chart Does Not Work"