JSFiddle - React, Tailwind, and code Playground
HTML
<html>
<body>
<div id = 'chart'></div>
</body>
</html>
JavaScript
var width = 900, height = 500;
var groupList = ['Group A', 'Group B', 'Group C', 'Group D'];
var data = d3.range(200).map(d => ({id: d, group: groupList[getRandomIntegerInRange(0, 3)], size: getRandomIntegerInRange(1, 100), total: getRandomIntegerInRange(1, 10)}))
var svg = d3.select("#chart")
.append("svg")
.attr("viewBox", "0 0 " + (width) + " " + (height))
.attr("preserveAspectRatio", "xMidYMid meet")
.attr('width', "100%")
.attr('height', height)
.attr('id', 'svg')
.append('g')
.attr('id', 'container')
.attr('transform', 'translate(' + 0 + ', ' + 0 + ')');
simulation = d3.forceSimulation();
data.forEach(function(d, i){
d.radius = Math.sqrt(d['size']);
});
colorScale = d3.scaleOrdinal(d3.schemeCategory10);
node = svg.append("g")
.attr("class", "node")
.selectAll(".bubble")
.data(data, function(d){ return d.id; })
.enter().append("circle")
.attr('class', 'bubble')
.attr('r', function(d){ return d.radius; }) // INITIALIZED RADII TO 0 HERE
.attr("fill", function(d) {
// initially sets node colors
return colorScale(d.group);
})
.attr('stroke-width', 0.5)
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
function dragstarted(d) {
if (!d3.event.active) {
simulation.alpha(.07).restart()
}
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alpha(0.07).restart()
d.fx = null;
d.fy = null;
// Update and restart the simulation.
simulation.nodes(data);
}
simulation
.nodes(data)
.force("x",...