Published
Edited
Dec 23, 2020
Insert cell
md`# Force Directed Bubble Chart`
Insert cell
chart = {
const root = pack(data);
console.log(root);
const simulation = d3
.forceSimulation(root.leaves())
.force("x", d3.forceX(width / 2).strength(0.5))
.force("y", d3.forceY(height / 2).strength(0.5))
.force('charge', d3.forceManyBody().strength(500))
.force(
"collision",
d3
.forceCollide()
.radius(function(d) {
return d.r + 2;
})
.strength(0.8)
);

const svg = d3
.create("svg")
.attr("width", width)
.attr("height", height)
.attr("font-size", 18)
.attr("font-family", "OpenSans")
.attr("font-weight", "bold")
.attr("text-anchor", "middle");

const leaf = svg
.selectAll("g")
.data(root.leaves())
.join("g")
.attr("transform", d => `translate(${d.x + 1},${d.y + 1})`);

leaf
.append("circle")
.attr("r", d => d.r)
.attr("fill-opacity", 0.5)
.attr("fill", d => d.data.color);

leaf
.append("text")
.attr("fill", d => d.data.color)
.selectAll("tspan")
.data(d => d.data.title.split(/(?=[A-Z][^A-Z])/g))
.join("tspan")
.attr("x", 0)
.attr("y", (d, i, nodes) => `${i - nodes.length / 2 + 0.8}em`)
.text(d => d);

simulation.on("tick", () => {
console.log(root.leaves());
leaf.attr("transform", d => `translate(${d.x + 1},${d.y + 1})`);
});

invalidation.then(() => simulation.stop());

return svg.node();
}
Insert cell
data=[
{
name: "Lack of Legal Protection",
title: "Lack of Legal Protection",
color: "#2E86C1",
value: 100,
},
{
name: "Poverty",
title: "Poverty",
color: "#229954",
value: 29,
},
{
name: "Stigma, Harassment & Discrimination",
title: "Stigma, Harassment & Discrimination",
color: "#AAB7B8",
value: 100,
},
{ name: "Violence", title: "Violence",color: "#E74C3C", value: 54 },
{ name: "Lack of Health Coverage", title: "Lack of Health Coverage",color: "#F4D03F", value: 22 },
{ name: "Inaccurate ID Documents", title: "Inaccurate ID Documents",color: "#884EA0", value: 50 },
]
Insert cell
pack = data => d3.pack()
.size([width , height ])
(d3.hierarchy({children: data})
.sum(d => {
console.log(d)
return d.value})
.sort((a, b) => b.value - a.value))
Insert cell
height =400
Insert cell
d3 = require("d3@5")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more