D3.js - How to prevent overlapping circles and text?

For each json a circle is created and x and y are arbitrarily set

for(var d = 0; d<json.length; d++){ circlexloc[d] = ((Math.random()*2*r)-r); circleyloc[d] = ((Math.random()*2*r)-r); }; 

Declaring an environment variable when setting attributes and animations

 var circle = svg.selectAll("circle").data(json) circle.enter().append('circle') 

Animation

 circle.transition() .duration(1000) .attr("fill", "blue") .attr('opacity',0.6) .attr('r', 5) .attr("cx", function(d, i) {return circlexloc[i] }) .attr("cy", function(d, i) {return circleyloc[i] }); circle.exit().transition().duration(1000) .attr('opacity',0) .attr("r",0) .remove(); 

Attach technology to circles

  var text = svg.selectAll('text') text.data(json) .enter().append("svg:text") .style("font-size", "10px") .text(function(d) { return d.TechName; }) .transition().duration(1000) .attr('opacity', 1) .attr("x", function (d, i) { return (circlexloc[i]+6)}) .attr("y", function (d, i) { return (circleyloc[i]+4)}); 

});

Currently, they tend to bend each other. How can I prevent this? Suggestions and examples will be appreciated - thanks.

+4
source share
1 answer

You have several different options, depending on what exactly you are going to do.

One way is to use a force-oriented layout that applies forces to the nodes to make sure that they do not overlap after reaching a steady state (note that they can overlap as they reach a steady state). You can see an example of this at http://bl.ocks.org/1377729 . Note that you can fully customize how the nodes look and exclude rows.

I created an example of a forced layout at http://jsfiddle.net/xwZjN/2/ . With a force-based layout, you need to add nodes first.

  force .nodes(nodes) .start(); 

And then update your locations for each force recount.

  force.on("tick", function() { text.attr("x", function(d) { return dx + 6; }) .attr("y", function(d) { return dy + 4; }); node.attr("cx", function(d) { return dx; }) .attr("cy", function(d) { return dy; }); }); 

Another option is to use the pack layout, for example, the example http://bl.ocks.org/1628131 . This arrangement will pack circles tightly and ensure that they do not overlap.

+6
source

Source: https://habr.com/ru/post/1440414/


All Articles