Published
Edited
Sep 6, 2021
1 star
Insert cell
Insert cell
Insert cell
Insert cell
chart = {
const mainnodes = root.descendants().filter((d) => d.height == 1);

const widthBand = d3.sum(mainnodes, (d) => d.r * 2 + widthPadding);

const stdY = height / 2;

const rScale = d3.scaleLinear().domain([0, widthBand]).range([0, width]);

const gScale = d3
.scalePoint()
.padding(0.5)
.domain(d3.map(mainnodes, (d) => d.data.name))
.range([0, width]);

const svg = d3
.create("svg")
.attr("viewBox", [0, 0, width, height])
.style("font", "10px sans-serif")
.attr("text-anchor", "middle");

const node = svg
.selectAll("g")
.data(root.descendants().filter((d) => d.height == 1))
.join("g")
.attr("transform", (d) => `translate(${gScale(d.data.name)},${stdY})`);

const innerNodes = node
.selectAll("circle")
.data((d) => d.children)
.join("circle")
.attr("r", (d) => rScale(d.r))
.attr("fill", (d) => colorScale(d.data.name))
.attr("cx", (d) => rScale(d.x - d.parent.x))
.attr("cy", (d) => rScale(d.y - d.parent.y));

const gAxis = svg
.append("g")
.call(d3.axisBottom(gScale))
.call((g) => g.select(".domain").remove());

gAxis.attr("transform", `translate(0, ${height - margin.bottom})`);

return svg.node();
}
Insert cell
colorScale = d3.scaleOrdinal(unique_values, d3.schemeCategory10)
Insert cell
unique_values = {
const names = new Set();
root.each((d) => (d.height == 0 ? names.add(d.data.name) : null));
return names;
}
Insert cell
root = pack(data)
Insert cell
pack = data =>
d3
.pack()
.size([width - 2, height - 2])
.padding(3)(
d3
.hierarchy(data)
.sum(d => d.value)
.sort((a, b) => b.value - a.value)
)
Insert cell
data = ({
name: 'All',
children: [
{
name: 'Group 1',
children: [
{ name: 'a1', value: 23 },
{ name: 'a2', value: 12 },
{ name: 'a3', value: 2 },
{ name: 'a4', value: 42 },
{ name: 'a5', value: 6 }
]
},
{
name: 'Group 2',
children: [
{ name: 'a1', value: 2 },
{ name: 'a2', value: 57 },
{ name: 'a3', value: 7 },
{ name: 'a4', value: 12 },
{ name: 'a5', value: 1 }
]
},
{
name: 'Group 3',
children: [
{ name: 'a1', value: 44 },
{ name: 'a2', value: 12 },
{ name: 'a3', value: 4 },
{ name: 'a4', value: 22 },
{ name: 'a5', value: 17 }
]
},
{
name: 'Group 4',
children: [
{ name: 'a1', value: 3 },
{ name: 'a2', value: 3 },
{ name: 'a3', value: 23 },
{ name: 'a4', value: 2 },
{ name: 'a5', value: 45 }
]
}
]
})
Insert cell
widthPadding = 15
Insert cell
margin = ({
bottom: 20
})
Insert cell
Insert cell
Insert cell
import { swatches } from "@d3/color-legend"
Insert cell
d3 = require("d3@6")
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