Public
Edited
Jul 2, 2023
1 fork
4 stars
Insert cell
Insert cell
chart = {
// Specify the dimensions of the chart.
const width = 2000;
const height = width;
const margin = 1; // to avoid clipping the root circle stroke

// Specify the number format for values.
const format = d3.format(",d");

// Create the pack layout.
const pack = d3.pack()
.size([width - margin * 2, height - margin * 2])
.padding(3);

// Compute the hierarchy from the JSON data; recursively sum the
// values for each node; sort the tree by descending value; lastly
// apply the pack layout.
const root = pack(d3.hierarchy(rollup)
.sum(([, value]) => value)
.sort((a, b) => b.value - a.value));

// Create the SVG container.
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [-margin, -margin, width, height])
.attr("style", "width: 100%; height: auto; font: 10px sans-serif;")
.attr("text-anchor", "middle");

// Place each node according to the layout’s x and y values.
const node = svg.append("g")
.selectAll()
.data(root.descendants())
.join("g")
.attr("transform", d => `translate(${d.x},${d.y})`);

// Add a title.
node.append("title")
.text(n => `${n.depth
? `${n.ancestors().reverse().slice(1).map(({data: [key]}) => key).join("\n")}\n`
: ""}${n.value.toLocaleString("en")}`
);

// Add a filled or stroked circle.
node.append("circle")
.attr("fill", d => d.children ? "#fff" : "#ddd")
.attr("stroke", d => d.children ? "#bbb" : null)
.attr("r", d => d.r);

// Add a label to leaf nodes.
const text = node
.filter(d => !d.children && d.r > 10)
.append("text")
.attr("clip-path", d => `circle(${d.r})`);

// Add a tspan for each word.
text.selectAll()
.data(d => d.data[0]?.split(/\s+/g) ?? [])
.join("tspan")
.attr("x", 0)
.attr("y", (d, i, nodes) => `${i - nodes.length / 2 + 0.35}em`)
.text(d => d);

return svg.node();
}
Insert cell
rollup = d3.rollup(
h1bs,
D => d3.sum(D, d => d["Initial Approvals"] + d["Initial Denials"] + d["Continuing Approvals"] + d["Continuing Denials"]),
d => d.State,
d => d.City,
d => d.Employer,
)
Insert cell
h1bs = FileAttachment("h1b_datahubexport-2019.csv").csv({typed: true})
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more