chart = {
var svg = d3.create("svg")
.attr("viewBox", [100, 100, width/2, height/2]);
const simulation = d3.forceSimulation(data)
.force('surface', function(){
cells.each(function(d){
d.surface = Math.sqrt(
d.children.map(function(t){
return t.length * t.length;
})
.reduce(function(a,b){
return a + b;
}, 0) / d.children.length);
})
})
.force('colidecell', function(){
cells.each(function(d){
var p1 = d.r + buffer;
d.polygon = d.children.map(function(t){
return [d.x + p1 * t.length * t.sin, d.y - p1 * t.length * t.cos];
});
});
var quadtree = d3.quadtree(data, d=>d.x, d=>d.y);
var collisions = 0;
cells.each(function(d,i){
quadtree.visit(function(node, x0, y0, x1, y1){
var p = node.data;
if (!p) return;
if (p.id == d.id) return;
var dx = p.x - d.x,
dy = p.y - d.y,
dist2 = dx*dx + dy*dy;
if (dist2 > 4 * (d.r + p.r) * (d.r + p.r)) return;
var stress = 0;
d.children.forEach(function(t){
var txy = [d.x + d.r * t.length * t.sin, d.y + d.r * t.length * t.cos];
var collisions = 0;
if (d3.polygonContains(p.polygon, txy)) {
collisions ++;
stress++;
t.length /= 1.05;
var tens = d.surface / p.surface,
f = 0.1 * (stress > 2 ? 6 : 1);
d.vx += f * Math.atan((d.x - p.x) * tens);
d.vy += f * Math.atan((d.y - p.y) * tens);
p.vx -= f * Math.atan((d.x - p.x) / tens);
p.vy -= f * Math.atan((d.y - p.y) / tens);
}
})
})
})
})
.force('y', d3.forceY().strength(function(d,i){return i < 60? 0.05 : 0.01}).y(-50))
.force('move', function(){
cells.each(function(d){
d.x += Math.random()-0.5;
d.y += Math.random()-0.5;
})
})
let cells = svg.append("g")
.attr('transform', 'translate(300,250)')
.selectAll('g.cell')
.data(simulation.nodes())
.enter()
.append('g')
.classed('cell', true)
.attr('transform', function (d) {
return 'translate(' + [d.x, d.y] + ')'
})
.attr("opacity",0.5);
let paths = cells
.append('path')
.attr('fill', function (d,i){
return color(i)
})
.attr('d', function (d) {
var arc = 2 * Math.PI / d.children.length,
data = d.children
.map(function (t, i) {
return [i * arc, d.r * t.length];
})
return line(data);
})
.attr("stroke","black")
.attr("stroke-width",1);
cells.each(function(d,i){
let currentCell = d3.select(this);
let data = d.children;
currentCell.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx",function(t){return (d.r + buffer) * t.length * t.sin})
.attr("cy",function(t){return (d.r + buffer) * t.length * t.cos})
.attr("r",1)
.attr('fill', color(i))
.attr("opacity",1)
});
let tickcount = 0
simulation.on("tick",function(d) {
tickcount++
cells.attr('transform', function (d) {
return 'translate(' + [d.x, d.y] + ')'
});
paths.attr('d', function (d) {
var arc = 2 * Math.PI / d.children.length,
data = d.children.map(function (t, i) {
return [i * arc, d.r * t.length];
});
return line(data);
});
cells.each(function(d){
d3.select(this)
.selectAll("circle")
.attr("cx",function(t){return (d.r + buffer) * t.length * t.sin})
.attr("cy",function(t){return (d.r + buffer) * t.length * t.cos})
})
})
return svg.node()
}